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

First look into Visual Studio Community 2013

Standard

Yesterday Connect(); Event, Scott Guthrie and Soma Somasegar made a number of important announcements for the cloud-first, mobile-first developer. Visual Studio Community 2013 is a new free, fully-featured edition of Visual Studio that lets developers target any platform, from desktop and mobile to web and cloud.

Visual Studio Community 2013

Visual Studio Community 2013

Visual Studio Community 2013 also supports full Visual Studio extensibility, offering access to the ecosystem of over 5000 extensions. You can download it from here. You can also try Visual Studio Community 2013 in Azure VM image.

What is new in Visual Studio Community 2013

  • Professional-grade editing, code analysis, and debugging support – Your favourite Refactor and Debugging features are included.
  • Support for open-source workflows (Git).
  • Compilers for managed languages, C++ and more
  • Cross-platform mobile development including the web, Android, iOS, and Windows Phone with the free Visual Studio Tools for Apache Cordova extension.
  • Take advantage of cloud services with simplified Azure SDK integration, and incorporate modern app analytics and telemetry with Application Insights. Application Insights collects, processes and presents a wide variety of telemetry including performance, usage, availability, exception, crash, environment, log and developer-supplied data from all components of a modern application – including clients (devices and browser), servers, databases and services.
    Application Insights

    Application Insights

  • Access to all the Visual Studio 2013 extensions on the Visual Studio Gallery

Visual Studio Community 2013 includes Update 4, which is a cumulative update of all previous Visual Studio 2013 updates.

Happy Programming :)

How to load WF workflows dynamically

Standard

This is post is about loading and running Workflow foundation (WF) XAML files. It is a powerful technique which can be used to change Workflows on the fly, without re-compiling the application. All this functionalities can be achieved via single line of code.

WorkflowInvoker.Invoke(ActivityXamlServices.Load("Activity1.xaml"));

Happy Programming :)

Generate your database entities using T4 templates

Standard

Long back I wrote some post about code generation using T4 templates. This post is about generating database entities using T4 templates. This code is pretty straight forward, you are reading the app.config to get the connection string, connecting to db server using Sql Server SMO objects, enumerating tables and columns.

Here is the code, which will read the App.Config file and get the connection string. (I am using a connection string with name, Default).

string appConfig = this.Host.ResolvePath("App.config");
if(!File.Exists(appConfig))
{
	Error("App.config not exists");
}

ExeConfigurationFileMap configFile = new ExeConfigurationFileMap();
configFile.ExeConfigFilename = appConfig;
var configuration = ConfigurationManager.OpenMappedExeConfiguration(configFile, ConfigurationUserLevel.None);
var connectionString = configuration.ConnectionStrings.ConnectionStrings["Default"].ConnectionString;

Here is the code which will connects to the database, enumerate tables and columns and generates classes and properties.

SqlConnection sqlConnection = new SqlConnection(connectionString);
ServerConnection serverConnection = new ServerConnection(sqlConnection);
Server server = new Server(serverConnection);
var tables = server.Databases[server.ConnectionContext.DatabaseName].Tables;
#>
namespace <#= server.ConnectionContext.DatabaseName #>.Entities
{
<#
foreach(Table table in tables)
{
#>
public sealed partial class <#= CleanName(table.Name) #>
{
<#
foreach(Column column in table.Columns)
{
#>
	public <#= ToClrType(column.DataType, column.Nullable) #> <#= CleanName(column.Name) #> { get; set; }
<#
}
#>
}
<#
}
#>
}

And here is the two functions which will fix any issue with table name and column names. And returns C# type by using a SQL Server type.

private string FixTableName(string tableName)
{
	var result = tableName.Replace(" ","_");
	return System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(result);
}

private string ToClrType(DataType dataType, bool isNullable)
{
	string returnType = string.Empty;
	switch (dataType.SqlDataType)
    {
        case SqlDataType.BigInt:
            returnType = string.Format("{0}{1}","long", isNullable ? "?":"");
			break;
        case SqlDataType.Binary:
        case SqlDataType.Image:
        case SqlDataType.Timestamp:
        case SqlDataType.VarBinary:
            returnType = "byte[]";
			break;
        case SqlDataType.Bit:
			returnType = string.Format("{0}{1}","bool", isNullable ? "?":"");
			break;
        case SqlDataType.Char:
        case SqlDataType.NChar:
        case SqlDataType.NText:
        case SqlDataType.NVarChar:
        case SqlDataType.Text:
        case SqlDataType.VarChar:
        case SqlDataType.Xml:
            returnType = string.Format("{0}{1}","string", "");
			break;
        case SqlDataType.DateTime:
        case SqlDataType.SmallDateTime:
        case SqlDataType.Date:
        case SqlDataType.Time:
        case SqlDataType.DateTime2:
			returnType = string.Format("{0}{1}","System.DateTime", isNullable ? "?":"");
			break;
        case SqlDataType.Decimal:
        case SqlDataType.Money:
        case SqlDataType.SmallMoney:
			returnType = string.Format("{0}{1}","decimal", isNullable ? "?":"");
			break;
        case SqlDataType.Float:
			returnType = string.Format("{0}{1}","double", isNullable ? "?":"");
			break;
        case SqlDataType.Int:
			returnType = string.Format("{0}{1}","int", isNullable ? "?":"");
			break;
        case SqlDataType.Real:
			returnType = string.Format("{0}{1}","float", isNullable ? "?":"");
			break;
        case SqlDataType.UniqueIdentifier:
			returnType = string.Format("{0}{1}","Guid", isNullable ? "?":"");
			break;
        case SqlDataType.SmallInt:
            returnType = string.Format("{0}{1}","short", isNullable ? "?":"");
			break;
        case SqlDataType.TinyInt:
            returnType = string.Format("{0}{1}","byte", isNullable ? "?":"");
			break;
        case SqlDataType.Variant:
            returnType = string.Format("{0}{1}","object", "");
			break;
        case SqlDataType.DateTimeOffset:
            returnType = string.Format("{0}{1}","DateTimeOffset", isNullable ? "?":"");
			break;
		}

		return returnType;
}

Happy Coding :)

You can find the Gist here