C# – Be careful when using struct to implement interface

All .net programmers know class can implement interface but I think that not all of them know a struct can implement an interface too. But there are a problem that we should take care when we use struct to implement interface. In this example below I would like to make a small example to demonstrate the problem. The complete source code is below. We just modify some words to cause problem.

interface IAccount
{
	void UpLevel();
}

class GameAccount : IAccount
{
	public string Name;
	public int Level;

	public GameAccount(string strName, int nLevel)
	{
		Name = strName;
		Level = nLevel;
	}

	public override string ToString()
	{
		return String.Format("{0} {1}", Name, Level);
	}

	#region IAccount Members

	public void UpLevel()
	{
		Level++;
	}

	#endregion
}

class Program
{
	static void Main(string[] args)
	{
		GameAccount gaAcc = new GameAccount("rongchaua", 95);
		IAccount iaAcc = gaAcc;
		Console.WriteLine(gaAcc);
		iaAcc.UpLevel();
		Console.WriteLine(gaAcc);
		Console.ReadLine();
	}
}

In the code snippet above I show a completely normal code in which I define an interface and a class to implement it. Run the program, you can see on the console screen.

It’s ok. The code does as we want. Variable of type IAccount iaAcc points exactly to memory space of gaAcc and when we increase level, the level of gaAcc object will increase too. Perfect. Now change class GameAccount to a struct.

struct GameAccount : IAccount
{
	 ...
}

What happens here now? Why do we have a false result? Obviously a boxing occurs here. When we casting a struct to interface, the compiler will automatically “box” it to a temporary class object and then the interface variable will point to this temporary class object, not the original struct any more. Therefore when we increase level, we are increasing the level of the temporary object, not the level of struct gaAcc.
So maybe you have another question. Ok, an automatic boxing took place. Why don’t we try to out boxing and test if the reference still works?

static void Main(string[] args)
{
	GameAccount gaAcc01 = new GameAccount("rongchaua", 95);
	GameAccount gaAcc02 = gaAcc01;
	Console.WriteLine(gaAcc01);
	gaAcc02.UpLevel();
	Console.WriteLine(gaAcc01);
	Console.ReadLine();
}

And the result is

Conclusion: Struct is a value-type. Be careful when using struct to implement your interface.

Security – How does Desktop Phishing work?

I think most of you know about the work “Phishing”. “In the field of computer security, phishing is the criminally fraudulent process of attempting to acquire sensitive information such as user names, passwords and credit card details by masquerading as a trustworthy entity in an electronic communication.“. I think an example is easier to understand about phishing. For example, I am a Yahoo user and I use their email service. When I want to log into my email account, I go to http://mail.yahoo.com, enter my user name and password and I can access my in-box. On one beautiful day, I decide to use a third party service which is relevant to yahoo, for example checks if my friends are invisible or makes my nick appear online as long as I want. To use this service, I must enter my user name and password. The services ensure that they will not steal my data by redirecting me to a page that looks like a yahoo login page.

Ah ha, I know this page. It “must” be Yahoo log in page, everything is same. I enter my data and some days later I lost my email account. If you are enough careful, you can immediately recognize this fake website through its URL. But what will happen, if you are hurry and have no time to check URL? Then your data will be phished. Man calls it Web Phishing.
Not long ago I heard about a new technique so called “Desktop Phishing”. This phishing will attack directly to your domain name resolver and redirect you to a phishing web page and you can not know that you are attacked because there are no fake URL anymore.
The main idea of this attack work as following (Windows OS) that your host file (http://en.wikipedia.org/wiki/Hosts_file) will be edited. A new entry with the format of “IP_Address domain_name” will be inserted. The IP_Address is the IP of the server of attacker. At this server he will build a web page that looks like the domain_name which he want to attack. To edit this host file, he’ll try to send to a victim a malicious file which runs malicious code to override our host file with his host file. Therefore when we try to access the reliable web page we will be redirected to attacker’s server.
For example, Yahoo page has its IP address 87.248.113.14, when we want to go to Yahoo page, our resolver will resolve the domain name to IP address and give the IP address back to our browser and the connection will be established. But at desktop phishing, a new entry will be inserted “141.84.69.20 http://yahoo.com”. Therefore if we want to go Yahoo page, instead of asking our DNS, the operating system will give this fake “141.84.69.20” back to our browser and the connection will be established between our browser and this fake one.
For more details, you can see this video (it’s not made by me)
Mirror 1: http://www.mediafire.com/?hifrbssi2r3dn4k
Mirror 2: http://www.box.com/s/882179a8043e09e22bf9

UPDATE 12.04.2012
Update download link

.Net PE File Format Library

Net PE File Format Library is a library to read information from a .net assembly. I wrote this library first for me, because sometimes when I write an unpacker I need to read the value of packed files, fix them and write them to a new one. It’s a lightweight library for .net PE file format; it based on the structure which CFF Explorer categories. That means what you see when you view an assembly with CFF Explorer, you can use this library to read that value. It is not as strong as Mono.Cecil, it can not handle the IL code and so far but I think it will be great in some cases when we just want to read some values of PE file format.

To use this library, you need add a reference to the assembly and declare in header that you’ll use it like this

using DotNetPeFileFormat;

To read values in PE of an assembly, you should create a new instance

PEFileFormat peffSource = new PEFileFormat(txtPath.Text);

And now you can read the values of this assembly, for example

peffSource.WriteDwordToArrayFromIndex(aOriginal, peffSource.OffsetToRva(nEntryPoint, peffSource.NTHeaders), 0xA8);

In above example, you can get the complete NTHeaders of that assembly, change an RVA address to Offset address and use an add-in function to write values into an array.

As I say, this library I wrote for my own uses. But I think I will help someone too. Don’t hesitate to ask if you do not know how to use it and your comments will be appreciated
* Requirements : .NET Framework 2.0
* Version: 1.0.0.1
NOTE:
* Don’t hesitate to ask if you don’t know how to use it. If you need more functions just post a comment.

LINK DOWN: When you want to post this libray to somewhere. Please post url to my site, that keeps update for this libray when you do that.
Download: http://hintdesk.com/Web/Tool/DotNetPeFileFormat.zip
HISTORY:
* [1.0.0.1] : Fix bugs
* [1.0.0.0] : BETA Version.

C# – Use BackgroundWorker to update GUI component

In this small blog I would like to review the way to use BackgroundWorker and pass arguments to it. As all of you know that BackgroundWorker executes an operation on a separate thread. Time-consuming operations like downloads and database transactions can cause your user interface (UI) to seem as though it has stopped responding while they are running. When you want a responsive UI and you are faced with long delays associated with such operations, the BackgroundWorker class provides a convenient solution. To execute a time-consuming operation in the background, create a BackgroundWorker and listen for events that report the progress of your operation and signal when your operation is finished.

As shown in image above, the dialog has two text boxes which indicate the path of the directory and the pattern of file which we want to search for. The program will search recursively and returns the result back into list view. In the code handles event click of btnStart, you can see how we pass the argument to BackgroundWorker. The arguments will be converted to array of string and passed away.

private void btnStart_Click(object sender, EventArgs e)
{
	if (btnStart.Text == "Start")
	{
		if (!Directory.Exists(txtSearchPath.Text.Trim()))
		{
			MessageBox.Show("The Search Directory does not exist","Path Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
		}
		else
		{
			if (txtSearchPattern.Text == "") txtSearchPattern.Text = "*";
			string[] args = new string[]{txtSearchPath.Text.Trim(),txtSearchPattern.Text.Trim()};
			lstFiles.Items.Clear();
			m_bgWorker.RunWorkerAsync(args);
			btnStart.Text = "Stop";
		}
	}
	else
	{
		m_bgWorker.CancelAsync();
	}
}

In the function which handles the DoWork event will filter the arguments back and start the asynchronous file search. The background thread does its work from this event. Please note that we should not write any code to update GUI in this function.

void m_bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
	string strPath = ((string[])e.Argument)[0];
	string strPattern = ((string[])e.Argument)[1];
	m_lstFiles = new List<string>();
	SearchFiles(strPath, strPattern);
	e.Result = "Found " + m_lstFiles.Count + " files";
}

private void SearchFiles(string strPath, string strPattern)
{
	string strMessage = "Parsing directory " + strPath;
	m_bgWorker.ReportProgress(0, strMessage);
	foreach (string strFileName in Directory.GetFiles(strPath, strPattern))
	{
		if (m_bgWorker.CancellationPending)
		{
			return;
		}
		else
		{
			m_lstFiles.Add(strFileName);
		}
	}

	foreach (string strDirName in Directory.GetDirectories(strPath))
	{
		if (m_bgWorker.CancellationPending)
		{
			return;
		}
		else
		{
			SearchFiles(strDirName, strPattern);
		} 
	}
}

To update GUI, we should write it in the ProcessChanged.

void m_bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
	if (bCallInProgress)
	{
		return;
	}
	else
	{
		bCallInProgress = true;
		lblMessage.Text = e.UserState.ToString();
		for (int nIndex = lstFiles.Items.Count; nIndex < m_lstFiles.Count ; nIndex++ )
		{
			lstFiles.Items.Add(m_lstFiles[nIndex]);
		}
		bCallInProgress = false;
	}
}

The bacground thread calls this event when you make a call to ReportProgress. It is OK to access user controls in the UI from this event. If you use a Progress Bar or some other control to report the tasks progress. You should avoid unnecessary calls to ReportProgress method because this causes a thread switch which is a relatively expensive in terms of processing time.
Source code: https://bitbucket.org/hintdesk/dotnet-use-backgroundworker-to-update-gui-component/

WPF – Use DataTrigger to set property of component

In Windows Form Programming, if we want to create a data trigger for a component we need to write code to process data change event and give suitable data back. In WPF Microsoft allows us to bind trigger direct to component in XAML code without writing any code. DataTrigger represents a trigger that applies property values or performs actions when the bound data meets a specified condition.

In this example below I would like to demonstrate how we create data trigger in WPF.
I place on grid a combo box and two text box. Then I add 3 combo box item “One”, “Two”, and “Tree”.

<ComboBox Height="26" Margin="34,32,137,0" Name="cbSelection" VerticalAlignment="Top">
	<ComboBoxItem>One</ComboBoxItem>
	<ComboBoxItem>Two</ComboBoxItem>
	<ComboBoxItem>Three</ComboBoxItem>
</ComboBox>
<TextBox  Height="23" Margin="34,0,138,90" Name="txtSelectionOne" VerticalAlignment="Bottom">
</TextBox>
<TextBox  Height="23" Margin="34,0,138,45" Name="txtSelectionTwo" VerticalAlignment="Bottom" >
</TextBox>

Style, ControlTemplate, and DataTemplate all have a triggers collection. A DataTrigger allows you to set property values when the property value of the data object matches a specified Value. Note that you must specify both the Binding and Value properties on a DataTrigger for the data trigger to be meaningful. If one or both of the properties are not specified, an exception is thrown. The Setters property of a DataTrigger object can only consist of Setter objects.
In our example we want when the combo box has value “One”, the text box one will be selected and “Two” for text box two. So we insert the data trigger into Style of each text box.

<TextBox  Height="23" Margin="34,0,138,90" Name="txtSelectionOne" VerticalAlignment="Bottom">
	<TextBox.Style>
		<Style>
			<Setter Property="TextBox.IsEnabled" Value="False"/>
			<Style.Triggers>
				<DataTrigger Binding="{Binding ElementName=cbSelection , Path=Text}" Value="One">
					<Setter  Property="TextBox.IsEnabled" Value="true"/>
				</DataTrigger>
			</Style.Triggers>
		</Style>
	</TextBox.Style>
</TextBox>

The property value produced by this binding is compared with the value specified by the Value property. That value is first converted to the type of the value of the binding (if possible), and then the two values are compared using the Object.Equals method. If the two values are equal, then the associated actions or setters are applied.
For the text box two, you just need to copy same code with small changes and everything will work.