Software release with sourcode: RSA File

 

Wow this gives a new definition to the internet term: “Long time no see”.

But I haven’t forgotten my lovely readers out there. I just took a break (I should have informed you I guess) so I could get back coding.

Lot’s have happened in this time. I’ve written quite a few applications, some which I finished, others just “bases” for later coding.

I’ve extended some of my own private libraries and even sent my home automation project out into V5 (more on that later).

But one of the few “gems” I managed to make was my little project: RSA File.

Why that stupid name? Because RSA is really refering to the public key encryption RSA.

The main window of the program

 

 

 

 

 

 

The whole idea to short it down is that fx. you are on a forum. And you need to have someone send over some information to you without others reading it. On this forum identity isn’t a problem so you know who are who, but everone can read everone elses messages. Or maybe a public chat where you need to exchange some secret file. What do you do?

The classic approach would be with a preshared encryptionkey. That could work if the chat or forum has private messages enabled.

But what if you can’t trust the admins in there and it’s the only way you have to communicate? Or you just want it to go fast?

How would you encrypt your files without ever disclosing a password in public?

It’s quite simple, using public key cryptography we can do just that! Using RSA (a common method of public key encryption) we can make a private and a public key. The public key can be sent to everyone and they can encrypt some data. But ONLY the private key can read it. If you encrypt something with the public key, the public key can’t decrypt it.

So everyone can send their public keys out into the public but only the private key (the original receiver) can decrypt the content. Public key encryption has however one major drawback. It only supports (at least in .NET) up to 1024 bytes of data and it’s really slow compared to classic encryption with pre shared keys.

 

To read more about public key encryption you can visit http://en.wikipedia.org/wiki/Public-key_cryptography otherwise, move along :)

 

But how are we going to pull this into a program then? No file now a days is only 1024 bytes?

Well… We will just combine both classic (also called symmetric) encryption with public key encryption (called asymmetric encryption).

We will ask the user for a file, generate a completely random password, unknown to the user, and then encrypt the file with that password using symmetric encryption.

After that we will encrypt the password with the public key given by the user and then put it at the beginning of the file!

Then the receiver receives the file he will have the private key, and be able to decrypt the random password and then decrypt the whole file.

Everyone can know the public key but only the original receiver which holds the private key will be able to read the files.

The encryption window of the program

 

 

 

 

 

 

 

 

It’s all cool and that but I just want to see the source / use the program.

Fine with me, I’m also going to continue programming on my home control system now.

Here are the download links for the source code. You will find the program itself inside the folder as follows:

RSA File > Bin > Release

Download:

RSA File - Public file sending (42)

 

Final note:

If you see this release elsewhere it’s because I’ve released it a few days earlier over at HackForums. The same thing is if some of you from there sees this. I have the user HSPSoftware over there so this is my source. While I’m at the thing with sources, my source code includes a custom theme from a guy called “Aeonhack”. Credits to you Aeon! :)

Final final note:

It just hit me that some of you are going to put me down like a cracker or something for saying that I’m over at HackForums too.

But let me put it like this: I’m active many places on the internet. Some more “dark” than others but I always hold myself on the right side of the law. The reason I’m over at HF is that they have some really clever people there. And I also like to consider my self as a “self declared spare time white hat hacker“. So for me it’s just another way of learning. And I also think it’s healthy for every programmer to understand the “dark side” of computers.

 

Writing custom media center plugins for windows 7

What is Windows Media Center?

Windows Media Center is a standard piece of software, shipping with most versions of Windows. It has the ability to present varying media in a common “sexy” way. It’s mostly intended for use with media center pc’s, therefore the name. It has built in support for IR remotes, and can search for song and video data through Microsofts webservices.

I find it pretty awesome, and use it for my own media center. Primarily for playing video files. It also has extensive support for custom addins. That’s what we are going to dive into today.

(You can read more about Windows Media Center on wikipedia: http://en.wikipedia.org/wiki/Windows_Media_Center)


The tools we will need


Before we can begin any kind of developement for Windows Media Center, we are going to need some tools. If you use Visual Studio 2010 as I do, you are going to need the Visual Studio 2008. And if you want to play with VB.NET… Well, you can forget it.

I personally don’t really care about which language it is, but I originally wanted to go for VB.NET. That wasn’t an option, and it didn’t stand anywhere that it wasn’t. So I thought that the SDK wasn’t installed and I started debugging. I just by accident opened Visual C# 2008 Express and saw that the SDK popped up there.

You can download Visual Studio 2008 Express edition on this link: Visual Studio 2008 Express editions.

Now onto the SDK itself. The one we will need is this file WindowsMediaCenterSDK6.msi. Remember to install visual studio c# 2008 first.


Creating a basic “Hello World” addin


Let’s begin by opening Visual C# 2008. If everything went smoothly, you will see a new project template listed.









Just click OK to continue. Wait a few seconds for it to create the project. It may take a little longer than normal.

Then the project has been created, it should automatically open the Readme.htm file in Visual Studio.

This actually serves as a quite good manual for starting out with addin development.

The first point in the list is:

Create a strong name key file and add it to the assembly


This is needed as we are going to install the addin in to the Global Assembly Cache (more on that later). The Global Assembly Cache is by short means a common place for .NET applications to store shared DLL files. But in order to load a DLL file into the GAC (short name), the DLL file must be signed with a strong name. It does not need to be a code signing certificate. A self signed certificate is more than enough.

Anyway, here are the steps involved.


  1. Goto project > MediaCenterApplication1 Properties.
  2. Select “Signing” in menu to the left.
  3. If it’s not checked, go check the “Sign the assembly” option.
  4. Click the dropdown menu and select “”.
  5. Write some key file name (for this purpose I’m calling it “HSP Test Certificate”) and write a password too (in this case just “HSPSoftware”). Always remember password, even though it should be a little stronger than mine ;)
  6. Hold won CTRL + SHIFT and press S on the keyboard. This is just the shortcut for saving all files. (File > Save all).

Press F6 to build the solution (Shortcut for Build > Build solution).

Enter the strong name key in the registration file


In this section we are going to “link” the strong name key to the Registration file used later on, then installing the addin.

But first we need to get the Public Key for our strong name. To do this, we will add an “external tool” to Visual Studio for easy access in the future.


  1. First go to Tools > External Tools.
  2. Write “Get Public Key” or anything else which makes sense to you in to the title box.
  3. Write C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\sn.exe in to the command box.
  4. Write -Tp “$(TargetPath)” in the arguments box.
  5. And lastly, uncheck anything else except “Use Output Window”.
  6. Hit Apply and OK.
  7. Go to Tools > Get Public Key (or whatever you named it). Note: You may need to hit debug (F5) first, even though you can’t run a DLL file in the IDE.
  8. Copy the Public Key Token from the outputwindow.
  9. Open Setup > Registration.xml.
  10. Replace “insert_public_key_token_here” with the actual public key.
  11. Save all and go to Build > Rebuild Solution.


Installing the actual DLL to the GAC and registering with Windows Media Center


Microsoft has been kind enough to provide us with a simple solution to do just that. It’s name is DevInstall.cmd and is placed in the root of your project… Unfortunately this don’t work for me. Neither on my old laptop. So you are free to try it out.

If it doesn’t work, or you just prefer to use some 15 year old kids work instead of Microsofts, you can use my own version of the script here. Their script copies the DLL and XML files to %Program Files%. My script just registers both from the Visual Studio bin/Release directory. Well, you can’t move your project folder around without re-running the script. But who does that anyway? (at least not very often). I just prefer it that way so my system isn’t cluttered up by random folders from random developments.

The download link is here: Custom Media Center Installer (121). Remember to edit the file to suit your project name. You are of course free to use it or redistribute it however you like. I don’t take any responsibility for either software- or hardware failure caused by this script.

Supposed you followed all the steps correctly until now, you can open Windows Media Center and see this nice little notification pop up.










Creating something a little more useful


By now, all the gears should be running and you a properly spinning around your office chair because of the great success you just had. BUT! … It isn’t really useful, is it? Showing some text in a popup, inside windows media center, is maybe cool around your geek friends. But your girlfriend is properly just going to slap you then your media center is starting to show weird Star Wars quotations.

Instead of being slapped, what about letting her control the TV from her iPhone then she can’t find the remote?

Or maybe you will just use this for switching to Discovery Channel, while she’s watching MTV, and get slapped anyway. The choice is yours.

Either way, remote control sounds pretty useful to me! So let’s get coding!


Until now, we have just lived high on the code provided by Microsoft. I haven’t covered changing it yet, but maybe you have already figured out how to change the default popup message into something else.

If you haven’t it’s okay. Just navigate to Code > Application.cs.

You will see a lot of code in there, but we only want to dive into this:

public void Start()
{
	string temp = "The background application did something.";
	DialogTest(temp);
}
public void DialogTest(string strClickedText)
{
	int timeout = 5;
	bool modal = true;
	string caption = Resources.DialogCaption;
	if (host != null)
	{
		MediaCenterEnvironment.Dialog(strClickedText,
							caption,
							new object[] { DialogButtons.Ok },
							timeout,
							modal,
							null,
							delegate(DialogResult dialogResult) { });
	}
	else
	{
		Debug.WriteLine("DialogTest");
	}
}

The start() routine is initiated from the Launch.cs. It is called then Windows Media Player is loading the addin.

DialogTest() is not going to be needed. This is just for easy showing of dialogs.


Let’s start out by going to the top and put in these namespaces under the existing.

using System.Net.Sockets;
using System.Threading;
using System.Text;

While you are up there, define this variable just under “private AddInHost host;”

private TcpListener tcpServer;

We just set up the required using declarations and defined a “placeholder” for a our TcpListener.

We did this as we are going to use TCP based communication to receive any commands given.

Go back to the start() routine and add this to start the server and make a basic loop to accept incoming clients.

tcpServer = new TcpListener(System.Net.IPAddress.Any, 3200);
tcpServer.Start();
while (true)
{
TcpClient client = tcpServer.AcceptTcpClient();
}

There, you could just make the usual stream in and out and loop back. But instead we are going to launch each new client on a new thread. This is done so the server (our addin) can accept multiple simultaneous connections.

We will do this by creating this new routine. It accepts a single parameter, which is just an object representing a TcpClient.

It will typecast this object into a TcpClient, open the networkstream and then create a 4096 byte buffer for receiving any commands.

private void HandleClientComm(object client)
{
	TcpClient tcpClient = (TcpClient)client;
	NetworkStream clientStream = tcpClient.GetStream();
	byte[] message = new byte[4096];
	int bytesRead;
	while (true)
	{
		bytesRead = 0;
		try
		{
			bytesRead = clientStream.Read(message, 0, 4096);
		}
		catch
		{
			break;
		}
		if (bytesRead == 0)
		{
			break;
		}
		//Handle command here
	}
tcpClient.Close();
}

Go back to the start routine once more. We just need to add a couple of lines after the accepting of a new TcpClient.

These lines will make the program define a new thread and then launch the HandleClientComm() while passing the connected TcpClient along to it.

Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);

Now we will just make a method for passing the commands given from the connected TcpClients. (I say TcpClients because there can be more than one at a time).

I could go into a lot of detail here but I will just show you my code (which I use for my own Media Center). It can do the most, play an audiofile, play a videofile, change volume, change channels, change mute, stop, pause, play and so on.

You can add your own commands if you want to of course :)

//This is just used for defining the available commands. Feel free to change.
private void handleRemoteCommand(string command)
{
	//I don't know, just a habbit I have when working with network protocols (after some bad experinces).
	command = command.Trim();
	//First we check for basic play, pause, stop commands.
	switch (command)
	{
		case "play":
			MediaCenterEnvironment.MediaExperience.Transport.PlayRate = (float)PlayRates.PLAYRATE_PLAY;
			break;
		case "pause":
			MediaCenterEnvironment.MediaExperience.Transport.PlayRate = (float)PlayRates.PLAYRATE_PAUSE;
			break;
		case "stop":
			MediaCenterEnvironment.MediaExperience.Transport.PlayRate = (float)PlayRates.PLAYRATE_STOP;
			break;
	}
	//If mute.
	if (command.StartsWith("mute"))
	{
		command = command.Substring(5);
		switch (command)
		{
			case "true":
				MediaCenterEnvironment.AudioMixer.Mute = true;
				break;
			case "false":
				MediaCenterEnvironment.AudioMixer.Mute = false;
				break;
		}
	}
	//Set's the volume. This took some time to figure out. Can be a little unprecise sometimes.
	else if (command.StartsWith("volume"))
	{
		command = command.Substring(7);
		int volumeSet = -1;
		try
		{
			volumeSet = int.Parse(command);
		}
		catch
		{
		}
		if (volumeSet >= 0 && volumeSet <= 50)
		{
			//If someone at Microsoft ever read this little comment... Please make this easier for all of us! ;)
			int actualVolume = (int)System.Math.Ceiling((double)((MediaCenterEnvironment.AudioMixer.Volume / 655.35)/2));
			if (actualVolume > volumeSet)
			{
				//This freezes the media center for a second or two. But it's acutally the way Microsoft
				//tells us to set the volume. You can also just change the system volume but I'm
				//not going into that now. For the purpose of this tutorial, this will do.
				int timesToGo = actualVolume - volumeSet;
				for (int i = 1; i <= timesToGo; i++)
				{
					MediaCenterEnvironment.AudioMixer.VolumeDown();
					//Well... In my case it actually speeds up a little when I give it a little bit of time inbetween commands
					System.Threading.Thread.Sleep(20);
				}
			}
			else if (actualVolume < volumeSet)
			{
				//This freezes the media center for a second or two. But it's acutally the way Microsoft
				//tells us to set the volume. You can also just change the system volume but I'm
				//not going into that now. For the purpose of this tutorial, this will do.
				int timesToGo = volumeSet - actualVolume;
				for (int i = 1; i <= timesToGo; i++)
				{
					MediaCenterEnvironment.AudioMixer.VolumeUp();
					//Well... In my case it actually speeds up a little when I give it a little bit of time inbetween commands
					System.Threading.Thread.Sleep(20);
				}
			}
		}
	}
	//This changes the channel. You can only use this if you have TV tuner.
	else if (command.StartsWith("channel"))
	{
		Microsoft.MediaCenter.TV.Epg.Lineup LineUP = new Microsoft.MediaCenter.TV.Epg.Lineup();
		command = command.Substring(8);
		foreach (System.Collections.Generic.KeyValuePair CID in LineUP.GetCallSigns())
		{
			if (CID.Value.Contains(command))
			{
				MediaCenterEnvironment.PlayMedia(MediaType.TV, CID.Value, false);
				MediaCenterEnvironment.MediaExperience.GoToFullScreen();
			}
		}
	}
	//Use this for playing a single audiofile
	else if (command.StartsWith("playaudio"))
	{
		command = command.Substring(10).Replace("\\", "\\\\");
		System.IO.FileInfo nfo = new System.IO.FileInfo(command);
		if (nfo.Exists)
		{
			MediaCenterEnvironment.PlayMedia(MediaType.Audio, command, false);
			MediaCenterEnvironment.MediaExperience.GoToFullScreen();
		}
	}
	//Use this for playing a single videofile
	else if (command.StartsWith("playvideo"))
	{
		command = command.Substring(10).Replace("\\", "\\\\");
		System.IO.FileInfo nfo = new System.IO.FileInfo(command);
		if (nfo.Exists)
		{
			MediaCenterEnvironment.PlayMedia(MediaType.Video, command, false);
			MediaCenterEnvironment.MediaExperience.GoToFullScreen();
		}
	}
}
//Can't remember where I got these from... Or if it just was MSDN.
//Anyway, if someone feels insulted, feel free to speak up.
private enum PlayRates
{
PLAYRATE_STOP = 0,
PLAYRATE_PAUSE = 1,
PLAYRATE_PLAY = 2
}


At last just add the following couple of lines at the end of the handleClientComm() loop

UTF8Encoding encoder = new UTF8Encoding();
handleRemoteCommand(encoder.GetString(message, 0, bytesRead));


Just build it / rebuild it. And install it as the first plugin. (My script automatically uninstalls and reinstalls the updated addin. Microsoft’s seems to do that too).

Open Windows Media Center… and…. Voila! Nothing. Well, we that’s because we made it remote controlled. Nothing happens unless we give the order. So let’s create some really simple client. Just make a new project and make this void.

void sendMediaCenterCommand(string command, string mediaCenterLocation, int mediaCenterPort)
{
	System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient();
	client.Connect(mediaCenterLocation, mediaCenterPort);
	byte[] outBytes = System.Text.Encoding.UTF8.GetBytes(command);
	System.Net.Sockets.NetworkStream stream = client.GetStream();
	if (stream.CanRead && stream.CanWrite)
	{
		stream.Write(outBytes, 0, outBytes.Length);
		stream.Flush();
	}
	stream.Close();
	stream.Dispose();
	client.Close();
}

Now you can call sendMediaCenterCommand() as much as you want with any command. It takes three arguments.

  • command: The command you want to send.
  • mediaCenterLocation: The IP of the mediacenter. Just 127.0.0.1 if it’s local.
  • mediaCenterPort: The port you run the addin on. In this case 3200.

You can find all the sourcecode including a full client a little lower on this page. You are free to redistribute it and use it however you like, but a little credit (my name or a link back – maybe both) is very appreciated.

Windows Media Center Addin Source Code (133)

Unofficial Google Translate in C# and VB.NET

Let me first start by apologizing for being away for so long time without writing any posts. I was just not in the mood if you know what I mean.

But today I’m going to show you how to translate some text using Google Translate, right inside your own .NET programs.

I was in need of that feature today, and at first glance I just thought “sure Google is nice, they have an API for programmers like me”. Turns out they do, but that’s a JSON API intended for javascript. Yes yes, we can indeed access that in .NET but I didn’t want to start messing with JSON at the moment and I always like a challenge. So I begin to look into the possibilities for screen scraping, a process I’m quite comfortable with as I’ve done a lot of it.

But be warned. If Google changes anything in their layout your application is likely to break. I will not offer support on this, but If you ask nice I may be able to help you anyway.

For me that doesn’t really matter as it’s primarily intended for personal use on a project I’m constantly working on.

So let’s get coding. First take a look at translation. For testing purposes I will go from Danish to English. But normally Google hides the parameters inside Ajax and POST so I will help you do the hard work and show you this URL.

http://translate.google.com/?hl=en&ie=UTF8&text=Hej+verden&langpair=da|en


It’s the direct translation URL. Put in your own text instead of “Hej Verden”, change the langpair to suit your needs (da|en means from Danish to English) and you are good to
go.

Let’s take that into .NET. Today I’m going to present it in C# but there will be a VB example at the end.

Let’s start out by creating a new Windows Forms project and open code view. You should begin with some imports. There should be some auto generated ones, so just insert
this at the end of the imports.

using System.Net;
using System.Text.RegularExpressions;

After that we can create or initial function. It will take 3 parameters. “input” is gonna be the text to be translated, “langFrom” is the language to translate from in shortcode (like
da or en, for Danish or English) and “langTo” is gonna be the language to translate to, in the same format as “langFrom”.

public string TranslateText(string input, string langFrom, string langTo)
{
	//Function here
}

Now we can move on to the next step where we will actually fetch some data from Google. We will create a new instance of WebClient and add the appropriate headers to it
(to make sure Google is going to send us UTF-8 encoded text). From where we will take the parameters passed to the function and insert them into our previous translation
URL, and after that fetch the content.

public string TranslateText(string input, string langFrom, string langTo)
{
	//Defines a new WebClient
	WebClient Client = new WebClient();
	//Sets the client encoding to UTF8
	Client.Headers.Add("Charset", "text/html; charset=UTF-8");
	//Creates the string. And yes I prefer this over string.format ! ;)
	string downloadUrl = "http://www.google.com/translate_t?hl=da&ie=UTF8&text=" + input + "&langpair="+langFrom+"|"+langTo;
	//Downloads the string from the URL above
	string data = Client.DownloadString(downloadUrl);
	return data;
}

Now we have the data stored inside our “data” variable. Let’s just parse it real fast. We will begin by finding where the “resultbox” and afterwards parse our way trough until we
hit two “” right after each other (indicating the end of the resultbox).

public string TranslateText(string input, string langFrom, string langTo)
{
	//Defines a new WebClient
	WebClient Client = new WebClient();
	//Sets the client encoding to UTF8
	Client.Headers.Add("Charset", "text/html; charset=UTF-8");
	//Creates the string. And yes I prefer this over string.format ! ;)
	string downloadUrl = "http://www.google.com/translate_t?hl=da&ie=UTF8&text=" + input + "&langpair="+langFrom+"|"+langTo;
	//Downloads the string from the URL above
	string data = Client.DownloadString(downloadUrl);
	//Searches for the beginning of the resultbox and cuts everything away before that
	data = data.Substring(data.IndexOf("<span id=result_box")+19);
	//Finds the ending of the resultbox by searching for two spans right after each other
	data = data.Remove(data.IndexOf("</span></span>")+7);
	return data;
}

Now we have the contents of the “resultbox” (and a little of it’s beginning) and are ready to move on to the next step. Here we will use a regex for counting the occurences of
spans and afterwards loop through the entire datablock, extract each span and put the together in the variable “translatedText” and return it at the end.

public string TranslateText(string input, string langFrom, string langTo)
{
	//Defines a new WebClient
	WebClient Client = new WebClient();
	//Sets the client encoding to UTF8
	Client.Headers.Add("Charset", "text/html; charset=UTF-8");
	//Creates the string. And yes I prefer this over string.format ! ;)
	string downloadUrl = "http://www.google.com/translate_t?hl=da&ie=UTF8&text=" + input + "&langpair="+langFrom+"|"+langTo;
	//Downloads the string from the URL above
	string data = Client.DownloadString(downloadUrl);
	//Searches for the beginning of the resultbox and cuts everything away before that
	data = data.Substring(data.IndexOf("<span id=result_box")+19);
	//Finds the ending of the resultbox by searching for two spans right after each other
	data = data.Remove(data.IndexOf("</span></span>")+7);
	//Defines a new regex used for counting all spans inside the resultbox
	Regex spans = new Regex("<span");
	//Finds the count and puts it inside the variable spanOccurences
	int spanOccurences = spans.Matches(data).Count;
	//Defines an empty string for use in the for loop
	string translatedText = "";
	//Extract each tiny bit of text from each span in the resultbox
	for (int i = 0; i < spanOccurences; i++)
	{
		//Defines currentBlock and sets it to everything which comes after the first "<span"
		string currentBlock = data.Substring(data.IndexOf("<span") + 5);
		//Finds the ending of the current span and removes everything after that
		currentBlock = currentBlock.Remove(currentBlock.IndexOf("</span>"));
		//Goes back to the beginning and cleans everything from inside the first span
		currentBlock = currentBlock.Substring(currentBlock.IndexOf(">") + 1);
		//Removes the current processed span from the beginning of the data for next extraction
		data = data.Substring(data.IndexOf("</span>") + 7);
		//Adds the extracted text to the translatedText variable
		translatedText += currentBlock;
	}
	//Returns the translated text
	return translatedText;
}

And the full code in C# looks like.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Text.RegularExpressions;
namespace TranslateScraper
{
	public partial class Form1 : Form
	{
		public Form1()
		{
			InitializeComponent();
		}
		private void Form1_Load(object sender, EventArgs e)
		{
			MessageBox.Show(TranslateText("Tillykke! Dine programmer kan nu bruge Google Oversæt", "da", "en"));
		}
		/// <summary>
		/// Translates a text using screenscaping on Google Translate
		/// </summary>
		/// <param name="input">The string to translate</param>
		/// <param name="langFrom">The language to translate from. Fx "en" for English or "da" for Danish</param>
		/// <param name="langTo">The language to translate to in the same format as langFrom</param>
		/// <returns></returns>
		public string TranslateText(string input, string langFrom, string langTo)
		{
			//Defines a new WebClient
			WebClient Client = new WebClient();
			//Sets the client encoding to UTF8
			Client.Headers.Add("Charset", "text/html; charset=UTF-8");
			//Creates the string. And yes I prefer this over string.format ! ;)
			string downloadUrl = "http://www.google.com/translate_t?hl=da&ie=UTF8&text=" + input + "&langpair="+langFrom+"|"+langTo;
			//Downloads the string from the URL above
			string data = Client.DownloadString(downloadUrl);
			//Searches for the beginning of the resultbox and cuts everything away before that
			data = data.Substring(data.IndexOf("<span id=result_box")+19);
			//Finds the ending of the resultbox by searching for two spans right after each other
			data = data.Remove(data.IndexOf("</span></span>")+7);
			//Defines a new regex used for counting all spans inside the resultbox
			Regex spans = new Regex("<span");
			//Finds the count and puts it inside the variable spanOccurences
			int spanOccurences = spans.Matches(data).Count;
			//Defines an empty string for use in the for loop
			string translatedText = "";
			//Extract each tiny bit of text from each span in the resultbox
			for (int i = 0; i < spanOccurences; i++)
			{
				//Defines currentBlock and sets it to everything which comes after the first "<span"
				string currentBlock = data.Substring(data.IndexOf("<span") + 5);
				//Finds the ending of the current span and removes everything after that
				currentBlock = currentBlock.Remove(currentBlock.IndexOf("</span>"));
				//Goes back to the beginning and cleans everything from inside the first span
				currentBlock = currentBlock.Substring(currentBlock.IndexOf(">") + 1);
				//Removes the current processed span from the beginning of the data for next extraction
				data = data.Substring(data.IndexOf("</span>") + 7);
				//Adds the extracted text to the translatedText variable
				translatedText += currentBlock;
			}
			//Returns the translated text
			return translatedText;
		}
	}
}

And in VB.

Imports System.Text.RegularExpressions
Imports System.Net
Public Class Form1
	Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
		MsgBox(TranslateText("Tillykke! Dine programmer kan nu bruge Google oversæt", "da", "en"))
	End Sub
	''' <summary>
	''' Translates a text using screenscaping on Google Translate
	''' </summary>
	''' <param name="input">The string to translate</param>
	''' <param name="langFrom">The language to translate from. Fx "en" for English or "da" for Danish</param>
	''' <param name="langTo">The language to translate to in the same format as langFrom</param>
	''' <returns></returns>
	Public Function TranslateText(ByVal input As String, ByVal langFrom As String, ByVal langTo As String) As String
		'Defines a new WebClient
		Dim Client As New WebClient()
		'Sets the client encoding to UTF8
		Client.Headers.Add("Charset", "text/html; charset=UTF-8")
		'Creates the string. And yes I prefer this over string.format ! ;)
		Dim downloadUrl As String = "http://www.google.com/translate_t?hl=da&ie=UTF8&text=" & input & "&langpair=" & langFrom & "|" &
		'Downloads the string from the URL above
		Dim data As String = Client.DownloadString(downloadUrl)
		'Searches for the beginning of the resultbox and cuts everything away before that
		data = data.Substring(data.IndexOf("<span id=result_box") + 19)
		'Finds the ending of the resultbox by searching for two spans right after each other
		data = data.Remove(data.IndexOf("</span></span>") + 7)
		'Defines a new regex used for counting all spans inside the resultbox
		Dim spans As New Regex("<span")
		'Finds the count and puts it inside the variable spanOccurences
		Dim spanOccurences As Integer = spans.Matches(data).Count
		'Defines an empty string for use in the for loop
		Dim translatedText As String = ""
		'Extract each tiny bit of text from each span in the resultbox
		For i As Integer = 0 To spanOccurences - 1
			'Defines currentBlock and sets it to everything which comes after the first "<span"
			Dim currentBlock As String = data.Substring(data.IndexOf("<span") + 5)
			'Finds the ending of the current span and removes everything after that
			currentBlock = currentBlock.Remove(currentBlock.IndexOf("</span>"))
			'Goes back to the beginning and cleans everything from inside the first span
			currentBlock = currentBlock.Substring(currentBlock.IndexOf(">") + 1)
			'Removes the current processed span from the beginning of the data for next extraction
			data = data.Substring(data.IndexOf("</span>") + 7)
			'Adds the extracted text to the translatedText variable
			translatedText += currentBlock
	Next
	'Returns the translated text
	Return translatedText
End Function
End Class

And that concludes this tutorial. Thanks for reading, I hope to be back soon with some fresh new content, and possibly an article about my home automation system.

Launching a nuclear war with VB.NET

Today I’m going to show you how to build a “nuclear command center” complete with voice synthesis and a spoken password, just like the movies ;)

(Or at least it’s the control interface. Unless you connect it to some sort of military installation, which I strongly suggest you not to, it will only act like a control center and not destroy any civilians while running.)

Anyway, let’s move on with the tutorial.


The main interface

Just make a standard windows forms application, nothing there. Here is my layout. I just used some completely free icons from www.iconfinder.net.





I also created some simple routines like “updateNuclearStatus(status)” and “showMessage(message)” to smoothen things up when we need to update our interface. If you want to skip this step, you can download the complete source code at the end. The

The voice recognition stuff

In order for us to do some real cool voice authentication, we will have to use the Windows Speech API. This will provide us with access to the windows text to speech engine, and also the voice recognition engine. At first you will need to add a reference to system.speech. Do this like so.











Right click your project name and choose Add Reference.










Scroll down to “System.Speech” and click on it, when “OK”.




Next we will import it and create some variables to work with. One SpeechSynthesizer and one SpeechRecognizer. The first provides access to text to speech and the other do the opposite thing.

Imports System.Speech
Imports System.Speech.Recognition.SrgsGrammar
Public Class MainForm
	Private WithEvents speechRecognitionEngine As New Recognition.SpeechRecognizer
	Private speechSynthesis As New Synthesis.SpeechSynthesizer()
End Class

Now we will initialize both our variables. First the SpeechSynthesizer. That’s the easy one. Just set a little slow speaking voice, with 100% volume and let it say something cool when the application is first launched.

speechSynthesis.Volume = 100
speechSynthesis.Rate = -1
speechSynthesis.SpeakAsync("Welcome to HSP Nuclear command center.")

And now onto the interesting part where we will configure the SpeechRecognizer. We will begin by creating a new grammatic document. And when create a new grammatic rule, where we will add some words we want our program to listen for. In fact we will add the whole phonetic alphabet + some extra commands (“Initiate launch sequence”, “Confirm”, “Abort”). We will when add these rules to our grammatic document and make them root. At last we load the whole grammatic document into our SpeechRecognizer.

Dim grammaticDocument As New SrgsDocument
Dim phoneticRule As New SrgsRule("Phonetic")
Dim phoneticList As New SrgsOneOf()
phoneticList.Add(New SrgsItem("Alpha"))
phoneticList.Add(New SrgsItem("Bravo"))
phoneticList.Add(New SrgsItem("Charlie"))
phoneticList.Add(New SrgsItem("Delta"))
phoneticList.Add(New SrgsItem("Echo"))
phoneticList.Add(New SrgsItem("Foxtrot"))
phoneticList.Add(New SrgsItem("Golft"))
phoneticList.Add(New SrgsItem("Hotel"))
phoneticList.Add(New SrgsItem("India"))
phoneticList.Add(New SrgsItem("Juliet"))
phoneticList.Add(New SrgsItem("Kilo"))
phoneticList.Add(New SrgsItem("Lima"))
phoneticList.Add(New SrgsItem("Mike"))
phoneticList.Add(New SrgsItem("November"))
phoneticList.Add(New SrgsItem("Oscar"))
phoneticList.Add(New SrgsItem("Papa"))
phoneticList.Add(New SrgsItem("Quebec"))
phoneticList.Add(New SrgsItem("Romeo"))
phoneticList.Add(New SrgsItem("Sierra"))
phoneticList.Add(New SrgsItem("Tango"))
phoneticList.Add(New SrgsItem("Uniform"))
phoneticList.Add(New SrgsItem("Victor"))
phoneticList.Add(New SrgsItem("Whiskey"))
phoneticList.Add(New SrgsItem("X-ray"))
phoneticList.Add(New SrgsItem("Yankee"))
phoneticList.Add(New SrgsItem("Zulu"))
'Just add the commands themself at the end.
phoneticList.Add(New SrgsItem("Confirm"))
phoneticList.Add(New SrgsItem("Initiate launch sequence"))
phoneticList.Add(New SrgsItem("Abort"))
phoneticRule.Add(phoneticList)
grammaticDocument.Rules.Add(phoneticRule)
grammaticDocument.Root = phoneticRule
speechRecognitionEngine.LoadGrammar(New Recognition.Grammar(grammaticDocument))

Now we can add an event handler at the end of the form loading function and make it point to a new routine.
Event handler

AddHandler speechRecognitionEngine.SpeechRecognized, AddressOf speechRecognized

New routine

Private Sub speechRecognized(ByVal sender As Object, ByVal e As System.Speech.Recognition.RecognitionEventArgs)
	'Futere code goes here
End Sub

Now we have our recognition working. You could add MsgBox(e.Result.Text) inside our function if you wanted to, run the application and when trying to say “Alpha” into the microphone. There should be a popup window with the text “Alpha”.



The logic and added coolness


Now that we have fully working program which recognizes some words, it is time to move on. Yeah you could have it show a popup each time you say something, or even repeat it. But why do that, when we can do so much cooler things. Like replicate the classic nuclear verification process which Hollywood loves to use all the time. So we will continue by adding some new variables at the top of the program.

'We will use this for password verification.
Private position As Integer = 0
'This will store the password (or passwords actually) in an array. Define your own at the end, seperated by spaces like mine.
Private password() As String = Split("Alpha Whiskey Kilo Lima Echo Tango Delta Charlie", " ")
'This will be used to dertime if the user has succesfully authenticated.
Private presidentRights As Boolean = False

Next up, add these subs somewhere in your program.

Private Sub accessGranted()
speechSynthesis.Speak("Access granted. Welcome mister president.")
presidentRights = True
position = 0
End Sub
Private Sub accessDenied()
speechSynthesis.Speak("Access denied. Password prompt resetting.")
presidentRights = False
position = 0
End Sub
Private Sub abort()
speechSynthesis.Speak("Password prompt resetting.")
presidentRights = False
position = 0
End Sub

And now the real funny part. Now we are going to validate the user password. I hope the comments makes it clear what it’s doing.

If presidentRights Then
	'If the user is authenticated as "president", the program will listen for the two keywords.
	Select Case e.Result.Text
		Case "Initiate launch sequence"
			'Says something if the launch is initiated.
			speechSynthesis.Speak("Launch sequence initiated. Everything blows up!")
			System.Threading.Thread.Sleep(2500)
			abort()
		Case "Abort"
			'Says something else if the launch is aborted.
			speechSynthesis.Speak("Launch sequence aborted. We are saved.")
			abort()
		End Select
	presidentRights = False
Else
	Select Case e.Result.Text
		'If the user chooses to confirm it validates the password (real simple.)
		Case "Confirm"
			If position = password.Length Then
				'If OK, call accessGranted()
				accessGranted()
			Else
				'If wrong, call accessDenied()
				accessDenied()
			End If
		Case "Abort"
			'Calls abort in case user choose to abort.
			abort()
		Case password(position)
			'Checks password. If right, the counter is increment.
			position += 1
		Case Else
			'If anything else (like wrong password) the position is reset to 0.
			position = 0
	End Select
End If

There you have it. A complete replica of the popular atomic launch system in the movies.


Demonstration

This is my first screencast, but I think it came out pretty good…



Launching a nuclear war with VB.NET from Henrik Pedersen on Vimeo.



Download

Lazy people can feed of my work here, even without copy pasting ;) – SpokenPassword (61)


Quick introduction to object orientated programming in VB.NET

I just did some quick work in VB.NET and I when thought about how hard it would have been without using objects.

When, the thoughts just flowed, and suddenly I was back to my young novice days where I didn’t utilized the powers of OOP.

“Oh no not you too…” You might say to yourself or: “What’s up with all this hype?”… I said that too, and just skipped straight past the subjects about this technique.

It’s quite understandable that people who don’t know the ways of the force OOP say like so, because it might sound quite overwhelming to a newbie at first. But now I’m going to take you trough it, in VB.NET. (can be easily adapted to C# if you want. Just use a free converter.)

The first thing is of course, a little background. This is taken straight from Wikipedia.org:

Object-oriented programming (OOP) is a programming paradigm that uses “objects” – data structures consisting of data fields and methods together with their interactions – to design applications and computer programs. Programming techniques may include features such as data abstraction, encapsulation,modularity, polymorphism, and inheritance. Many modern programming languages now support OOP.

And to translate it to everyday language: Now we are just taking this simple little example code as a demonstration. It is about dogs, but could be about anything else here in life. We are using a function to create a new dog, and when just accessing the variables directly later on.

Private dogName as String = ""
Private dogAge as Integer = 0
Private Sub createDog(ByVal name As String, ByVal age As Integer) 
	dogName = name
	dogAge = age 
End Sub  
Private Sub mainCodeHere() 
	createDog("Oskar", 7) 
	MsgBox(dogName & " is " & dogAge.ToString & " year(s) old!") 
End Sub

But what if we wanted multiple dogs? If we where trying to make a new dog, the old dogs information would be deleted. We could of course use something like an array, or even a hidden listbox.

But that would not be very good practice at all! Instead we could try with an object.

Think of an object, as a kind of variable. But this kind of variable holds as much code as you want it to, just like a little program within your program.

It can have public functions, subs and variables, and also have hidden ones, used by itself. An object is created from a class. The class can when reside in a namespace, but for simplicity we are leaving out that part for now.

Let’s begin by making a new class and making some simple variables:

Public Class Dog
	Private dogName As String = ""
	Private dogAge As Integer = 0 
End Class

Now let’s try making a sub within, for creating the new dog.

Public Class Dog
	Private dogName As String = ""
	Private dogAge As Integer = 0
	Public Sub createDog(ByVal name As String, ByVal age As Integer)
		dogName = name
		dogAge = age
	End Sub
End Class

Now we are almost finished. Let’s just try it out right now, and see what happens. (I suppose your class exists in a separate vb file)

Private Sub mainCodeHere()
	Dim dog1 As New Dog()
	dog1.createDog("Oskar", 7)
End Sub

That my friend, was your first piece of OOP code. We created the object Dog from the class Dog and accessed the sub createDog. “But what if I want to get the data back into my main program?” you may say… Fear not, the solution comes right away! In fact you could just declare the variables in the class as public, but it’s way better to use Properties as that gives a greater amount of control. So let’s set up some properties. (Back inside the class file.)

Public Class Dog
	Private dogName As String = ""
	Private dogAge As Integer = 0
	Public Property name As String
		Get
			Return dogName
		End Get 
		Set(ByVal value As String) 
			dogName = value 
		End Set 
	End Property 
	Public Property age As Integer
		Get
			Return dogAge
		End Get 
		Set(ByVal value As Integer)
			dogAge = value 
		End Set 
	End Property 
	Public Sub createDog(ByVal name As String, ByVal age As Integer)
		dogName = name
		dogAge = age
	End Sub
End Class

Now it’s very easy to use the object to both create a dog, and when retrieve the values. We can also change the values as demonstrated here.

Private Sub mainCodeHere()
	Dim dog1 As New Dog()
	dog1.createDog("Oskar", 7)
	MsgBox(dog1.name &" is " & dog1.age.ToString() & " year(s) old!")
	dog1.age = 8
	MsgBox(dog1.name & " is now " & dog1.age.ToString() & " year(s) old!")
End Sub

“Woaw that’s impressive. But I still don’t get why we need to use properties?” … Yeah I just said it was bad practice not to, and it might be bad practice to say just that. So here is the explanation. Remember I said something about greater control? What if we want it to be like a dog’s maximum age is 20 years old? Or more likely, we want it to be so that we can’t assign negative values as age. This can be done trough the property used to set the age. See below:

Public Class Dog
	Private dogName As String = ""
	Private dogAge As Integer = 0
	Public Property name As String
		Get
			Return dogName
		End Get
		Set(ByVal value As String)
			dogName = value
		End Set
	End Property
	Public Property age As Integer
		Get
			Return dogAge
		End Get
		Set(ByVal value As Integer)
			If value <= 20 And value >= 0 Then
				dogAge = value
			ElseIf value > 20 Then
				MsgBox("WARNING: Dog age to high. Setting to 20")
				dogAge = 20
			ElseIf value < 0 Then
				MsgBox("WARNING: Dog age to low. Setting to 0")
				dogAge = 0
			End If
		End Set
	End Property
	Public Sub createDog(ByVal name As String, ByVal age As Integer)
		dogName = name
		dogAge = age
	End Sub
End Class

Now we have a good class for managing dogs. And just to demonstrate, now we can make multiple dogs without having them to interfere with each other. And each object has it’s own settings, and you can also create more functions as you need. Now I’m just going to show of this last piece of code with 3 dogs.

Private Sub mainCodeHere()
	Dim dog1 As New Dog()
	dog1.createDog("Oskar", 7)
	Dim dog2 As New Dog()
	dog2.createDog("Karlo", 14)
	Dim dog3 As New Dog()
	dog3.createDog("Buster", 12)
	MsgBox(dog1.name & " is " & dog1.age.ToString() & " year(s) old!")
	MsgBox(dog2.name & " is " & dog2.age.ToString() & " year(s) old!")
	MsgBox(dog3.name & " is " & dog3.age.ToString() & " year(s) old!") 
End Sub

Congratulations, you just finished this basic course in OOP. I hope you will find this information useful, and use it in your own code. Feel free to ask questions, or comment about how you use it below.


VB.NET TCP File Transfer

Here it is as I promised!


Yesterday I needed to make a simple update procedure for my home automation software, so I could remotely send out updates from my laptop to the home server. While writing the software, I produced this class.


It’s by no means perfect or anything, but it worked for my needs and I think it may work for yours to ;)



A little warning, I saw that the file size sometimes increases a little. I’ve never seen a problem with it in my case (transfered both zips, exe’s and pictures.) But if you check the file with some hashfunction this could be a problem.


I’ve not looked more closely at the “problem” but I believe it to be somewhere within the buffers, and maybe when the file is written to disc. If anyone experiences any problems, they are free to contact me and we can try and work it out :)



Download link:



VB.NET File Transfer (186)


Enjoy! ;)