Monday, June 2, 2014

Buggy for loop in C#

"for" loop appears to behaves abnormally when put in test to iterate through a whole range of "Integers", "Double", "byte", etc. However, this seems to be buggy but this situation arises due to "check arithmetic" that is used by default when incrementing the loop control variable beyond its maximum value which makes it value overflows and the loop restart's at the type's minimum value.

At first glance following example of for loop iteration seems to be fine and appears that it will iterate through the full range of the byte data type. However, the loop control variable can never exceeds than byte.MaxValue and it will reinitializes to byte.MinValue which makes it an infinite loop as predicate always evaluate it to true.


for (byte b = byte.MinValue; b <= byte.MaxValue; b++)
{
   Console.WriteLine(b);
}

Saturday, March 1, 2014

Detecting 64 Bit Operating System

There are several ways to determine the 64 bit operating system on this post we will look on two most preferred ways of detecting it in .Net framework.

Solution 1:
With the help of following extern methods

[DllImport("kernel32.dll")]
static extern IntPtr GetCurrentProcess();

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
static extern IntPtr GetModuleHandle(string moduleName);

[DllImport("kernel32", CharSet = CharSet.Auto, SetLastError = true)]
static extern IntPtr GetProcAddress(IntPtr hModule, [MarshalAs(UnmanagedType.LPStr)]string procName);

[DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool IsWow64Process([In] IntPtr hProcess, [Out] out bool lpSystemInfo);

static bool DoesWin32MethodExist(string moduleName, string methodName)
{
    IntPtr moduleHandle = GetModuleHandle(moduleName);
    if (moduleHandle == IntPtr.Zero)
    {
        return false;
    }
    return (GetProcAddress(moduleHandle, methodName) != IntPtr.Zero);
}

static bool Is64Bit()
{
    bool retVal;

    IsWow64Process(Process.GetCurrentProcess().Handle, out retVal);

    return retVal;
}

public static bool Is64BitOperatingSystem()
{
    if (IntPtr.Size == 8)  // 64-bit programs run only on Win64
    {
        return true;
    }
    else  // 32-bit programs run on both 32-bit and 64-bit Windows
    {
        // Detect whether the current process is a 32-bit process
        // running on a 64-bit system.
        bool flag;
        return ((DoesWin32MethodExist("kernel32.dll", "IsWow64Process") &&
               IsWow64Process(GetCurrentProcess(), out flag)) && flag);
    }
}

static void Main(string[] args)
{
    Console.WriteLine(DateTime.Now.ToLongDateString());

    bool f64bitOS = Is64BitOperatingSystem();
    Console.WriteLine("The current operating system {0} 64-bit.", f64bitOS ? "is" : "is not");

}

Saturday, February 8, 2014

Detecting System Time Change Event

When developing software that uses the system time, it can be necessary to react when a user makes a change to the time using the Control Panel. It is possible to detect such alterations using an standard event, which is defined in the SystemEvents class.

SystemEvents

The SystemEvents class is a standard type in the .NET framework, found within the Microsoft.Win32 namespace. It defines a number of events that are raised when the user performs operating system functions. These can be subscribed to in the same manner as any other event.

If you need to detect a change to the clock, you can subscribe to the TimeChanged event. If the user modifies the date or time, the event will be raised and you can react accordingly. There is an issue with the event; it may be raised twice for a single change in the time. If this would cause a problem in your scenario, or if the action you perform when the time changes uses lots of resources, you should attempt to detect and ignore repeated events.

To show the use of the event, create a new console application and add the following using directive to the automatically generated class:

using Microsoft.Win32;

static void Main(string[] args)
{
    SystemEvents.TimeChanged += SystemEvents_TimeChanged;
    Console.ReadLine();
}
static void SystemEvents_TimeChanged(object sender, EventArgs e)
{
    Console.WriteLine("Time changed");
}

Using Environment.FailFast

The FailFast method stops When an application or program becomes critically unstable, it is sometimes better to exit, rather than risk corruption. If even exiting normally could cause damage to data, it is appropriate to ignore any exception handling and stop the process immediately.


Environment.FailFast
The FailFast method stops your program immediately, ensuring that no further code can execute. As this means that you cannot report the problem directly to the user, this static method includes a parameter, to which you can provide a string containing a status message. This message is recorded in the application event log.

Tuesday, August 27, 2013

Hiding code from debugger in C#

Occasionally stepping through properties and methods gives no help to a developer who is trying to debug particular code. In these conditions it can be worthy to hide code from the debugger so that it is stepped over automatically.

[DebuggerStepThrough] Attribute
The .NET framework provides an attributes that you can apply to achieve stepping through the code, in some methods, properties and even entire classes, avoiding noisy and complicated debugging. Sometimes it is more convenient to hide a member or type from the debugger completely.


Example 

using System;
using System.Text;
using System.Collections.Generic;
using System.Diagnostics;

static void Main(string[] args)
{
    DoSomething();
}


[DebuggerStepThrough]
public static void DoSomething()
{
    Console.WriteLine("Can't stop here!"); // Breakpoint
    DoSomethingElse();
}


private static void DoSomethingElse()
{
    Console.WriteLine("Can stop here!"); // Breakpoint
}