This post has been imported from the old blog and has not yet been converted to the new syntax yet.
Next article is one on how to access Outlook from C#.

Gather Addresses collects email addresses from a given folder in Outlook.

This is the second article for my birthday present ;)

Article #3 will be later tonight, have to format a pc and re-install WinXP first.
 
This post has been imported from the old blog and has not yet been converted to the new syntax yet.
For this article I decided to work with Outlook from C#.

I get way too much spam, and not only the commercial kind of spam. But also the jokes crap that 'friends' send you with 40 CC's in.

So here's my idea: We'll write an email gatherer. It'll take a folder and will go trough every mail in it, extract email addresses and save them as a comma delimited file.

Where can we find email addresses in a mail? Well, first of all, the sender. That's one already. Then the recipients of course, all those CC addresses. And lastly the mail itself, all those forwards caused the body to have plenty of addresses as well.

Real usage for this tool? Probably nothing, but you learn to work with Outlook from C# and you can have fun with collecting things, email addresses in this case.

Let's begin. All of this is in a Console App called GatherAddresses.

First we need a reference to Outlook. So add a reference to 'Microsoft Outlook 11.0 Object Library' (or 10.0, if you use 10.0 leave a comment if this source worked for you!)



When you did this you'll have two new reference, just remove the Office Core... so that you have something like this:



Our application has a very simple logic, where the Main controls it all.

[csharp]
using System;
using System.Text.RegularExpressions;
using System.Collections;
using System.IO;
using Outlook = Microsoft.Office.Interop.Outlook;

namespace GatherAddresses {
class GatherAddresses {
static void Main(string[] args) {
// TODO
}
} /* GatherAddresses */
} /* GatherAddresses */
[/csharp]

Our goal is to collect all addresses, and we don't know how many there will be, so we store them in an ArrayList.

[csharp]
private static ArrayList emailCollection = new ArrayList();
[/csharp]

First we ask for a folder. This folder is in the form of a path. Starting from Outlook Today (the root in Outlook) to the folder you want. Example: CumpsD\Inbox would give you my Inbox.

[csharp]
Console.Write("Path to mailfolder: ");
string mailFolder = Console.ReadLine();
[/csharp]

Now we create our Outlook 'connection'.

[csharp]
Outlook._Application appOutlook = new Outlook.Application();

Outlook.NameSpace olNS = appOutlook.GetNamespace("MAPI");
olNS.Logon("", null, null, null);
[/csharp]

We navigate to the given folder with the GetFolder method, we will write later on in this article. This method will return a MAPIFolder which we need to read the Items from.

[csharp]
Console.WriteLine("Searching Folder...");
Outlook.MAPIFolder olMailFolder = GetFolder(mailFolder);
Outlook.Items olMailItems = olMailFolder.Items;
[/csharp]

Next is the real collecting part of our application. We take each MailItem in our folder and save the addresses. To get the addresses from the body we use the GetAddresses method we'll also write later on.

[csharp]
Console.WriteLine("Gathering Addresses...");
foreach(Outlook.MailItem olMail in olMailItems) {
AddAddress(olMail.SenderEmailAddress);
foreach(Outlook.Recipient olRecipient in olMail.Recipients) {
AddAddress(olRecipient.Address);
}
string[] emailAddresses = GetAddresses(olMail.Body);
foreach (string emailAddress in emailAddresses) {
AddAddress(emailAddress);
}
}
[/csharp]

After we have done everything we wanted with Outlook we close it and throw it away.

[csharp]
olNS.Logoff();

olMailItems = null;
olMailFolder = null;
olNS = null;
appOutlook = null;
[/csharp]

And lastly we save the collected addresses.

[csharp]
Console.WriteLine("Sorting & Outputting Addresses...");
SaveAddresses();
[/csharp]

Now onto our private methods:

First the GetFolder method. This will get us our folder we specified with a path.

Again we open Outlook. Then we split the path into the corresponding folders and we look for the root folder.

[csharp]
Outlook._Application appOutlook = new Outlook.Application();
Outlook.NameSpace olNS = appOutlook.GetNamespace("MAPI");
olNS.Logon("", null, null, null);

Outlook.MAPIFolder olFolder = null;
folderPath.Replace("/", @"\");
string[] arrFolders = folderPath.Split('\\');

foreach (Outlook.MAPIFolder olTmpFolder in olNS.Folders) {
if (olTmpFolder.Name == arrFolders[0]) {
olFolder = olTmpFolder;
break;
}
}
[/csharp]

When we have found our root folder, we will look for our first folder and when we find it, we replace our parent object by that folder and go looking for the next folder.

[csharp]
if (olFolder != null) {
for (int i = 1; i < arrFolders.Length; i++) {
Outlook.Folders olFolders = olFolder.Folders;
olFolder = null;

foreach (Outlook.MAPIFolder olTmpFolder in olFolders) {
if (olTmpFolder.Name == arrFolders[i]) {
olFolder = olTmpFolder;
break;
}
}
olFolders = null;
}
}
[/csharp]

And in the end we return our found folder after cleaning up.

[csharp]
arrFolders = null;
olNS = null;
appOutlook = null;
return olFolder;
[/csharp]

Next is the GetAddresses method. This method has been created by Rob Windsor in VB.NET and posted here. Permission was granted to convert it to C# and use it for this article. Thanks!

This method uses a regular expression to extract the email addresses out of a string after which they are returned as a string array.

[csharp]
// Converted from http://www.codeproject.com/vb/net/extractemail.asp
private static string[] GetAddresses(string bodyText) {
// Regex expression garnered from www.regexlib.com - thanks guys!
MatchCollection mcEmail = Regex.Matches(bodyText, @"([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5})");
string[] emailAddresses = new string[mcEmail.Count];
for (int i = 0; i < mcEmail.Count; i++) {
emailAddresses[i] = mcEmail[i].Value;
}
return emailAddresses;
} /* GetAddresses */
[/csharp]

Adding our addresses is as simple as checking if the ArrayList already Contains it and add it if it doesn't.

[csharp]
private static void AddAddress(string emailAddress) {
emailAddress = emailAddress.Trim();
emailAddress = emailAddress.ToLower();
if (!emailCollection.Contains(emailAddress)) {
emailCollection.Add(emailAddress);
}
} /* AddAddress */
[/csharp]

And to close this article, the SaveAddresses method asks for a filename to write to and writes the addresses there as a delimited list which you can import in other applications.

[csharp]
private static void SaveAddresses() {
Console.Write("Path to save to: ");
string savePath = Console.ReadLine();
if (savePath != "") {
emailCollection.Sort();
using (StreamWriter sw = new StreamWriter(savePath)) {
foreach (string emailAddress in emailCollection) {
sw.WriteLine(String.Format("{0};", emailAddress));
}
}
}
} /* SaveAddresses */
[/csharp]

I tested this on 29 'fun' mails I received, and guess how many addresses came out of there? 1473!! I imported them in a small Access table to test the saved format ;)


As always, I've uploaded the project for you.
 
This post has been imported from the old blog and has not yet been converted to the new syntax yet.
Today's my birthday, I'm turning 20 :)


And because of that I'm giving you guys a present. In the form of some articles.

Going to write 3 articles today for you, starting with how to create a small console chat server.

The other two articles will follow later on today, got to follow some classes first ;)
 
This post has been imported from the old blog and has not yet been converted to the new syntax yet.
In this article we'll write a small ChatServer.

I'll start by explaining the logic we will follow:

We start a Console Application (ChatServer) which will listen on a specified TCP port. When a client connects we create a new object that will represent the Connection. This object has three events, two of those will Add and Remove the client from the connected list when the connection is created and closed. The last one will simply be fired when a message is received.

Our ChatServer will upon receiving a message broadcast it to all clients currently connected. There is no processing, just forwarding to every connected client. A very basic framework for a client/server architecture.

Let's begin by creating a Console App called ChatServer.

[csharp]
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Collections;

namespace ChatServer {
class ChatServer {
static void Main(string[] args) {
ChatServer chatServer = new ChatServer();
} /* Main */

public ChatServer() { }
} /* ChatServer */
} /* ChatServer */
[/csharp]

We are using the System.Net namespace to be able to listen for connections. And System.Threading because we will launch our Listen method in a separate Thread.

What info do we need? We'll need a serverport to listen on, a TcpListener, a Thread where the listener runs in, and we'll use an ArrayList to contain our connected clients.

[csharp]
private int serverPort;
private Thread listenerThread;
private TcpListener socketListener;
private ArrayList chatClients;
[/csharp]

I made properties of these as well, called ServerPort, ListenThread, ListenSocket and Clients.

In our constructor we will assign the port, start the listener and provide some feedback.

[csharp]
public ChatServer() {
this.ServerPort = 54321;
this.ListenThread = new Thread(new ThreadStart(Listen));
this.ListenThread.Start();
this.Clients = new ArrayList();
this.Output("STATUS", String.Format("ChatServer Started on port {0}.", this.ServerPort));
} /* ChatServer */
[/csharp]

Before we go any further in our ChatServer, we'll create a new class called Connection.

[csharp]
using System;
using System.Net.Sockets;
using System.IO;
using System.Threading;

namespace ChatServer {
public class Connection {
public Connection(TcpClient chatClient, int clientId) {
// TODO
} /* Connection */
} /* Connection */
} /* ChatServer */
[/csharp]

Let's see, what does a Connection really need? We need some way to identify it, so we add a clientNumber. We have a TcpClient where we will get a NetworkStream from to create a StreamWriter and StreamReader. We're also going to launch our listener in a separate Thread.

[csharp]
private int clientNumber;
private Thread listenerThread;
private TcpClient chatConnection;
private NetworkStream chatStream;
private StreamWriter chatWriter;
private StreamReader chatReader;
[/csharp]

These are the following properties: Id, ChatConnection, ChatStream, ChatWriter, ChatReader and ListenThread.

Each Connection will be able to fire of events, so let's create those.

[csharp]
namespace ChatServer {
#region Delegates
public delegate void MessageReceived(string msgText, int chatClient);
public delegate void AddClient(Connection chatConnection);
public delegate void RemoveClient(Connection chatConnection);
#endregion

public class Connection {
#region Events
public event MessageReceived eventReceiving;
public event AddClient eventAdding;
public event RemoveClient eventRemoving;
#endregion
[/csharp]

When we first create a Connection we take a TcpClient and a number assigned to us be the server.

[csharp]
public Connection(TcpClient chatClient, int clientId) {
this.ChatConnection = chatClient;
this.clientNumber = clientId;
} /* Connection */
[/csharp]

After our object is created the server will bind the events and will Connect the client.

[csharp]
public void Connect() {
/* If we implement the listener while loop here,
only one client at a time will be able to send.
Therefore we launch a new Thread that is responsible for one Connection. */

this.ListenThread = new Thread(new ThreadStart(Listen));
this.ListenThread.Start();
if (eventAdding != null) { this.eventAdding(this); }
} /* Connect */
[/csharp]

Let's take a look at the Listen method.

[csharp]
private void Listen() {
this.ChatStream = this.ChatConnection.GetStream();
this.ChatReader = new StreamReader(this.ChatStream);
this.ChatWriter = new StreamWriter(this.ChatStream);
bool connOpen = true;

this.SendMessage(String.Format("Welcome to ChatServer. You are client #{0}.", this.Id));

while (connOpen) {
string chatMsg;
while ((chatMsg = this.ChatReader.ReadLine()) != null) {
if (eventReceiving != null) { this.eventReceiving(chatMsg, this.Id); }
}
this.ChatWriter.Close();
this.ChatReader.Close();
this.ChatConnection.Close();
if (eventRemoving != null) { this.eventRemoving(this); }
connOpen = false;
}
} /* Listen */
[/csharp]

We take our Stream, open a StreamReader and a StreamWriter and we wait for incoming messages, and when the client disconnects we remove ourself from the client list.

We also sent some feedback to the client with a SendMessage method. This is a very simple one, it writes a line to the StreamWriter.

[csharp]
public void SendMessage(string chatMsg) {
/* We check if the Writer already exists, else we get an exception thrown
(which doesn't crash the server thou).
This situation can occur when a client first connects. */

if (this.ChatWriter != null) {
this.ChatWriter.WriteLine(chatMsg);
this.ChatWriter.Flush();
}
} /* SendMessage */
[/csharp]

That's all for our Connection class. Let's go back to our server to set up the Listen method over there.

We want to listen on every address on our pc:

[csharp]
IPAddress ipAddress = Dns.Resolve("0.0.0.0").AddressList[0];
[/csharp]

Then we listen on a specific port and we wait for clients. When a client connects we create an object, assign events and Connect it. And then we wait for another client to connect.

[csharp]
// We listen for connections on all available IPs on port 54321.
this.ListenSocket = new TcpListener(ipAddress, this.ServerPort);
this.ListenSocket.Start();
while(true) {
// For every connection we create a new Connection object.
Connection chatConnection = new Connection(this.ListenSocket.AcceptTcpClient(), this.Clients.Count + 1);
chatConnection.eventReceiving += new MessageReceived(this.MessageReceived);
chatConnection.eventAdding += new AddClient(this.AddClient);
chatConnection.eventRemoving += new RemoveClient(this.RemoveClient);
chatConnection.Connect();
}
[/csharp]

When we receive a message we broadcast it to all other clients.

[csharp]
private void MessageReceived(string chatMessage, int chatClient) {
this.Output("MESSAGE", String.Format("[{0}]: {1}", chatClient, chatMessage));
} /* MessageReceived */

private void Output(string msgStatus, string msgText) {
Console.WriteLine(String.Format("{0}: {1}", msgStatus, msgText));
foreach (Connection chatClient in this.Clients) {
chatClient.SendMessage(msgText);
}
} /* Output */
[/csharp]

Adding and Removing a client is just adding it to an ArrayList and removing it. When we remove it we also set the object to null to get it collected.

That's our class. Now just run the server, telnet to it and chat ;)

Server:


Telnet:


As always I've uploaded the project for you too look at.
 
This post has been imported from the old blog and has not yet been converted to the new syntax yet.
Today I'll talk about hash functions.

A hash algorithm takes a piece of text and gives a hash as result. This hash is unique for the given text. If you use the hash function on the same text again, you'll get the same hash. But there is no way to get the given text from the hash. This is great for storing passwords.

Now, in PHP it's as easy as using md5() or sha1(). But in C# it takes a bit more work. This is what we want to simplify.

So we'll create a Hash class to create hashes.

Create a new project and add a class (Hash).

[csharp]
using System;
using System.Security.Cryptography;
using System.Text;

namespace Hash {
public class Hash {
public Hash() { }

} /* Hash */
} /* Hash */
[/csharp]

Let's start by adding an enum representing all the hash functions we are going to support.

[csharp]public enum HashType :int { MD5, SHA1, SHA256, SHA384, SHA512 }[/csharp]

Our class will have 2 public methods, one for creating a hash and one for checking a hash against a given text.

First we'll create the GetHash method:

[csharp]
public static string GetHash(string strPlain, HashType hshType) {
string strRet;
switch (hshType) {
case HashType.MD5: strRet = GetMD5(strPlain); break;
case HashType.SHA1: strRet = GetSHA1(strPlain); break;
case HashType.SHA256: strRet = GetSHA256(strPlain); break;
case HashType.SHA384: strRet = GetSHA384(strPlain); break;
case HashType.SHA512: strRet = GetSHA512(strPlain); break;
default: strRet = "Invalid HashType"; break;
}
return strRet;
} /* GetHash */
[/csharp]

And our CheckHash will depend on this so we might as well add it now.

[csharp]
public static bool CheckHash(string strOriginal, string strHash, HashType hshType) {
string strOrigHash = GetHash(strOriginal, hshType);
return (strOrigHash == strHash);
} /* CheckHash */
[/csharp]

As you can see, I created 5 separate methods to create hashes. I'll explain one for this article, the others are the same but use another hashing class. You'll find them in the source at the end of this article.

A hash function works on a byte array, so we will create two arrays, one for our resulting hash and one for the given text

[csharp]
UnicodeEncoding UE = new UnicodeEncoding();
byte[] HashValue, MessageBytes = UE.GetBytes(strPlain);
[/csharp]

Now we create an object that will hash our text:

[csharp]
SHA1Managed SHhash = new SHA1Managed();
[/csharp]

And finally we calculate the hash and convert it to a hexadecimal string. Which we can store in a database for example.

[csharp]
string strHex = "";

HashValue = SHhash.ComputeHash(MessageBytes);
foreach(byte b in HashValue) {
strHex += String.Format("{0:x2}", b);
}
return strHex;
[/csharp]

This is how we test it:

[csharp]
static void Main(string[] args) {
String hash = Hash.Hash.GetHash("This is a sample text :p", Hash.Hash.HashType.SHA256);
Console.WriteLine(hash);
Console.WriteLine(Hash.Hash.CheckHash("This is a sample text :p", hash, Hash.Hash.HashType.SHA256));
Console.WriteLine(Hash.Hash.CheckHash("This is a wrong text.", hash, Hash.Hash.HashType.SHA256));
} /* Main */
[/csharp]

Now we have our sweet and simple methods available as a class, ready to be used in any project.

I've uploaded the sources again, you will see I documented it as well. When you use NDoc on the generated .xml file you get a very sweet MSDN like documentation.

Important Update:
To get the same result as the md5() function in PHP, use ASCIIEncoding!
As in: ASCIIEncoding UE = new ASCIIEncoding();