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 :)

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 :)

OpenXML and opening a file in Read only mode

Standard

In one of my project, I am using OpenXML SDK for opening Excel files. Recently I got an issue like SpreadsheetDocument.Open() method was throwing an IOException, if the Excel file is opened by MS Excel, even if I set the isEditable parameter false.

IO Exception - Open XML opening file in Read Only mode

IO Exception – Open XML opening file in Read Only mode

I fixed this problem by passing a stream instead of string (file path). And I used the File stream class to open the Excel file. Here is the code snippet.

using (var fileStream = new FileStream(fileName, FileMode.Open, 
    FileAccess.Read, FileShare.ReadWrite))
{
    using (var spreadSheetDocument = SpreadsheetDocument.Open(fileStream, false))
    {
        //Implementation
    }
}

Happy Coding :)

Read Excel as DataTable using OpenXML and C#

Standard

In the current project we were using OpenXML extensively for reading Excel files. Here is the code snippet, which will help you to read / convert Excel files to DataTable.

using System;
using System.Data;
using System.Linq;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;

public static DataTable ReadAsDataTable(string fileName)
{
    DataTable dataTable = new DataTable();
    using (SpreadsheetDocument spreadSheetDocument = SpreadsheetDocument.Open(fileName, false))
    {
        WorkbookPart workbookPart = spreadSheetDocument.WorkbookPart;
        IEnumerable<Sheet> sheets = spreadSheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>();
        string relationshipId = sheets.First().Id.Value;
        WorksheetPart worksheetPart = (WorksheetPart)spreadSheetDocument.WorkbookPart.GetPartById(relationshipId);
        Worksheet workSheet = worksheetPart.Worksheet;
        SheetData sheetData = workSheet.GetFirstChild<SheetData>();
        IEnumerable<Row> rows = sheetData.Descendants<Row>();

        foreach (Cell cell in rows.ElementAt(0))
        {
            dataTable.Columns.Add(GetCellValue(spreadSheetDocument, cell));
        }

        foreach (Row row in rows)
        {
            DataRow dataRow = dataTable.NewRow();
            for (int i = 0; i < row.Descendants<Cell>().Count(); i++)
            {
                dataRow[i] = GetCellValue(spreadSheetDocument, row.Descendants<Cell>().ElementAt(i));
            }

            dataTable.Rows.Add(dataRow);
        }

    }
    dataTable.Rows.RemoveAt(0);

    return dataTable;
}

private static string GetCellValue(SpreadsheetDocument document, Cell cell)
{
    SharedStringTablePart stringTablePart = document.WorkbookPart.SharedStringTablePart;
    string value = cell.CellValue.InnerXml;

    if (cell.DataType != null && cell.DataType.Value == CellValues.SharedString)
    {
        return stringTablePart.SharedStringTable.ChildElements[Int32.Parse(value)].InnerText;
    }
    else
    {
        return value;
    }
}

Happy Programming :)

Update : Previous code snippet had some problem, now I fixed it.