Verify Internet connection is available using C#

Standard

While reviewing some code, I found a snippet for checking internet connection, like this

private static bool IsConnectedtoInternet()
{
	bool IsConnectedtoInternet;
	try
	{
		using (WebClient client = new WebClient())
		{
			using (client.OpenRead("http://www.microsoft.com"))
			{
				IsConnectedtoInternet = true;
			}
		}
	}
	catch
	{
		IsConnectedtoInternet = false;
	}
	return IsConnectedtoInternet;
}

I found this way of internet connection availablilty many times, but most of the times it was google.com :) So I thought of writing the correct way (at least from my prespective) of verifying internet connection. For this I am using a WIN32 API, InternetGetConnectedState method, from wininet.dll. And here is the snippet.

[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState
    (out int Description, int ReservedValue);
private static bool IsConnectedtoInternet()
{
    int description;
    return InternetGetConnectedState(out description, 0);
}

Happy Programming :)

Force .NET application to run in 32bit process

Standard

Due to lack of 64 bit version of few COM libararies, we faced a situation to run our AnyCPU application into 32 bit. You can do this either by setting the Platform target or by using the corflags command.

  1. Using Platform target feature. – This is the simple solution, you can change the Platform target settings from Project Properties > Build tab.

    Platform Target settings from Project Properties

    Platform Target settings from Project Properties

    This will cause the compiler to set the 32Bit flag in the CLR header of the corresponding assembly. Every time we run this application no matter on what type of OS it will execute as a 32bit process. But this solution although simple and straight forward was not a viable solution for us since – as mentioned above – we want to have one and only one version of our product. Thus all components of our package have to be compiled with Platform Target set to Any CPU.

    From VS 2011 onwards there is new compiler flag available “Prefer 32-bit”, which will help a .NET application compiled to x86 will fail to run on an ARM Windows system, but an “Any CPU 32-bit preferred” application will run successfully. Also, the “Prefer 32-bit” checkbox is only enabled for .NET 4.5+ executable projects.

  2. Using corflags command – Similar to the above solution, here as well we are setting the CLR header to 32 bit using a tool called corflags – You can find more details about this tool here. To set the 32Bit flag, open the Developer Command prompt, navigate to the directory where your assembly is and use this command.
    CorFlags.exe Sample.exe /32Bit+
    

    You can use this solution as part of the build, so that you can switch to x64 in future, developer don’t need to worry about any platforms.

Happy Programming :)

Why you shouldn’t believe in your favorite .net decompiler

Standard

Yesterday I posted about explicit interface implementation. I was curious about to know how CLR treats Explicit interface implementation. I looked into the generated IL code using IL DASM, and it was pretty similar to C# code I wrote. So I thought of reverse engineering the assembly. I verified the assembly with five .net decompilers. And only two provided the compilable code. Here is the .Net decompilers I used.

This the code I compiled.

static void Main(string[] args)
{
    ISample sample = new Sample();
    var result = sample.Add(10, 20);
    Console.WriteLine(result);  //Will return 30

    ISample2 sample2 = new Sample();
    var result2 = sample2.Add(10, 20);
    Console.WriteLine(result2);  //Will return 40
}

And here is the code from decompilers.

ILSpy

// ConsoleApplication6.Program
private static void Main(string[] args)
{
	ISample sample = new Sample();
	int value = sample.Add(10, 20);
	Console.WriteLine(value);
	ISample2 sample2 = new Sample();
	int value2 = sample2.Add(10, 20);
	Console.WriteLine(value2);
}

dotPeek

private static void Main(string[] args)
{
    Console.WriteLine(new Sample().Add(10, 20));
    Console.WriteLine(new Sample().Add(10, 20));
}

JustDecompile

private static void Main(string[] args)
{
    Console.WriteLine((new Sample()).Add(10, 20));
    Console.WriteLine((new Sample()).Add(10, 20));
}

.NET CodeReflect

private static void Main(string[] args)
{
    Console.WriteLine(new ConsoleApplication6.Sample().Add(10, 20));
    Console.WriteLine(new ConsoleApplication6.Sample().Add(10, 20));
}

.NET Reflector 8

private static void Main(string[] args)
{
    ISample sample = new Sample();
    Console.WriteLine(sample.Add(10, 20));
    ISample2 sample2 = new Sample();
    Console.WriteLine(sample2.Add(10, 20));
}

If you look into the decompiled code, only ILSpy and .NET Reflector gives compilable code. It doesn’t mean other decompilers are not good, but for this given scenario, all the other three decompilers failed reverse engineer C# code properly.

Happy Programming :)

Explicit Interface Implementation in C#

Standard

If a class implements two interfaces that contain a member with the same signature, then implementing that member on the class will cause both interfaces to use that member as their implementation.

class Sample : ISample, ISample2
{
    //Both ISample and ISample2 will call this method.
    public int Add(int a, int b)
    {
        return a + b;
    }
}

interface ISample
{
    int Add(int a, int b);
}

interface ISample2
{
    int Add(int a, int b);
}

If the two interface members do not perform the same function, however, this can lead to an incorrect implementation of one or both of the interfaces.

Explicit Interface Implementation

Explicit Interface Implementation

It is possible to implement an interface member explicitly – creating a class member that is only called through the interface, and is specific to that interface. This is accomplished by naming the class member with the name of the interface and a period.

class Sample : ISample, ISample2
{
    public int Add(int a, int b)
    {
        return a + b;
    }

    int ISample2.Add(int a, int b)
    {
        return a + b + 10;
    }
}

The class member ISample2.Add only available via ISample2 interface, not available through class instance.

var sample = new Sample();
var result = sample.Add(10, 20);
Console.WriteLine(result);  //Will return 30

ISample2 sample2 = new Sample();
var result2 = sample2.Add(10, 20);
Console.WriteLine(result2);  //Will return 40

Explicit implementation is also used to resolve cases where two interfaces each declare different members of the same name such as a property and a method.

Points of interest.

  • Solves the diamond problem – The “diamond problem” (sometimes referred to as the “deadly diamond of death”[6]) is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C. If there is a method in A that B and/or C has overridden, and D does not override it, then which version of the method does D inherit: that of B, or that of C?
  • Improves design – always promotes “Program to interface not implementation” design technique
  • Explicit Interface Implementations are not overridable and cannot be made virtual.
  • Avoid implementing interface members explicitly without having a strong reason to do so. – Understanding explicit implementation requires an advanced level of expertise. For example, many developers do not know that an explicitly implemented member is publicly callable even though its signature is private. Because of this, explicitly implemented members do not appear in the list of publicly visible members. Explicitly implementing a member can also cause unnecessary boxing of value types.
  • Cleaner code / Refactoring is safer – There will be a compiler error if the an interface method is removed in case of explicit interface implementation, however if you implement the method implicitly you can end up with unused ‘orphaned’ public methods.

Do we require Explicit Interface Implementation always? / Should we enforce it as best practice? – Not always, for me it is complicated and confusing. If you found a library from nuget and will check which all interfaces available in it or will you check available public methods in it? Again it is subjective, as MSDN recommends – Avoid implementing interface members explicitly without having a strong reason to do so. If you are developing a framework, I will not recommend explicit interface implementation.

Happy Coding :)