Memory dumps of a developer

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

  • 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


  • RemoteValidation Attribute in ASP.NET MVC

    One great feature we have in ASP.NET MVC is ability to do client side validations using Data Annotations and it definitely save a lot of time from writing mundane client side scripts for validations such as required, number formats, email formats etc. When we decorate properties with validation attributes, the runtime will inject JavaScript automatically when the page is rendered to do that validation. But in some scenarios we will need to do the validation in the server side say in cases such as we need to verify an user exists or not when the data is entered in the text box. Most of us will invoke an ajax call on the blur event to achieve this, but in MVC there is validation attribute that can do this for you with minimal amount of code.

    Remote Validation Attribute

    Remote Validation is the process in which we perform the validation in the server side for a specific control without posting the entire form information to the server. In ASP.NET MVC, we will use the Remote attribute in the System.Web.MVC namespace to the decorate the property. Let's take an example wherein we need to validate an username exists or not when he type it in the form field.

    Step 1 : Decorate the property

    Decorate the property with the Remote attribute with first param being the action name that needs to be executed, second one is the controller name and third is the message that needs to be shown when validation fails.

    using System.ComponentModel.DataAnnotations;
    using System.Web.Mvc;

    public class User
    {
    [Required]
    [Display(Name = "Enter Username")]
    [Remote("CheckExistingUser", "User", ErrorMessage = "Username already exists!")]
    public string UserName { get; set; }
    }

    Step 2 : Create the Action Method and Validation Logic

    Now you need to create the action method in the controller which specified in the attribute. Here I have created a method for validating the username which will return a false if the text entered in the field is admin or administrator.

    public ActionResult CheckExistingUser(string UserName)
    {
         try
         {
              return Json(ValidateUser(UserName), JsonRequestBehavior.AllowGet);
         }
         catch (Exception ex)
         {
              return Json(false, JsonRequestBehavior.AllowGet);
         }
    }
    

    private bool ValidateUser(String UserName)
    {
    	if (UserName.ToLower().Equals("admin") || UserName.ToLower().Equals("administrator"))
            	return false;
            else
    		return true;
    }
    


  • Disable a Module in Orchard SDF Database

    Somedays ago I was dealing with an issue that caused my blog www.techrepository.in to go offline. I was playing around the SSL module in Orchard Dashboard and accidently saved it with some incorrect settings. It brought my entire site down and I was unable to login to the Dashboard too. One of the option I had was to download a backup, restore it in local and then upload it back to production which will subsequently override my incorrect setting. But I didn't want to go that way because it was time consuming and lot of work involved, so I decided to put it in the backburner for the time being and decided to consider it if nothing works out.

    I googled a lot and finally stumbled on an article which explained the steps needed to disable a module using the database Orchard uses. Normally when we configure Orchard for the first time, we have the option to choose either SQL Server or SQL Server CE as the database. In my case I chose SQL CE database and now I needed to find a tool which can be used to connect and run queries against it. I found this wonderful utility called LinqPad for this and I have already published a detailed post on how to use it with a SQL CE database. 

    First thing you needed to do is to stop the website in IIS and download the SDF file from your hosting space. For an Orchard CMS, the default location for the database will be Site Root -> App_Data -> Sites -> Default. The structure of these two tables are given below.

     

    To disable a module, you will need to delete the entries for the module from the two tables

    Settings_ShellFeatureRecord
    Settings_ShellFeatureStateRecord

    Once the entries are deleted, you can upload the SDF file back to your hosting space by replacing the existing one. Also you need to delete the cache.dat file in the App_Data folder before restarting the website in IIS. That's all you need to disable a module, now you will be able to access your site and can verify this by checking from your Orchard Dashboard.


  • Using LinqPad to Access Your Orchard SDF Database

    Recently I was trying to setup SSL for my site www.techrepository.in and was playing around with the SSL module in Orchard. I accidently entered incorrect settings in the module which brought down the site and really wanted to bring it back as soon as possible. I definitely didn't want to download the backup, restore it in local and try to correct it by using the CLI tool available in Orchard. When I googled for solutions to resolve this issue, found one site that explained the steps to disable the module by directly updating the datastore of a blog hosted using Orchard.

    I was using the SQL CE option as the backend for my blog, so I tried connecting to it using SQL Server Management Studio 2014 but only to found later that it's no longer supported. Again, I resorted to google and found this wonderful utility called LinqPad which support SQL CE databases. So in this post, I will be showing you how to connect the database and run queries against it.

    About LinqPad

    You may think that LinqPad can be used only for experimenting the Linq queries, but it's much more than that and according to the creators it's an ultimate scratchpad for C#, F# and VB. You can read more about the utility in their site and can be downloaded from here. The installer is around 14 MB only and installation won't take much of your time.

    The home screen of the utility is a minmalistic one, has two list boxes on the left for showing the connections and other for showing the saved queries. The big one on the right is the playground where you can write and run queries against your database. 


  • Visual Studio 2017 - Introducing the New Installation Experience

    As many of you have already are aware that Microsoft has released a Release Candidate version of the latest incarnation of Visual Studio during the Connect() event held at New York City in November. Visual Studio is one of the most widely used IDE in the world and the latest avatar comes with lot of new features and performance improvements under the hood. The most notable among these is the all new installation experience which considerably reduces the installation time as well as eradicates a lot of pain points that an user faced during the installation of the earlier versions of the software.

    Preparing Installation

    Visual Studio 2017 RC is free for all and can be downloaded from the Visual Studio site here and also read about the minimum system requirements is available at https://www.visualstudio.com/en-us/productinfo/vs2017-system-requirements-vs before you start the installation. You will get a nice little installer utility from the download link and when you run vs_enterprise.exe, it will show the new launch screen which will tell you to accept the license before proceeding to the installation.

    Selecting Components

    Visual Studio is used by a wide variety of users for developing different types of application and majority of them doesn't need to install every garbage that comes along with the installation package. So deciding what to choose for your need was confusing and particularly about the dependencies that need to selected for a hassle free experience.

    In Visual Studio 2017, the concept of Workloads are introduced to solve this problem and now there are separate workloads for .NET desktop development, web development, UWP development etc. So if you are a web developer and selecting the Web Development workload will ensure that Visual Studio will install all the necessary tooling and dependencies that are needed for developing web applications. 


  • Consolidate Model Validation Errors as a Single String in ASP.NET Web API

    As we all know that we can do validation in ASP.NET MVC by decorating the model with validation attributes and when the page is generated by the framework it will automatically generate the client side validation scripts. You can read more about it in the Microsoft Documentation here. Normally the output will be like in the figure given below.

    Let's see how we can use the same mechanism in ASP.NET WebAPI to do the validation. I have created a model class as shown below

    public class Employee
        {
            [Required]
            [MaxLength(50, ErrorMessage="First name should not exceed 50 characters")]
            public string FirstName { get; set; }
            [Required]
            [MaxLength(50, ErrorMessage="Last name should not exceed 50 characters")]
            public string LastName { get; set; }
            [Required]
            [MaxLength(200, ErrorMessage="Address should not exceed 200 characters")]
            public string Address { get; set; }
            [Required]
            [EmailAddress(ErrorMessage="Email is invalid")]
            [MaxLength(50, ErrorMessage="EmailAddress should not exceed 50 characters")]
            public string EmailAddress { get; set; }
        }
    

    And created a POST method as given below which basically validates the model and if any errors are found then returns an error as response.

    public HttpResponseMessage Post([FromBody] Employee emp)
            {
                if (!ModelState.IsValid)
                    return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ModelState);
                return Request.CreateResponse(HttpStatusCode.Created, emp);
            }
    

  • Compile a ASP.NET Core Web App on the fly using dotnet watch command

    One of the mostly used feature in Visual Studio while developing ASP.NET web applications is the ablity to make changes on the fly in the source code and able to see the changes in the browser without doing a compilation process manually. Actually Visual Studio tracks the changes made in the code and when you save the modifications, VS will automatically compile the changes in the background and restrats the session.

    In the .NET Core world, most of the development is happening with code editors such as Notepad, Visual Studio Code etc. These are vanilla text editors and lacks most of the features found in Visual Studio. So .NET Core team has created a command line tool called dotnet watch to achieve this ability for .NET Core. It's basically a file watcher which restarts the specified application whenever there is change is made in the source code. You can read more about it in the documentation hosted in GitHub.

    To add this functionlity in your code, you need to add the reference in the tools section in the project.json file as shown below.

    "tools": {
        "Microsoft.DotNet.Watcher.Tools": "1.0.0-preview2-final"  
      }

    After adding the entry in the tools, you needs to restore the package using the dotnet restore command to get all the required files for the watch tool.

    Syntax

    dotnet watch <dotnet arguments>

    The watch tool can be used to compile, run application or test and publish whenever there is a change in the source code. So the <dotnet arugments> can be compile, run, publish etc. For the run command the usage is as shown below

    Usage

    dotnet watch run

    Now, if you make any changes in server side code, the application will be automatically compiled and the reflected changes can be seen by just refreshing the browser.  In the following animation, if you look closely in the Terminal Window you can see that the application is stopped and compiled automatically when the source code is saved after making the changes.

    So using this tool, whenever we need to make change in the source code there is no need to stop the running instance and executing the dotnet run command again. Similary it can be used along with any other dotnet command as discussed in the post here in the documentation.


  • Deploying an Optimized Image of your ASP.NET Core MVC Web App in Docker

    In one of the posts I authored in the blog, I have shown you how to deploy an ASP.NET Core Web application in a Docker container, but the approach in the post has got a significant disadvantage. In that approach we always copied the entire contents of the directory which included all the static files, source code files etc, then restores all the packages inside the container and builds the application before it’s hosted in the container. This increases the boot up time of the container as well as the file size of the container.

    In this post, I will show you how to publish a web application into the container rather than copying all the files into container and then build the application inside that. I am going to create an .NET Core MVC web application using the dotnet new command, you can read more about that my post here.

    Step 1 : Create Project

    dotnet new –t web

    Step 2 : Restore Packages

    dotnet restore //restores all the packages referenced in the project.json files

    Step 3 : Publish Project

    dotnet publish –c Release –o publish

    Publishes the output of the project to the publish folder using the Release configuration. Before running the command make sure that node, bower and gulp is installed in your machine otherwise the publish command will fail

    If you look inside the publish folder you will find that it has copied all our static files and resources along with the dlls of our application and the dependencies used in it