This is the fist post on the new web server. After few hours work, finally I manged to move Nick’s Lounge to the new web server. It will give more bandwidth and more disk space.
Resize photo in C#
Today, my friend asked me to recommend a free resize photo tool, and he got lots of photos. I really don’t know. Normally I use MS Paint and select Stretch and Skew. If here are many photos, it would take ages. I then wrote a small tool for him using C#. The code is fairly simple cause .Net Framework provides huge library to use.
private void ResizePhoto()
{
//find all jpg photos in given folder
string[] jpgFiles = Directory.GetFiles(photoPath,"*.jpg");
foreach(string file in jpgFiles)
{
//load orignial photo into memory
Image image = Image.FromFile(file);
//create new photo using new size from original photo
Image newImage = new Bitmap(image,new Size(newWidth,newHeight));
//give a new file name
string newFileName = "newsize" + file;
//save new photo
newImage.Save(newFileName,System.Drawing.Imaging.ImageFormat.Jpeg);
newImage.Dispose();
image.Dispose();
}
}
Santa’s coming
Christmas is coming. The Christmas atmosphere is everywhere in Sydney.
Add watermark in your photo using C#
Some of my photos need to be added watermark to prevent abusing. I just found a easy way to add watermark into your photo using C#. Here is the code to share.
private void button1_Click(object sender, System.EventArgs e)
{
OpenFileDialog of = new OpenFileDialog();
of.Filter = "Image Files (*.bmp;*.emf;*.exif;*.gif;*.jpg;*.png;*.tif;*.wmf)|*.bmp;*.emf;*.exif;*.gif;*.jpg;*.png;*.tif;*.wmf";
if(of.ShowDialog(this) == DialogResult.OK)
{
Image image = Image.FromFile(of.FileName);
Graphics g = Graphics.FromImage(image);
// Create a solid brush to write the watermark text on the image
Brush myBrush = new SolidBrush(Color.Black);
Font myFont = this.Font;
// Calculate the size of the text
SizeF sz = g.MeasureString("http://www.nickdu.com", myFont);
// drawing position (X,Y)
float X =(image.Width - sz.Width)/2f;
float Y = image.Height/2f;
g.DrawString("http://www.nickdu.com",myFont,myBrush,X,Y);
SaveFileDialog sf = new SaveFileDialog();
sf.Filter = of.Filter;
if(sf.ShowDialog(this) == DialogResult.OK)
{
image.Save(sf.FileName);
}
image.Dispose();
}
}
This is the sample

Build your own network usage monitor in C# (raw socket)
Although there are lots of excellent network monitor available, e.g NetWorx, DU Meter, I just think to build my own network monitor. Firstly I can explore the socket programming, secondly it’s free of charge.
OK, let’s do it.
Create a new WinForm project from Visual Studio

public MainForm()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// Set your PC ip address
//
rs.CreateAndBindSocket(ipaddress);
rs.Run();
}
//when main window showing up, we update meter text
private void ShowMainWindow(object sender, System.EventArgs e)
{
todayUsage.Text = string.Format("Today's Usage: {0}",FormatSize((ulong)rs.TotalReceivedBytes));
}
//define ip header
[StructLayout(LayoutKind.Explicit)]
public struct IPHeader
{
[FieldOffset(0)] public byte ip_verlen;
[FieldOffset(1)] public byte ip_tos;
[FieldOffset(2)] public ushort ip_totallength;
[FieldOffset(4)] public ushort ip_id;
[FieldOffset(6)] public ushort ip_offset;
[FieldOffset(8)] public byte ip_ttl;
[FieldOffset(9)] public byte ip_protocol;
[FieldOffset(10)] public ushort ip_checksum;
[FieldOffset(12)] public uint ip_srcaddr;
[FieldOffset(16)] public uint ip_destaddr;
}
//the core function - raw socket
public class RawSocket
{
private bool error_occurred;
private int totalReceivedBytes = 0;
private const int BUFFER_SIZE = 8192;
private byte [] receive_buf = new byte[BUFFER_SIZE];
private Socket socket = null;
const int SIO_R = unchecked((int)0x98000001);
const int SIO_1 = unchecked((int)0x98000002);
const int SIO_2 = unchecked((int)0x98000003);
public int TotalReceivedBytes
{
get {return totalReceivedBytes;}
set {totalReceivedBytes = value;}
}
public RawSocket()
{
error_occurred=false;
}
public void CreateAndBindSocket(string IP)
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
socket.Blocking = false;
socket.Bind(new IPEndPoint(IPAddress.Parse(IP), 0));
if (SetSocketOption()==false)
error_occurred=true;
}
public bool ErrorOccurred
{
get { return error_occurred;}
}
public void Shutdown()
{
error_occurred = true;
if(socket != null)
{
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
}
private bool SetSocketOption()
{
bool ret_value = true;
try
{
socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, 1);
byte []IN = new byte[4]{1, 0, 0, 0};
byte []OUT = new byte[4];
int ret_code = socket.IOControl(SIO_R, IN, OUT);
ret_code = OUT[0] + OUT[1] + OUT[2] + OUT[3];
if(ret_code != 0) ret_value = false;
}
catch(SocketException)
{
ret_value = false;
}
return ret_value;
}
unsafe private bool IsInternetTraffic(byte[] buf)
{
byte temp_protocol=0;
uint temp_version=0;
uint temp_ip_srcaddr=0;
string sourceIP;
fixed(byte *fixed_buf = buf)
{
IPHeader * head = (IPHeader *) fixed_buf;
temp_protocol = head->ip_protocol;
temp_version =(uint)(head->ip_verlen & 0xF0) >> 4;
temp_ip_srcaddr = head->ip_srcaddr;
sourceIP = new IPAddress(temp_ip_srcaddr).ToString();
}
//we only capture internet traffic
return !sourceIP.StartsWith("10.")
&& !sourceIP.StartsWith("172.16.")
&& !sourceIP.StartsWith("127.")
&& !sourceIP.StartsWith("192.168.");
}
private void ReceiveCallback( IAsyncResult ar)
{
try
{
int received_bytes = socket.EndReceive(ar);
if(received_bytes>0 && IsInternetTraffic(receive_buf))
{
totalReceivedBytes += received_bytes;
}
}
finally
{
socket.BeginReceive(receive_buf,0,BUFFER_SIZE,SocketFlags.None,new AsyncCallback(ReceiveCallback),null);
}
}
public void Run()
{
socket.BeginReceive(receive_buf,0,BUFFER_SIZE,SocketFlags.None,new AsyncCallback(ReceiveCallback),null);
}
}
Exchange Web Services (EWS) programming with Exchange Server 2010 in C#
I have an application to sniff email notification from Exchange Server and automatically insert data record to SQL database. Because recently our IT department upgraded MS Exchange Server to 2010 and Exchange Server 2010 does not support WebDAV any more, my robust WebDAV program is dead 🙁
To revive my application, I have to migrant WebDAV to EWS, because WebDAV has been replaced by Exchange Web Services (EWS). EWS is relatively new, and there is no too much information I can use. Here to share my EWS programming experience.
private void ReceiveEmail(object sender, EventArgs e)
{
ExchangeServiceBinding esb = new ExchangeServiceBinding();
esb.Credentials = new NetworkCredential(username, password, domain);
ServicePointManager.ServerCertificateValidationCallback =
delegate(Object obj, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
// trust any certificate
return true;
};
esb.Url = @"https://exchangeserver/EWS/Exchange.asmx";
FindItemType findRequest = new FindItemType();
findRequest.ItemShape = new ItemResponseShapeType();
findRequest.ItemShape.BaseShape = DefaultShapeNamesType.AllProperties;
DistinguishedFolderIdType inbox = new DistinguishedFolderIdType();
inbox.Id = DistinguishedFolderIdNameType.inbox;
findRequest.ParentFolderIds = new []{inbox};
findRequest.Traversal = ItemQueryTraversalType.Shallow;
findRequest.ItemShape.BodyType = BodyTypeResponseType.Text;
findRequest.ItemShape.BodyTypeSpecified = true;
FindItemResponseType response = esb.FindItem(findRequest);
FindItemResponseMessageType responseMessage =
response.ResponseMessages.Items[0]
as FindItemResponseMessageType;
ArrayOfRealItemsType items = responseMessage.RootFolder.Item as ArrayOfRealItemsType;
foreach (MessageType item in items.Items)
{
MessageType msg = (MessageType) item;
string emailBody = GetMessageBody(esb, msg);
//delete email
this.DeleteMessage(esb,msg);
}
}
private string GetMessageBody(ExchangeServiceBinding binding, MessageType message)
{
string messageBody = string.Empty;
MessageType temp = null;
// Call GetItem on each ItemId to retrieve the
// item’s Body property and any AttachmentIds.
//
// Form the GetItem request.
GetItemType getItemRequest = new GetItemType();
getItemRequest.ItemShape = new ItemResponseShapeType();
// AllProperties on a GetItem request WILL return
// the message body.
getItemRequest.ItemShape.BaseShape = DefaultShapeNamesType.AllProperties;
getItemRequest.ItemIds = new ItemIdType[1];
getItemRequest.ItemIds[0] = (BaseItemIdType)message.ItemId;
// Here is the call to exchange.
GetItemResponseType getItemResponse = binding.GetItem(getItemRequest);
// We only passed in one ItemId to the GetItem
// request. Therefore, we can assume that
// we got at most one Item back.
ItemInfoResponseMessageType getItemResponseMessage =
getItemResponse.ResponseMessages.Items[0]
as ItemInfoResponseMessageType;
if (getItemResponseMessage != null)
{
if (getItemResponseMessage.ResponseClass ==
ResponseClassType.Success
&& getItemResponseMessage.Items.Items != null
&& getItemResponseMessage.Items.Items.Length > 0)
{
temp = (MessageType)getItemResponseMessage.Items.Items[0];
if (temp.Body != null)
messageBody = temp.Body.Value;
}
}
return messageBody;
}
private void DeleteMessage(ExchangeServiceBinding binding, MessageType message)
{
// Call DeleteItem on each ItemId to delete the message
// Form the DeleteItem request.
DeleteItemType delItemRequest = new DeleteItemType();
delItemRequest.ItemIds = new ItemIdType[1];
delItemRequest.ItemIds[0] = (BaseItemIdType)message.ItemId;
// Here is the call to exchange.
DeleteItemResponseType delItemResponse = binding.DeleteItem(delItemRequest);
}
Tuliptime in Bowral
Bowral is situated 120km south of Sydney. This weekend, it’s her famous Tuliptime festival. We drove 1.5 hours from Sydney along Hume Highway.
Dynamically update parity bit during serial communication in C#
Today boss asked me to implement a serial com port simulator. I used MSCommLib COM library in C# to develop this simulator.
The serial protocol I am working on is a bit strange:
The message synchronization is achieved via a technique utilizing the parity bit of serially of transmitted data. The parity bit sent with each byte no longer denotes the byte’s parity, but the parity bit is used instead to indicate the start of new messages. In this mode, the parity bit is often referred to as the “wake-up bit”. The parity bit is now used in the following manner: when the parity bit is set, this denotes the start (i.e. the first byte) of a new message. , the parity bit (or wake-up bit), is only ever set on the first byte (i.e. the address byte) of a message. The remainder of the message has parity forced to zero.
Therefore, this protocol needs dynamically update the parity bit settings during the message sending. There are many articles about generic serial com programming. However, it’s hard to find the parity bit toggling. After few hours exploring, I found a way to achieve this.
Like other serial protocol, we have to initialize com port
public void InitComPort(int portNumber)
{
// Set the com port to be 1
m_ComPort.CommPort = (short)portNumber;
// This port is already open, close it to reset it.
if (m_ComPort.PortOpen)
m_ComPort.PortOpen = false;
// Trigger the OnComm event whenever data is received
m_ComPort.RThreshold = 1;
//e, Even. m, Mark. m, (Default) None. o, Odd. s, Space
// Set the port to 19200 baud, even parity bit, 8 data bits, 1 stop bit (all standard)
m_ComPort.Settings = "19200,e,8,1";
// Force the DTR line high, used sometimes to hang up modems
m_ComPort.DTREnable = true;
// No handshaking is used
m_ComPort.Handshaking = MSCommLib.HandshakeConstants.comNone;
// Use this line instead for byte array input, best for most communications
m_ComPort.InputMode = MSCommLib.InputModeConstants.comInputModeBinary;
// Read the entire waiting data when com.Input is used
m_ComPort.InputLen = 0;
// Don't discard nulls, 0x00 is a useful byte
m_ComPort.NullDiscard = false;
// Attach the event handler
m_ComPort.OnComm += new MSCommLib.DMSCommEvents_OnCommEventHandler(OnComm);
m_ComPort.ParityReplace = "0";
// Open the com port
m_ComPort.PortOpen = true;
}
Here is the way to toggle the parity bit during sending message
private void SendThread()
{
while(m_ComPort.PortOpen)
{
m_ComPort.PortOpen = false;
// Change port setting, toggle the parity bit to 1
m_ComPort.Settings = "19200,m,8,1";
m_ComPort.PortOpen = true;
m_ComPort.Output = addr;
// wait 10 ms to toggle parity bit
Thread.Sleep(10);
m_ComPort.PortOpen = false;
// Change port setting, toggle the parity bit to 0
m_ComPort.Settings = "19200,s,8,1";
m_ComPort.PortOpen = true;
m_ComPort.Output = packet;
}
}
Edit password protected MS Word document
Some Microsoft Word document has editing restrictions, which is protected by password. If you want to edit the content of the document, you need the password.


What you need to do is to save the document as html format

Open html by using Notepad and delete the password inside of <w:UnprotectPassword> section.

Re-open the document by using MS Word. You can freely edit the Word document without inputting any password.
2011 Australasian Gaming Expo (AGE) at Darling Harbour
Australasian Gaming Expo (AGE) is one of the largest gaming exhibitions in the world. This year it’s from 21 August to 23 August at Sydney Convention and Exhibition Centre.
AGE entrance

Aristocrat show stand


IGT new game theme – Sex and the City

Konami show stand

Shuffle Master show stand

AGT show stand
