Memory dumps of a developer

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

  • 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


  • Scaffolding an ASP.NET Core MVC application using dotnet command

    We all know that the dotnet new command will create a new console project containing a two files Program.cs and project.json out of the box for you

    dotnet new

    dotnet new console app

    Output

    dotnet new console app directory

    It was of great help in getting started with a console application in .NET Core, but this command was missing a more important feature – the ability to create a ASP.NET Core Web project from the command line. So, we developers relied on scaffolding tools such as yeoman to generate Web/MVC/Web API projects targeting .NET Core. So whenever the .NET team made changes to the framework and tools, we faced some incompatibilities. Either we needed to wait till the template is upgraded to support the new changes or needed to manually update the files after the project is created.

    This is now a thing of the past with the latest update to the .NET Core project implementing to facility to scaffold an MVC project targeting the Core  framework.

    Syntax

    dotnet new –t web

    Output

    dotnet new mvc project

    dotnet new mvc project directory

    The process of building and running the web project remains the same by using the following statements

    dotnet restore //restores the referenced packages
    dotnet run //compiles the project if it’s not and then hosts the application in the default port 5000

    dotnet restore mvc core app

    dotnet run web app

    web app in browser


  • Consuming Rest API methods in .NET Core MVC application

    Up until we need to rely on third party libraries for consuming a Web API in .NET Core applications. Even though Microsoft has got the Microsoft.AspNet.WebApi.Client library that can be used for consuming API methods, the support for .NET Core was not there until now. This library had a dependency on Microsoft.Net.Http library which was not supported in .NET Core. So with the release of the 5.2.3 version of Microsoft.AspNet.WebApi.Client they have fixed this issue and now it's available for you to use in .NET Core web applications too.

    Step 1 : Add reference in project.json

    You need to add following entries under dependencies section in the project.json file as given below.

    The Microsoft.AspNet.WebApi.Client is dependent on System.Net.Http and System.Runtime.Serialization.Xml libraries and that's why we need to add the above ones in the json file

    Step 2 : Use HttpClient to consume API

    We will use an object of the HttpClient class in the System.Net.Http namespace which was rebuilt for supporting .NET Core in latest version to invoke a connection to the service and for consuming the method. Then we will the base address and request headers using the BaseAddress and DefaultRequestHeaders methods respectively. To consume the web method, we will use the GetAysnc method which returns a resposne stream object containing the response from the Web API and by using the ReadAsAsync to read the result from the stream

    For other operations such as Post, Put and Delete we can use PostAsAsync, PutAsJsonAsync, DeleteAsync

    For more please refer here: http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client


  • Using Nginx as a Reverse Proxy for ASP.NET Core Web App in Docker

    One of the main features of .NET Core framework is the ability to run the applications on variety of environments such as Linux, MacOS etc. It includes a light weight server known as Kestrel which is used to run web apps targeting the .NET Core framework. But one of the main disadvantage of Kestrel is that it is primarily a development server and is not recommended for production environments. We always used IIS as server for hosting .NET Web app, but in the case of .NET Core since it's cross platform and we can't rely on IIS for platforms other than Windows. In the case of Linux, Nginx is one of the most popular web server out there and is very good at serving static content. But, for the example in this post we are going to make use of the reverse proxy(passing requests to other servers) feature in Nginx to serve our core web app from a docker container running on a Linux distro.

    I had already written a post about the on how to get started with Nginx and I recommend you to go through the post here if you are working with Nginx for the first time. In this post, I am going to host a .NET Core web app in a Docker container using Nginx and Kestrel to serve the site on a Linux machine.

    Before I get started with coding, here's a little advice for all you guys. It is always a recommended thing to follow a proper structure for your source files in your project. In this case, I have created two folders, one for putting all the files related to .NET and one for putting all those related to Nginx as shown in the screenshot below.

    Step 1 : Create .NET Core App

    Create a sample mvc core application under the dotnet folder. I created this one using the boiler plate template provided by yeoman which generated all the folders and files showed in the above image. If you run the application now using the dotnet run command, it will host the application in Kestrel and can be accessed by using the url http://localhost:5000. I have modified the sample page to show the name of the server using the below code.

    Served By : @System.Environment.MachineName 

    Since I'm running it from the local machine, the page will show the name of my local box as the server name as shown in the image below.

    Since we are going to host our application inside the Docker container, let's create a docker file which contains some instructions to Docker to set up the container. It basically tells which base image should be used, copies the files from the current folder to a folder called app inside the container and sets it's as the working directory. Then it executes two dotnet commands to restore the packages first and then executes the build. Once the build is completed it exposes the port #8018 for serving the app from the container. The ENTRYPOINT command is used execute the application when we start the container and in our case it will execute the run command to host the application.