Difference between LINQ and lambda expression

I have stuck at this field for a long time. Today it suddenly becomes clear to me: LINQ and lambda expressions are to very different things (though they complements each other on many occasions).

Lambda expression

Lambda expression, to sum up, is only about the operator “=>” (read as “goes to”). It serves as a shorthand for anonymous function (usually used to write short expressions like “x => x % 2 == 0” to find even numbers). It will be automatically typed as either an Expression, a delegate or a Func depending on where it is used.

LINQ

LINQ is like SQL for objects. It can query arrays, list or any other enumerable objects. It’s sort of an advanced for loops with SQL-like operations like sorting, grouping and of course, lambda expression support. Usual syntax is “from <iterator name> in <data> where <condition on iterator> select <iterator>”

Note on capturing value of a variable in an anonymous function

Extraction from “C# programming language 4th edition”

When not captured, there is no way to observe exactly how often a local variable is instan-tiated: Because the lifetimes of the instantiations are disjoint, it is possible for each
instantiation to simply use the same storage location. However, when an anonymous
function captures a local variable, the effects of instantiation become apparent.
The example

using System;
delegate void D();
class Test 
{
static D[] F() {
D[] result = new D[3];
for (int i = 0; i  { Console.WriteLine(x); };
}
return result;
}
static void Main() {
foreach (D d in F()) d();
} 
}

produces the following output:
1
3
5
However, when the declaration of xis moved outside the loop

static D[] F() {
D[] result = new D[3];
int x;
for (int i = 0; i  { Console.WriteLine(x); };
}
return result; 
}

the output is
5
5
5
If a forloop declares an iteration variable, that variable itself is considered to be declared
outside of the loop. Thus, if the example is changed to capture the iteration variable itself,

static D[] F() {
D[] result = new D[3];
for (int i = 0; i  { Console.WriteLine(i); };
}
return result; 
}
only one instance of the iteration variable is captured, which produces the following 
output:
3 
3 
3

The reason is C# capture the variable, not the value. It’s a bit hard to warp your head around this

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

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

How to cope with designer errors in Visual Studio

From time to time, when you have some errors in your controls, Visual may just stop responding altogether and forces you to restart without any indicator on what happened and how to fix it. To overcome this, there is two things developers should keep in mind:

  1. Check database and connection routines, make sure they are initialized properly or blocked from running by checking the special property DesignMode (available as Form.DesignMode and UserControl.DesignMode).
  2. To see the cause of the error, you have to debug Visual Studio itself. When designer error happened to you, choose debug this program and start a new instance of Visual Studio. The second instance should give you the unhandled exception and the code location of the error.
I think this is an artifact from the first days of Visual Studio carried over when they expect all code to behave (after all, developers have to spend years just for planning and resources is not available as much as today). For this Microsoft are way behind Eclipse: In android development tools, if you have errors in your control, the designer at least give you a message about the error and refuses to continue rendering the screen but it won’t crash. Visual Studio, on the other hand, requires a full restart which consumes a lot of time (this particular time it took me 2 hours to find the source of the error).