Memory dumps of a developer

Articles and tutorials on .NET Core, ASP.NET MVC, Kendo UI, Windows 10, Windows Mobile, Orchard

  • Bug : dotnet CLI Template Engine Produces Invalid Code if Name of the Directory is a Valid C# Keyword

    With the release of .NET Core 1.0 tooling, dotnet new make use of the templating engine to generate various types of projects like Console App, Web App, WebAPI etc. If you are not aware of it, please read my earlier post on it here.


  • Stream Video Using Azure Media Services

    Recently I faced some dilemma in setting up video streaming for a site which I was working on. Since most of the targeted audience was from the enterprises, I wanted to avoid YouTube and other popular streaming services because of the greater possibility of it getting blocked by the corporate firewalls. So after some research, I found that the offering from Microsoft Azure very interesting and decided to explore it further. So in this post, I will be going through the various steps for setting up video streaming using Azure Media Services.

    From the documentation, Azure Media Service is

    An extensible cloud-based platform that enables developers to build scalable media management and delivery applications. Media Services is based on REST APIs that enable you to securely upload, store, encode and package video or audio content for both on-demand and live streaming delivery to various clients (for example, TV, PC, and mobile devices).

    Setting Up Media Services

    To get started, search for Media Services by typing it in the search box and then click on the first one under Web + Mobile category

    When you click on the Create button, you will be prompted to give a Name, choose a subscription, resource group, location and a storage account. Make sure that you choose the same region for your location and storage account, otherwise you may face problems down the line.

    We are now all set for creating a media service, just click on the Create button to start the deployment and you will see a new entry under Media Services after the deployment as shown below.


  • Executing a Task in the Background in ASP.NET MVC

    In some cases we want to execute some long running task in the background without affecting the main thread. One classic example is sending mails when we are implementing a sign in module. Mostly people will either go for a scheduled job independent of the application or do it in the main thread itself. 

    .NET Framework 4.5.2 has got a new API called QueueBackgroundWorkItem which can execute short-lived resource intense tasks in an effective and reliable manner. As per the documentation

    QBWI schedules a task which can run in the background, independent of any request. This differs from a normal ThreadPool work item in that ASP.NET automatically keeps track of how many work items registered through this API are currently running, and the ASP.NET runtime will try to delay AppDomain shutdown until these work items have finished executing.

    One of the advantages of using the QBWI(QueueBackgroundWorkItem) is that it can keep track of the items that are registered through this API is currently running and the runtime will be able to delay the shutdown of the App Domain upto 90 seconds so that the running tasks can be completed. 

    Let's see an example of file upload in ASP.NET MVC. In this example, I will chose file from the local machine using the file upload control and when you click the Upload button, the file will be saved inside a folder in the server which will be handled by the QBWI. 

    View 

    @{
        ViewBag.Title = "Index";
    }
    @model List<string>
    
    <h2>Index</h2>
    @using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new { id = "frmImageGallery", enctype = "multipart/form-data" }))
     { 
       <input type="file" name="file" />
       <input type="submit" value="Upload"  id="btnUpload" />
     }
    
    <h2>Images</h2>
    @foreach (var item in Model)
    { 
        <p><img src="@String.Concat("Images/Uploaded/",item)" style="height:200px" /></p><br />
    }
    <script>
        $(function () {
            $(document).on("click", "#btnUpload", function (event) {
                event.preventDefault();
                var fileOptions = {
                    success: res,
                    dataType: "json"
                }
                $("#frmImageGallery").ajaxSubmit(fileOptions);
            });
    
        }); 
    </script>
    
    

  • Add/Remove References Using dotnet CLI Tool

    In the latest update made to the .NET Core tooling, dotnet new and add command has undergone significant changes in the usage and options available for the command. You can read more about the updates here in the official blog. In this current update it replaces the dotnet add p2p command with a new syntax.

    Adding a Reference

    Syntax

    dotnet add reference <path to project file>

    Usage 

    dotnet add reference ..\Lib\Lib.csproj

    When you execute the following command it will get added to the project and if look at the csproj file of the project to which the reference is added you will see the entry for it

    Remove a Reference

    Syntax

    dotnet remove reference <path to the proj file which needs to be removed>

    Usage

    dotnet remove reference ..\Lib\Lib.csproj

    To remove the referernce we will use the dotnet remove reference as shown below.


  • Add/Remove Packages Using dotnet CLI Tool

    With the release of .NET Core RC3, the tooling has undergone signinficant improvements in fixing bugs and stablilty. With this release the team has added the ability to add/remove NuGet packages to your project using the dotnet command. The .NET Core CLI tools were introduced to make it easier for developers who uses command line to create and manage projects and with this addition they will become more productive.

    Let's create a sample console application project and see how we can add/remove NuGet packages to and from the project. To create the project execute the following command.

    dotnet new console

    When the command is executed, two files will be created. One is the source file and other one is the project file

    Program.cs

    namespace AddPackagageSample
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine("Hello World!");
            }
        }
    }
    

    csproj file

    <Project Sdk="Microsoft.NET.Sdk">
    
      <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>netcoreapp1.0</TargetFramework>
      </PropertyGroup>
    
    </Project>
    

     To see this project in action, let's restore the packages and build it as shown below

    Let's modify the Program.cs file to do some Json Serialiazation as shown below


  • Templates Available for dotnet new command

    Early this week Microsoft announced the release of updates to .NET Core Tooling included in the Visual Studio 2017 RC which brings some major changes in the toolset. You can refer this link to read about the official release of the update. One of the major change is in creating new projects using the dotnet new command which is widely used by novice and experienced hands in their day to day life as a developer. According to the release note, the updated dotnet command will be having the following characteristics.

    • Powerful — expressive and scriptable command-line syntax.
    • Helpful — an interactive mode helps users pick the templates they need (think Yeoman).
    • Extensible — anyone can write templates for dotnet new!
    • Updatable — templates can be updated outside of primary delivery vehicles (e.g. Visual Studio, .NET Core SDK).
    • Platform — can be used by tools like Visual Studio and generator-aspnet (think yo aspnet).

    The major change in dotnet new is that it is based on a templating engine which will create the artifacts automatically depending upon the projects you chose to create. To view the options available in the command, just execute the following command in the prompt.

    dotnet new --help


  • Host ASP.NET MVC Application in a Windows Container in Docker

    In an earlier post which I published a week go, went through the steps needed for setting up an IIS server in a Docker container running on a Windows Server 2016 machine. In this post, I will explain the steps needed to host an ASP.NET MVC application on a IIS server running inside a docker container based on Windows

    Step 1 : Setup IIS with ASP.NET Support

    First, we will create a new image based on the official IIS image released by Microsoft. Because in that image features such as ASP.NET 4.5 and Microsoft Web Deploy are not installed by default and we need to have it for deloying our application. So download the installer package for Web Deploy from the Microsoft site and store it in a folder in your local machine. To create the image I have created a Dockerfile as given below

    FROM microsoft/iis
    
    RUN dism /online /enable-feature /all /featurename:IIS-ASPNET45 
    RUN mkdir c:\install
    ADD WebDeploy_amd64_en-US.msi /install/WebDeploy_amd64_en-US.msi
    WORKDIR /install RUN powershell start-Process msiexec.exe -ArgumentList '/i c:\install\WebDeploy_amd64_en-US.msi /qn' -Wait

    Let's create the image by executing the following command

    docker build -t amaldevv/aspnetwithwebdeploy .

    When the command is executed, it will first check whether image for IIS is available in locally in docker and if it's not found then will download it from Microsoft repository in Docker Hub. The second statement in the file is for installing the ASP.NET 4.5 feature and once that is finished it will create a folder named install in the container and then copies the installer package for Web Deploy which we downloaded earlier into it. After that msiexec process is called using Powershell to install  Web Deploy inside the container

    You can verify the images is successfully built or not by executing the docker images command as shown below


  • Running IIS from a Docker Container in Windows Server 2016

    Many of you may already aware that Windows Server 2016 now natively supports Docker containers and it means that the same shared-kernel-isolation-paradigm from the Linux world is now well and truly supported in Windows too. The advantage of this approach is that your containers will load more speedily with minimum amount of resources. Please go through this link to read more about it. In this post, I will show how to host IIS in a docker container in Windows Server 2016 machine.

    Step 1 : Get the base image for IIS

    First you need to pull the latest image for IIS from the Docker hub by executing the following statement.

    docker pull microsoft/iis

    It will pull the image with the tag latest from the docker repository. If you want specify a different tag, then you need to specify that after the image  name with a color(:) prepended to it

    If you execute the docker images, our newly downloaded image will be shown in the list as shown below.

    Step 2 : Create the Container

    Now, you need to create a container based on the image which we downloaded in the earlier step. For that you will to need to execute the following command

    docker run -it -d -p 80:80 microsoft/iis

    With this command, we are telling Docker to create a container based on microsoft/iis image. The -d switch indicates that container should be run in the background and -p switch is used for mapping the port numbers for host and the container. In this example we are redirecting the requests coming into the port #80 in the host machine to port #80 in the container we just created. When it's successfully executed, it will emit the full container id and then returns to the prompt as shown below

    You can verify whether the container is running or not by executing the docker ps command. The ps command will show all the active processes running in docker as shown below

    Step 3 : Check IIS status

    You verify whether the IIS running inside the container is properly serving content or not by typing in the IP address of the host machine in the browser. If everything is good you will see the default web site page of the IIS as shown below.

    Since port # 80 is used for http by default and we don't need to provide that along with the IP address. The redirection magic is done by the daemon whom will see a request at port 80 is coming in the host machine, intercepts it and redirects it to the port#80 of our container which then spits out the default website page.

     


  • Override Default port and Host Name Used By ASP.NET Core Toolset

    .NET Core is the brand new modular framework from Microsoft for creating a wide variety of applications targeting Windows, Web, Cloud, IoT devices etc. Along with that they have introduced a cross platform toolchain for the command line which will help you to create and execute .NET core apps from the command line. 

    So for creating a normal web app in the .NET Core we will execute the following command.

    > dotnet run -t Web

    Then you will restore the packages by executing the command given below

    > dotnet restore

    After that you will execute the run command to build and host the application locally

    > dotnet run

    When this command is executed, it will first compile the application and upon successful build it will then host it using the built-in web server named Kestrel. Kestrel will use the port number 5000 by default for listening the requests for your app.

    From the screenshot you can see that the app is using port #5000 and is binded to localhost. This will be perfectly ok in a Dev enviroment since the developer will creating the application and is hosting it in the same machine. But this won't work in a production environment, where the requests to our app will be coming to the server from different machines out in the wild. That means, if you try to access the site using the ip address of the machine instead of localhost you will get a 404 error.


  • elmah.io - Logging Exceptions to the Cloud

    Elmah stands for Error Logging Modules and Handlers is a great open source application logging utility for ASP.NET which is available for some time now. Some of the features provided by Elmah are given below.

    • Logging Unhandled exceptions
    • Provides a web page to view the logged exceptions
    • Also provides a web page to view all the details of a logged exception
    • Option to send an email notification when an error occurs
    • RSS feed for the last 15 errors from the log
    • Options for backing store for the log includes in-memory, SQL Server, flat file, Oracle, SQL Lite etc

    Normally when we log exceptions we will keep the info in a flat file or in the database, but Elmah got another option which is to directly store all the logs in the cloud via elmah.io without much change to your existing framework.

    Set Up  elmah.io

    First you need to create an account in elmah.io, it's pretty simple and even you can use any of social logins provided by Twitter, Facebook, Outlook or Google. Once you create the login, just create a log for your application from the dashboard. Just give a name for the log and click save. We will leave the other options for the time being. Also whenever a log is created, Elmah will create a unique id for the log, keep a note of it as we need it later when we configure it in our project.

    Setup your project to use elmah.io

    Now, in our project we need to add a Elmah logger by installing the following command in the Nuget Package Manager Console.

    Install-Package elmah.io