Skip to main content

Posts

Showing posts with the label c# Interview Question

Preprocess Win32 Messages through Windows Forms

In the unmanaged world, it was quite common to intercept Win32 messages as they were plucked off the message queue. In that rare case in which you wish to do so from a managed Windows Forms application, your first step is to build a helper class which implements the IMessageFilter interface. The sole method, PreFilterMessage(), allows you to get at the underlying message ID, as well as the raw WPARAM and LPARAM data. By way of a simple example: public class MyMessageFilter : IMessageFilter { public bool PreFilterMessage(ref Message m) { // Intercept the left mouse button down message. if (m.Msg == 513) { MessageBox.Show("WM_LBUTTONDOWN is: " + m.Msg); return true; } return false; } } At this point you must register your helper class with the Application type: public class mainForm : System.Windows.Forms.Form { private MyMessageFilter msgFliter = new MyMessageFilter(); public mainForm() { // Register message filter. Applicati...

Is it possible to output the command-line used to build a project in Visual Studio?

Now that Whidbey has been out in Beta for more than a few months, it seems worth revisiting some frequently asked questions which have different (better?) answers now. In Everett (v7.1) the answer used to be No. However, in Whidbey (v8.0), the answer is Yes (and No). For the yes part of the answer, after building, go to the Output Window, select "Show Output from: Build", and about half way down you will see a section like this: Target "Compile" in project "ConsoleApplication1.csproj" Task "Csc" Csc.exe /noconfig /warn:4 /define:DEBUG;TRACE /debug+ /optimize- /out:obj\Debug\ConsoleApplication1.exe /reference:C:\WINDOWS\Microsoft.NET\Framework\v2.0.31125\System.Data.dll, C:\WINDOWS.0\Microsoft.NET\Framework\v2.0.31125\System.XML.dll, C:\WINDOWS\Microsoft.NET\Framework\v2.0.31125\System.dll /target:exe /win32icon:App.ico AssemblyInfo.cs Class1.cs The task is invoking the IDE's in-process compiler to perform the equivalent of the above command-l...

How do I get and set Environment variables?

Use the System.Environment class.Specifically the GetEnvironmentVariable and SetEnvironmentVariable methods. Admitedly, this is not a question specific to C#, but it is one I have seen enough C# programmers ask, and the ability to set environment variables is new to the Whidbey release, as is the EnvironmentVariableTarget enumeration which lets you separately specify process, machine, and user.

How do I create a constant that is an array?

Strictly speaking you can't, since const can only be applied to a field or local whose value is known at compile time. In both the lines below, the right-hand is not a constant expression (not in C#). const int [] constIntArray = newint [] {2, 3, 4}; // error CS0133: The expression being assigned to 'constIntArray' must be constant const int [] constIntArrayAnother = {2, 3, 4}; // error CS0623: Array initializers can only be used in a variable or field // initializer. Try using a new expression instead. However, there are some workarounds, depending on what it is you want to achieve. If want a proper .NET array (System.Array) that cannot be reassigned, then static readonly will do for you. static readonly int [] constIntArray = new int[] {1, 2, 3}; The constIntArray field will be initialized before it its first use. If, on the other hand, you really need a const set of values (say as an argument to an attribute constructor), then - if you can limit yourself...

What is the difference between const and static readonly?

The difference is that the value of a static readonly field is set at run time, and can thus be modified by the containing class, w hereas the value of a const field is set to a compile time constant. In the static readonly case, the containing class is allowed to modify it only in the variable declaration (through a variable initializer) in the static constructor (instance constructors, if it's not static) static readonly is typically used if the type of the field is not allowed in a const declaration, or when the value is not known at compile time. Instance readonly fields are also allowed. Remember that for reference types, in both cases (static and instance) the readonly modifier only prevents you from assigning a new reference to the field. It specifically does not make immutable the object pointed to by the reference. class Program { public static readonly Test test = new Test (); static void Main ( string [] args) { test.Name = "Program"; test = new T...

How can I easily log a message to a file for debugging purposes?

Often, you need a way to monitor your applications once they are running on the server or even at the customer site -- away from your Visual Studio debugger. In those situations, it is often helpful to have a simple routine that you can use to log messages to a text file for later analysis. Here’s a simple routine that has helped me a lot for example when writing server applications without an user interface: using System.IO; public string GetTempPath() { string path = System.Environment.GetEnvironmentVariable("TEMP"); if (!path.EndsWith("\\")) path += "\\"; return path; } public void LogMessageToFile(string msg) { System.IO.StreamWriter sw = System.IO.File.AppendText( GetTempPath() + "My Log File.txt"); try { string logLine = System.String.Format( "{0:G}: {1}.", System.DateTime.Now, msg); sw.WriteLine(logLine); } finally { sw.Close(); } } With th...

How do I calculate a MD5 hash from a string?

It is a common practice to store passwords in databases using a hash. MD5 (defined in RFC 1321) is a common hash algorithm, and using it from C# is easy. Here’s an implementation of a method that converts a string to an MD5 hash, which is a 32-character string of hexadecimal numbers. public string CalculateMD5Hash(string input){ // step 1, calculate MD5 hash from input MD5 md5 = System.Security.Cryptography.MD5.Create(); byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input); byte[] hash = md5.ComputeHash(inputBytes); // step 2, convert byte array to hex string StringBuilder sb = new StringBuilder(); for (int i = 0; i sb.Append(hash[i].ToString("X2")); } return sb.ToString(); } An example call: string hash = CalculateMD5Hash("abcdefghijklmnopqrstuvwxyz"); …returns a string like this: C3FCD3D76192E4007DFB496CCA67E13BTo make the hex string use lower-case letters instead of upper-case, replace the single line inside the for loop with this li...

How do I send out simple debug messages to help with my debugging?

Visual Studio offers tons of useful debugging features and allows you to step through your code line-by-line. However, there are times when you don’t want to step through your application, but want to make it output simple text strings with variable values, etc. Enter the System.Diagnostics.Debug class and its Write* methods. By using the Debug class, you can output messages similarly to the way the Win32 API function OutputDebugString. However, the beauty of the Debug class is that when you build your application using the default Release configuration in Visual Studio, no code lines are generated for your Debug.Write* class. This means there’s no performance penalty for using the Debug class in release code. To use the Debug class, simply add the “using System.Diagnostics;” statement to your C# code file, and call Debug.Write: Debug.Write("Hello, Debugger!"); In addition to Write, you have the possibility to call WriteIf, WriteLine and WriteLineIf. For example: bool @this =...