Calling C# from C++

Most of the post on the internet about interoperability is the other way around (Calling C++ from C#) since C# is apparently the superior language in terms of developer friendliness. But a part of research work is to make weird combinations of system work regardless of the reason.

I succeeded in doing just that thank to this Visual C++ example (documentation is available in part 1 of the tutorial).

One thing to add is, I needed a tool to export .NET 4.0 to .tlb files so I can use the same assemblies in C++ (pure C++ and not C++.NET). The tool is called tlbgen, and the syntax is quite simple:

tlbgen System.Net.dll

Web service for device (WS4D) and using make, cmake with Integrated Development Environments (IDEs) on Linux

WS4D-gSOAP is a framework to deploy web services on multiple environments (computers, embedded devices, phones…) without having to rewrite code. More introduction information can be found in this post. The downside for WS4D is that the build system is based on cmake, and it’s a bit complicated to use. I have since managed to successfully build the stack from source (there’s no binary distribution). But I ran into numerous problems during my time getting familiar with the stack. Namely following the tutorial.

Even for such a simple task of copying and pasting code from the tutorial (The Air Conditioner tutorial), I did not succeed. The client and device doesn’t seem to be able to communicate with each other. Even though the tutorial have been kind enough to include logging code (send, received and memory allocations), I’m still unable to figure out where the problem lies. And that’s when I think I’m forced to perform debugging on the project. That leads to a big problem: what am I supposed to use to debug this?

So I tried to install Code Blocks, but it doesn’t support cmake projects, it couldn’t import the CMakeList.txt. Then reading through several articles revealed Eclipse to be a pretty good gdb front-end, I installed it, and have successfully imported the project, but I was hit with several problems:

  • I couldn’t build the project, Eclipse’s project structure was make-based, not cmake-based, trying to ‘make all’ or ‘make clean’ with Eclipse obviously would generate errors
  • Editing  the code is an eyesore because Eclipse doesn’t seem to be able to recognize include and libraries directories even after I added them manually in project properties.
After several more hours of analyzing WS4D-gSOAP documentation (not really helpful, they are only related to build and run with command line), cmake (wiki pages after wiki pages with no structure between pages and in articles), Eclipse and Code Blocks’ documentation on make projects; I finally realized the right way to do this: cmake supports generating make-based projects for both Code Blocks and Eclipse, and it’s as simple as this:
  1. Go to the directory where you would normally run cmake to build your project from the command line
  2. Perform

    cmake -G"Eclipse CDT4 - Unix Makefiles" -D CMAKE_BUILD_TYPE=Debug ../certi_src
    cmake . -G "CodeBlocks - Unix Makefiles"
  3. Import

    The project directory
    ProjectName.cbp file
You can now work with the project normally within your preferred IDE

Management task: Remote shutdown utility

I run a simple web server to serve as a storage medium for my mobile devices (I don’t like using dropbox or other online storage solutions because they don’t offer much space and they hogs up bandwidth unnecessarily). Before I go to sleep I usually shut down the server to save energy, but in order to do so, I have to have another computer turned on to perform remote access into the server and shut it down via command line. Occasionally, I would turn off my work computer before I remember that I want to shut down the server and I’m too lazy by then to turn on my work computer again.

That’s why I wanted an application that is capable of shutting down Windows on my behalf. The scenario is like this: because I can access FTP service from my phone, I will create a file, namely ‘shutdown’; when the server sees this file, it will delete the file and initiate shutdown. Quite simple.

To shut down, I use Windows management interface (System.Management namespace in C#)

        static void Shutdown()
        {
            ManagementBaseObject mboShutdown = null;
            ManagementClass mcWin32 = new ManagementClass("Win32_OperatingSystem");
            mcWin32.Get();

            // You can't shutdown without security privileges
            mcWin32.Scope.Options.EnablePrivileges = true;
            ManagementBaseObject mboShutdownParams =
                     mcWin32.GetMethodParameters("Win32Shutdown");

            // Flag 1 means we want to shut down the system. Use "2" to reboot.
            mboShutdownParams["Flags"] = "1";
            mboShutdownParams["Reserved"] = "0";
            foreach (ManagementObject manObj in mcWin32.GetInstances())
            {
                mboShutdown = manObj.InvokeMethod("Win32Shutdown",
                                               mboShutdownParams, null);
            }
        }

From here

And the rest is just a loop to check if the file exists

        /// 
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            while (true)
            {
                if (!System.IO.File.Exists("D:\Shutdown"))
                {
                    Thread.Sleep(500);
                }
                else
                {
                    System.IO.File.Delete("D:\Shutdown");
                    Shutdown();
                    return;
                }
            }
        }

That’s it, I run the application and it will wait until I create a file named ‘shutdown’ in D:, it will perform shutdown and quit

Here’s the sample code and binary

Java snippets of the day

Palindrome test

import java.util.Scanner;

public class PalindromeTest {
    static boolean isPalindrome(String source) {
		// Trivial case
        if (source == null)
            return false;
		// We ignore case when checking for palidrome
        String toTest = source.toLowerCase();
		// We start at the two ends of the string
        int start = 0;
        int end = toTest.length() - 1;
		// When the ends doesn't meet
        while (start < end) {
			// If they are not characters (like punctuation and spaces, we ignore them by
			// moving the pointer to the next character
            while (!Character.isLetter(toTest.charAt(start)))
                start++;
			// Similiar for the end pointer
            while (!Character.isLetter(toTest.charAt(end)))
                end--;

			// Compares the end and start pointer
            if (toTest.charAt(start) != toTest.charAt(end))
                return false;

			// Match, move to the next position
            start++;
            end--;
        }
		// The whole string has been testetd, so it's a palidrome
        return true;
    }

    public static void main(String[] args) {
        System.out.println(isPalindrome("Dammit I'm mad"));
        System.out.println(isPalindrome("Was it a car or a cat I saw"));
        System.out.println(isPalindrome("A man, a plan, a canal - Panama!"));
        System.out.println(isPalindrome("Are we not drawn onward, we few, drawn onward to new era?"));
        System.out.println(isPalindrome("Go hang a salami; I'm a lasagna hog!"));
        System.out.println(isPalindrome("aaaaaaaaaaao"));
    }
}

String permutation

	import java.util.ArrayList;

	public class PermutationPrinter {

		// Returns the list of possible permutations
		static ArrayList getPermutations(String target) {
			ArrayList result = new ArrayList();
			if (target.length() == 1) {
				// There's only one permutation for "a", right?
				result.add(target);
			} else {
				// There's target.length() way to select a character from a string, so...
				for (int i = 0; i < target.length(); i++) {
					// We iteratively pick characters
					char theChar = target.charAt(i);
					// Take them out of the question, then find the rest 's permutation, the string is
					// smaller by one character, and it will keep getting smaller until there's only 1
					// character left
					ArrayList smaller = getPermutations(target.substring(0, i) + target.substring(i + 1));
					// For each permutation string of the smaller string, add the original character into it
					for (String s: smaller) {
						 result.add(theChar + s);
					}
				}
			}
			// Return theh result
			return result;
		}

		public static void main(String[] args) {
			ArrayList p = getPermutations("1234");
			for (String s: p) {
					System.out.println(s);
			}
		}
	}

A readable example of how code become unreadable

Consider the following problem: You need to calculate how many dots are there in a square triangle for a specific width, for example

.
..
...

Has an area of 6

.
..
...
....

Has an area of 10
The catch is, you are not allowed to use the mathematical formula to calculate the number instantly, so there’s two ways remaining to solve this problem:

  • Use two for loops
  • Recursion

We will follow the second direction because it’s probably shorter to write, so someone wrote

public class TrianglePrinter {
    static int getTriangleArea(int width) {
        int result = 0; // Default return
        if (width > 0) { // Stop condition
            result = getTriangleArea(width - 1) + width; // Split the problem
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(getTriangleArea(4));
    }
}

This can be “optimized” to become a one-line method, short code gives longer lives!

public class TrianglePrinter {
    static int getTriangleArea(int bottomWidth) {
        return (bottomWidth > 0) ? getTriangleArea(bottomWidth - 1) + bottomWidth : 0;
    }

    public static void main(String[] args) {
        System.out.println(getTriangleArea(4));
    }
}

Then when it is compacted (like, in Javascript…)

public class TrianglePrinter {
    static int g(int w) {
        return (w > 0) ? g(w - 1) + w : 0;
    }

    public static void main(String[] args) {
        System.out.println(g(4));
    }
}