C# – How to fix “Invalid algorithm specified” when signing with SHA256

A digital signature or digital signature scheme is a mathematical scheme for demonstrating the authenticity of a digital message or document. A valid digital signature gives a recipient reason to believe that the message was created by a known sender, and that it was not altered in transit. Digital signatures are commonly used for software distribution, financial transactions, and in other cases where it is important to detect forgery or tampering (From Wikipedia)”. If you are now working in information security fields, you should be familiar with this concept. Since version .Net Framework 3.5 SP1, Microsoft has supported for signing and verifing digital signature with SHA256. However maybe you’ll get an error “Invalid algorithm specified” if trying to sign data with SHA256. To reproduce the error, I would like to make a demo of code for signing with SHA256 in the code below

Continue reading C# – How to fix “Invalid algorithm specified” when signing with SHA256

C# – Print all MS Office 2010/2013 ImageMso to files

Last month I received a project for converting an Access application from version 97 to version 2010. Thanks to good MS Access I don’t have to change a lot of things. Just replace some not working components like ListView, TreeView, ImageList with the new ones and edit some code behind so that the program works. For example ListView component needs header definition if we want to access it according to columns. There is only one big problem which takes me a lot of time is the menu. Menu is still supported in Office 2010 but with a lot of limitations because he is now replaced by ribbon bar.

Continue reading C# – Print all MS Office 2010/2013 ImageMso to files

C# – Get free space of network harddisk

Although working as a software developer but I am interested in Networking too. Yesterday when I was “running around” the file servers of my company, I found an interesting question but I can not answer myself therefore I would like to post my question here so that if someone knows the answer can help me. In my company there is a server whose name is “srvxxxx” and publicizes theses folders to all network users

Folder Network

For each folder above I can use the command “net use” to map them to my local disks like this

net use T: \\SRVxxxx\Txxxxxxx		/persistent:yes

Then I have a list of network mapped disks with description about how much free space and total space there are. The free space and total space belong of course to the hard disk where these folders lie.

Network mapped disks

So it’s great but if I open server “srvxxxx” in Windows Explorer and take a look at property of the folder which is mapped to my local disks, I can’t see any information about free space, files or something like that.

Network Folder Properties

My question is why I can’t see the information about files and free space when I am browsing directly on server? Only mapping these folders to local hard disk, then these information will be shown. So I tried to answer myself by making a small code to give me these information. First, I would like to list my local hard disks with their spaces. It’s pretty easy with help of DriveInfo class of .Net Framework.

private static void FreeSpaceLocal()
	DriveInfo[] allDrives = DriveInfo.GetDrives();

	foreach (DriveInfo d in allDrives)
		Console.WriteLine("Drive {0}", d.Name);
		Console.WriteLine("  File type: {0}", d.DriveType);
		if (d.IsReady == true)
			Console.WriteLine("  Volume label: {0}", d.VolumeLabel);
			Console.WriteLine("  File system: {0}", d.DriveFormat);
			Console.WriteLine("  Available space to current user:{0, 15} bytes", d.AvailableFreeSpace);
			Console.WriteLine("  Total size of drive:            {0, 15} bytes ", d.TotalSize);

Then I tried with a remote computer in same LAN but the DriveInfo class can not resolve the UNC Path which looks like this “\\computername\c$”. Therefore to get information of remote computer , I need a reference to System.Management


and then I will use WMI to fetch the information of the remote harddisk. Windows Management Instrumentation (WMI) is the infrastructure for management data and operations on Windows-based operating systems. You can write WMI scripts or applications to automate administrative tasks on remote computers but WMI also supplies management data to other parts of the operating system and products, for example System Center Operations Manager, formerly Microsoft Operations Manager (MOM), or Windows Remote Management. (MSDN)

private static void FreeSpaceNetwork(string srvname)
		ConnectionOptions conn = new ConnectionOptions();
		string strNameSpace = @"\\";
		if (srvname != "")
			strNameSpace += srvname;
			strNameSpace += ".";
		strNameSpace += @"\root\cimv2";
		System.Management.ManagementScope managementScope = new System.Management.ManagementScope(strNameSpace, conn);
		System.Management.ObjectQuery query = new System.Management.ObjectQuery("select * from Win32_LogicalDisk where DriveType=3");
		ManagementObjectSearcher moSearcher = new ManagementObjectSearcher(managementScope, query);
		ManagementObjectCollection moCollection = moSearcher.Get();
		foreach (ManagementObject oReturn in moCollection)
			//foreach (PropertyData prop in oReturn.Properties)
			//    Console.WriteLine(prop.Name + " " + prop.Value);

			Console.WriteLine("Drive {0}", oReturn["Name"].ToString());
			Console.WriteLine("  Volume label: {0}", oReturn["VolumeName"].ToString());
			Console.WriteLine("  File system: {0}", oReturn["FileSystem"].ToString());
			Console.WriteLine("  Available space to current user:{0, 15} bytes", oReturn["FreeSpace"].ToString());
			Console.WriteLine("  Total size of drive:            {0, 15} bytes ", oReturn["Size"].ToString());
	catch (Exception ex)

If you want to know more about WMI, I warmly introduced this link http://msdn.microsoft.com/en-us/library/aa394582%28v=vs.85%29.aspx which explains and discusses about how WMI works, what WMI provides and how to use it in your application with many examples or a book if you don’t like to sit for hours in front of computers

VBScript, WMI, and ADSI Unleashed: Using VBScript, WMI, and ADSI to Automate Windows Administration

Although the code about works perfectly with a normal remote computer but when I tried to fetch information of the server I got an error with “Access denied” although I have administrator right and already set administrator login (Username and Password) for the connection. Until now I still don’t understand why it does not work with the server. If you are interested in the source code for getting free space of remote computer, you can get it here “Free Space Harddisk“.

C# – Action delegates

When I am browsing the source code of my team, I see a lot of styles writing Action delegate. It makes me really interesting that my team has made use of this delegate to write more beautiful, shorter and sometimes… messy code. Therefore I would like to extract and reform some typical examples from our source code to this blog to show how Action delegate could be used in real application. According to MSDN, Action delegate encapsulates a method that has a single parameter and does not return a value with this syntax

public delegate void Action<in T>(T obj)

where as
in T: The type of the parameter of the method that this delegate encapsulates and
T obj : The parameter of the method that this delegate encapsulates.

If you want to read more, you can follow this link http://msdn.microsoft.com/en-us/library/018hxwa8.aspx. In this small blog, I just want to enumerate 6 typical examples of Action which are used in my team.

1. Example One.

private void btnExampleOne_Click(object sender, RoutedEventArgs e)
	Action<string> PrintString = new Action<string>(PrintStringToConsole);
	List<string> names = new List<string>() { "Example One","W", "A", "S", "T" };
	btnExampleOne.IsEnabled = false;
private void PrintStringToConsole(string name)
	txtResult.Text += Environment.NewLine + name;

The Example One shows a typical example of Action with data type in C# version before 3.0. I define a function (PrintStringToConsole) with a single paramter and define an Action delegate to encapsulate this parameter then call this action in foreach loop. You can replace data type “string” with any other data type which you want to apply the Action.

2. Example Two

private void btnExampleTwo_Click(object sender, RoutedEventArgs e)
	List<string> names = new List<string>() { "Example Two", "W", "A", "S", "T" };
	names.ForEach(x =>
		txtResult.Text += Environment.NewLine;
		txtResult.Text += x;
	btnExampleTwo.IsEnabled = false;

This example doesn’t do anything different to the first one. But with the help of Lambda Expression, I can define the function intern the foreach loop which make it easier to follow if the function is short and really complex to follow if the function is too long. Believe me, I have met a long long loo…ng function with this art of Action delegate and I really forgot what I was reading before going into the foreach loop. So don’t make your collegueas angry with this coding style.

3. Example Three

private void btnExampleThree_Click(object sender, RoutedEventArgs e)
	txtResult.Text += Environment.NewLine + "Example Three";
	Dictionary<Role, Action<Employee>> taskList = new Dictionary<Role, Action<Employee>>();
	taskList.Add(Role.Chef, Planning);
	taskList.Add(Role.Developer, Developing);
	Employee w = new Employee() { Name = "W" };
	btnExampleThree.IsEnabled = false;
private void Planning(Employee employee)
	txtResult.Text += Environment.NewLine +  "Employee " + employee.Name + " is on planning task";

private  void Developing(Employee employee)
	 txtResult.Text +=Environment.NewLine + "Employee " + employee.Name + " is on developing task";


enum Role

class Employee
	public string Name { get; set; }

Example Three demonstrates the ability to assign approriate Action for each object according to predefined types. You can see in the example that each Role has his own Action. The Chef should plan resources, projects,cost … and the Developer does his job with programming,basic testing,writing documentation …. I can then examine an Employee with a Role and see how he behaves with this Role through the defined Action. It’s really comfortable for testing, simulating or applying Action on many objects without writing divergently specific code for each type of objects.

4. Example Four

private void btnExampleFour_Click(object sender, RoutedEventArgs e)
	Dictionary<Type, Action<Control>> controlDefaults = new Dictionary<Type, Action<Control>>()
		{typeof(TextBox), x => ((TextBox)x).Text = "Result will be shown hier: "},
		{typeof(Button), x => ((Button)x).IsEnabled = true},

	FindVisualChildren<Control>(gridMain).ToList().ForEach(x =>
			if (controlDefaults.ContainsKey(x.GetType()))
public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
	if (depObj != null)
		for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
			DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
			if (child != null && child is T)
				yield return (T)child;

			foreach (T childOfChild in FindVisualChildren<T>(child))
				yield return childOfChild;

Bases on Example Three, Example Four shows how we can easily reset all controls on form. Just declare their types with approriate action, loop through all controls and use the Action defined for them in Dictionary Set. It can not be simple and more beautiful.

5.Example Five

btnExampleFive.Click += (sender, e) =>
	txtResult.Text += Environment.NewLine + "Example Five" + Environment.NewLine + "Hey, hey I am an Action event";
	btnExampleFive.IsEnabled = false;

Again, I have a Lambda Expression for registering an Action to a click event of a button. When you are lazy to browse to Visual Studio Designer, use this way.

6. Example Six

private void btnExampleSix_Click(object sender, RoutedEventArgs e)
	this.Dispatcher.Invoke(new Action(() => 
			txtResult.Text += Environment.NewLine + "Example Six" + Environment.NewLine + "Go back to GUI thread from another one";
			btnExampleSix.IsEnabled = false;

Now is the last example with an anonymous Action without any input argument which is normally used in my team for updating GUI from another Thread. Ofcourse you should replace “this” with your GUI UIElement which I discussed in this blog before http://hintdesk.com/c-wpf-copy-files-with-progress-bar-by-copyfileex-api/

This is the end of this blog. Nothing special, just enumerate some styles of Action delegate which are used in our source code. There are of course more of them but I would like to discuss some most popular ones. The source you can download here “Action delegates