Introduction to Dapper.NET ORM in ASP.NET 5

Standard

Dapper.NET is an open source, high performance Micro-ORM supporting Sql Server, MySQL, Sqlite, SqlCE, Firebird etc, from Stack Overflow team. Drapper provides extension methods for IDbConnection, so you require an instance of IDbConnection to use Dapper. To use Dapper, you need to include Dapper in the project.json file. In this post I am using Repository pattern and injecting the repository to the controller via constructor injection.

Here is the project.json file, the EntityFramework.SqlServer reference is required to use IDbConnection interface.

{
  "dependencies": {
    "Microsoft.AspNet.Diagnostics": "1.0.0-beta2",
    "Microsoft.AspNet.Hosting": "1.0.0-beta2",
    "Microsoft.AspNet.Mvc": "6.0.0-beta2",
    "Microsoft.AspNet.Server.WebListener": "1.0.0-beta2",
    "EntityFramework.SqlServer": "7.0.0-beta2",
    "Microsoft.AspNet.StaticFiles": "1.0.0-beta2",
     "Dapper":"1.38.0-*"
  },
  "commands": {
    "web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5010",
  },
  "frameworks": {
    "aspnet50": {}
  }
}

Here is the constructor of the respository class. In this I am creating the instance of SqlConnection.

private IDbConnection _connection;
public EmployeeRepository()
{
	_connection = new SqlConnection("Server=.\\SQLEXPRESS; Database=DemoDb; Integrated Security=SSPI");
	_connection.Open();
}

Dapper extends the IDbConnection with Query method, which you can use to execute a query and map the result to a strongly typed object or list of objects.

public Employee Get(int? id)
{
	return _connection.Query<Employee>("SELECT * FROM Employees WHERE Id = @Id", new{ Id = id }).FirstOrDefault();
}

public IEnumerable<Employee> FindAll()
{
	return _connection.Query<Employee>("SELECT * FROM Employees");
}

You can use Execute method to execute DML queries as well to the Database.

public void Save(Employee employee)
{
	_connection.Execute("INSERT INTO Employees(Name,Designation,JoiningDate,Remarks) VALUES(@Name,@Designation,@JoiningDate,@Remarks)", employee);
}

public void Delete(Employee employee)
{
	_connection.Execute("DELETE FROM Employees WHERE Id=@Id", employee);
}

Dapper also supports Stored Procedures as well. You need to provide the command type parameter.

public void Update(Employee employee)
{
	_connection.Query("usp_UpdateEmployee", employee, commandType: CommandType.StoredProcedure);
}

You can use Dapper in ASP.NET or any .net applications, for that you need to include the Dapper nuget reference. You can find more details about Dapper from Dapper wiki

Happy Programming :)

k web command and agile development environment

Standard

With the new version of ASP.NET, you can avail the flexibility of deploying your app via an agile app development methodology, where you can modify and save the C# file and refresh the browser, your changes will be updated automatically. You don’t need to go for any explicit compilation in Visual Studio. The in-built .NET Compiler Platform ROSLYN available with ASP.NET vNext handles app deployment transparently in either the server or the development machine. This feature is only available with Visual Studio, it won’t work with “k” command. The k command comes with –watch switch, documentation says “Watch file changes”, but it is also not working. When there is a file change, it will stop the server. I found few Node plugins for this purpose. Today I thought of writing a C# implementation.

Here is the implementation, I have a FileSystem watcher, which will monitor the files inside the directory, will raise events on file changes, if there is a change, it will restart the server. For some files, like project.json, if there is change, it will restore the packages and restart the server.

Implementation – File System watcher – Listening on file system change events

static void Main(string[] args)
{
    var currentDirectory = AppDomain.CurrentDomain.BaseDirectory;
    var fileSystemWatcher = new FileSystemWatcher(currentDirectory);
    fileSystemWatcher.IncludeSubdirectories = true;
    fileSystemWatcher.NotifyFilter = NotifyFilters.LastAccess
        | NotifyFilters.LastWrite
        | NotifyFilters.FileName
        | NotifyFilters.DirectoryName;
    fileSystemWatcher.Changed += new FileSystemEventHandler(OnChanged);
    fileSystemWatcher.Created += new FileSystemEventHandler(OnChanged);
    fileSystemWatcher.Deleted += new FileSystemEventHandler(OnChanged);
    fileSystemWatcher.EnableRaisingEvents = true;

    Console.WriteLine("Starting server");
    StartProcess("k --watch web");
    Console.WriteLine("Press \'q\' to quit the web monitor.");
    while (Console.Read() != 'q') ;
}

Here is the implementation – Starting / Restarting server and restoring packages.

private static Process StartProcess(string arguments)
{
    var filename = "cmd.exe";
    var processStartInfo = new ProcessStartInfo(filename, " /C " + arguments);
    processStartInfo.RedirectStandardError = true;
    processStartInfo.RedirectStandardInput = true;
    processStartInfo.RedirectStandardOutput = true;
    processStartInfo.CreateNoWindow = true;
    processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    processStartInfo.UseShellExecute = false;
    var process = Process.Start(processStartInfo);

    process.EnableRaisingEvents = true;
    process.OutputDataReceived += (o, dre) =>
    {
        Console.WriteLine(dre.Data);
    };

    process.BeginOutputReadLine();
    return process;
}

And here is the core part – OnChanged, which will listen the file changes and based on the file type do the process.

private static void OnChanged(object source, FileSystemEventArgs e)
{
    DateTime lastWriteTime = File.GetLastWriteTime(e.FullPath);
    if (lastWriteTime != _lastRead)
    {
        var extension = Path.GetExtension(e.Name);
        if (extension.Equals(".json"))
        {
            Console.WriteLine("{0} file modified. Package restore starting", e.Name);
            var process = StartProcess("kpm restore");
            process.WaitForExit();
            if (process.ExitCode == 0)
            {
                Console.WriteLine("Package restore completed successfully. Restarting server.");
                process = StartProcess("k --watch web");
                process.WaitForExit();
            }
            else
            {
                Console.WriteLine("Package restore failed. Please make sure your {0} file is valid.", e.Name);
            }
        }
        else
        {
            Console.WriteLine("{0} file modified. Restarting server", e.Name);
            var process = StartProcess("k --watch web");
            process.WaitForExit();
            if (process.ExitCode != 0)
            {
                Console.WriteLine("Server restart failed. Please make sure you can compile {0} file.", e.Name);
            }
        }

        _lastRead = lastWriteTime;
    }
}

There is a problem with FileSystemWatcher Changed event, when ever there is change, FileSystem watcher will raise the OnChanged event twice. To overcome this issue, the _lastRead and lastWriteTime variables used. Here is the screenshot of kmonitor.exe running on my system.

kmonitor - running

kmonitor – running

Here is the gist for kmonitor

Happy Programming :)

TagHelpers in ASP.NET 5

Standard

TagHelpers is a new feature in ASP.NET, it is similar to HTML helpers, which already available in ASP.NET MVC. Similar to HTML helps TagHelpers allows to process server side content on HTML controls. So

<a asp-controller="Home" asp-action="Index">Home</a>

Will be rendered as

<a href="/Home/Index">Home</a>

It looks similar to ASP.NET controls but it doesn’t have life cycle events, view state or control state. TagHelpers available under Microsoft.AspNet.Mvc.TagHelpers namespace. You can find more details about the available Tag Helpers from ASP.NET MVC GitHub Page

To use TagHelpers in MVC Views, you need to add reference of “Microsoft.AspNet.Mvc.TagHelpers” to the project.json file. And add the TagHelpers namespace in the views, where you need to use the TagHelpers. If you want to include it in all the Views you can include this statement in _ViewStart.cshtml.

@addtaghelper "Microsoft.AspNet.Mvc.TagHelpers"

Similar to Server side controls and HTML Helpers, ASP.NET allows developers to create custom Tag Helpers. To create your own tag helper, you need to inherit from TagHelper class. And you need to override Process() or ProcessAsync() methods.

Happy Programming :)

Continuous Deployment (GitHub) with Azure Web Sites

Standard

Windows Azure websites supports Continuous Deployment. Continuous Deployment can be thought as an extension of continuous integration, where when ever users commit a changeset, build will be triggered. And in case of Continuous Deployment, the changes will be published to your live application directly from source control, when ever user commits a changeset. This is a fantastic automation feature that can be leveraged from a range of source control tools such as Visual Studio Online and others (GitHub, BitBucket, DropBox, CodePlex, or Mercurial) . Azure websites supports staged publishing (it is in Preview state) as well, so if you don’t want to publish your changes direcly to live, you can deploy it to staging and verify it. Once verification is completed, you can push the staging to live.

In this post I will be describing the deploying to direct live environment approach only. I am using GitHub as my source control. First you need to create Website. You can do it from Azure portal or from Visual Studio. Once you created website, go to the Dashboard and select the option “Set up deployment from source control”

Set up deployment from source control

Set up deployment from source control

Now select GitHub from the list.

GitHub from Source code repository list

GitHub from Source code repository list

Azure will popup GitHub authentication and authorization window, once you authorize, you need to select the source code repository.

Select GitHub repository

Select GitHub repository

Once you choose source code repository, if the repository contains source, it will be pushed to the live environment. To verify continues deployment, you can modify the source and publish the changes.

In this post I have enabled Continuous Deployment for a HTML5 single page application. Now I am integrating VisualStudio online Application Insights code to the HTML page.

Integrating application insight code to HTML Page

Integrating application insight code to HTML Page

Now commit the changes (I have added a description – “Application insights code added Application insights code added”) and publish the source code. You can verify the Deployments Tab in Azure portal and can see the changeset applied.

Deployments Tab in Azure portal

Deployments Tab in Azure portal

You can see the comment in the active deployment – “Application insights code added Application insights code added”

I will post about staging deployment later.

Happy Programming :)