C# – RSA encryption and decryption

Many software use RSA algorithm for generating serial key and protecting it from cracker to release key generator because RSA algorithm is too much complex. Cracking RSA private key from the public key encrypted with 1024 bit, is really not possible with power of current computer. Therefore RSA was applied in many security fields, especially in public key communication. There are a lot of articles on Internet describing how it works so I do not intend to discuss about this algorithm again in this blog. I just would like to make a small example to show how we encrypt and decrypt data with RSA which in some cases will help us to protect our data.
Usually when we encrypt and decrypt data, both of process will need the same key. However RSA allows us to encrypt data with a public key and decrypt data with another key. In .Net, we’ll use RSACryptoServiceProvider as our RSA engine.

Continue reading C# – RSA encryption and decryption

C#, WinForm, WPF – Low level hook keyboard to write a simple keylogger

When I saw a video tutorial for writing a simple keylogger in VB.NET, I would like to write my own one in C# because I do not like the way which the author of this video uses a timer to monitor which window is being now the foreground window. This simple keylogger bases on hooking low-level keyboard with API SetWindowsHookEx to get key input. What makes me interesting is Avira Antivirus does not recognize my keylogger as malicious software ^^. I think when I implement to send the report to email or open port to send data back to me, Avira recognizes it immediately.
The keylogger has a low-level hook keyboard engine class.

Continue reading C#, WinForm, WPF – Low level hook keyboard to write a simple keylogger

C# – Lambda expressions and access to modified closure

When I use Lambda expressions, I find out a strange and unexpected behavior. Let’s consider the following example

static ICollection<Func<string>> CreateExample1()
{
	ICollection<Func<string>> lstFunctions = new LinkedList<Func<string>>();
	for (int nIndex = 0; nIndex < cnst_nCount; nIndex++)
	{
		lstFunctions.Add(() => nIndex.ToString());
	}
	return lstFunctions;
}

static void Print(ICollection<Func<string>> lstFunctions)
{
	Console.WriteLine(string.Join(", ", lstFunctions.Select(f => f()).ToArray()));
}

What are we waiting for when calling Print(CreateExample1())? An output with “0, 1, 2, 3”? The answer is no. When we compile and run the code above we will have a black screen with array of “4, 4, 4, 4”. Why doesn’t it run correctly? Let’s go back to review how the Lambda expression work.

A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.
All lambda expressions use the lambda operator =>, which is read as “goes to”. The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block
.
The important feature of lambda expression that we must know is that it is evaluated during run-time. That means, in the example above, the lambda expression will be “compiled and executed” only when the for-loop starts to run. Therefore when the expression is being evaluated, the value of nIndex variable was changed and in our case the nIndex reaches it up-bound already when the evaluation of expression is going on.
To solve this problem, what we should do is pushing our variable nIndex into stack and when the expression is evaluated, it will pop the value from stack for its calculation.
To push value into stack, we can use a temporary variable to store current value of iteration variable.

static ICollection<Func<string>> CorrectExample()
{
	ICollection<Func<string>> lstFunctions = new LinkedList<Func<string>>();
	for (int nIndex = 0; nIndex < cnst_nCount; nIndex++)
	{
		int j = nIndex;
		lstFunctions.Add(() => j.ToString());
	}
	return lstFunctions;
}

So in the end of this blog, remember this hint “Using the iteration variable in a lambda expression may have unexpected results. Instead, create a local variable within the loop and assign it the value of the iteration variable.

WPF – Use ZedGraph in WPF application

Maybe you already know about ZedGraph. ZedGraph is a set of classes, written in C#, for creating 2D line and bar graphs of arbitrary datasets http://sourceforge.net/projects/zedgraph/ . If you need some basic samples for using this library you can read a useful article at CodeProject http://www.codeproject.com/KB/graphics/zedgraph.aspx . However this library now only supports Windows Form Application. If you want to host a graph on WPF application, you can follow the steps in this blog below. The main idea of this method is host a graph in a User Control of Windows Form and then host this user control in WPF application.

Continue reading WPF – Use ZedGraph in WPF application

C# – Notify modified properties of class

Today I follow a thread on mycsharp.de and discover an interesting post about finding out which property is just changed or modified http://www.mycsharp.de/wbb2/thread.php?threadid=80535 . This post was written in German and I just want to translate it into English. This example illustrates how we can monitor changes of properties. In the example below, I make a rectangle class with two properties Width, Height and Area property which is calculated by multiple Width with Height.

public class CustomRectangle
{
	private int nWidth;
	private int nHeight;

	public int Height
	{
		get { return nHeight; }
		set { nHeight = value; }
	}

	public int Width
	{
		get { return nWidth; }
		set { nWidth = value; }
	}

	public int Area
	{
		get { return Height * Width; }
	}
}

To notify which property is changed, the CustomRectangle class should implement INotifyPropertyChanged. Therefore I made some modifications to raise an event when a property is changed.

public class CustomRectangle : INotifyPropertyChanged
{
	...

	public int Height
	{
		...
		set { nHeight = value; NotifyPropertyChanged(MethodInfo.GetCurrentMethod()); }
	}

	public int Width
	{
		...
		set { nWidth = value; NotifyPropertyChanged(MethodInfo.GetCurrentMethod()); }
	}
	...
	public event PropertyChangedEventHandler PropertyChanged;
	public void NotifyPropertyChanged(String propertyName)
	{
		if (PropertyChanged != null)
		{
			PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
		}	   
		...
	}    
        public void NotifyPropertyChanged(System.Reflection.MethodBase methodBase)
	{
		NotifyPropertyChanged(methodBase.Name.Substring(4));
	} 
}

In the code snippet above, reflection was used to identify which method is being called. However the property Area based on Width and Height still does not raise any event. This property is changed when Width or Height is changed, therefore we must notify the property Area whenever Width/Height is set. As introduced in the thread on mycsharp.de, we can use a custom attribute for Area and then use reflection to find out which property Area depends on, is changed to raise an event simultaneously.

[DependsUpon("Height", "Width")]
public int Area
{
	get { return Height * Width; }
}

[global::System.AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
sealed class DependsUponAttribute : Attribute
{
	#region Private Members
	private readonly string[] lstProperties;
	#endregion

	#region Public Properties
	public string[] Properties
	{
		get { return lstProperties; }
	}
	#endregion

	#region Constructors
	public DependsUponAttribute(params string[] properties)
	{
		this.lstProperties = properties;
	}
	#endregion
}

public void NotifyPropertyChanged(String propertyName)
{
	if (PropertyChanged != null)
	{
		PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
	}   
	if (dictPropertyDependencies.ContainsKey(propertyName))
	{
		string[] depended = dictPropertyDependencies[propertyName];
		foreach (var propName in depended) NotifyPropertyChanged(propName);
	}  
}

The main idea of this method is introduced above however you will need the complete source code to understand more about this structure. You can download here “Notify modified properties