C#

  • Json.NET - Reducing the Payload of Data Transferred

    While developing web apps, it's the duty of we, developers to make sure that we are sending only the required data back and forth. Otherwise it can cause a performance hit for for your application. Let's assume that you hava class that contains a lot of properties and in a page you are using a couple for properties in that instance for showing the data in the page. In this case if we send the whole instance to client, we are actually sending lot of unwanted data to the client consuming bandwidth and also making the page slower.

    Json.net has got lot of options baked into the framework to get through these kind of situations. Json.Net will serialize all the properties and fields from the class to create the json. You can restrict that in two ways

    1. JsonIgnore Attribute

    If you want Json.net to ignore some properties while writing to JSON, you can decorate that property with JsonIgnore attribute as shown below.


  • Json.NET - Handling Default Values

    In the earlier post we have seen that we can use the NullValueHandling property to handle null values during serialization and omit it from the resulting json string.

    There is another feature called Default Value Handling, where we can specify a default value for the attribute and instruct Json.Net to use that value during conversion operation when the underlying property is empty.

    The NullValueHandling  property is available in the JsonSerializationSettings class and it accepts 4 values.

    1. DefaultValueHandling.Ignore

    When we set this property, during serialization, if the property names matches the default values of the data type, like Min Value for Date, Null for nullable fields, then those field will be omitted from the resulting string

    In the above example, I have specified null value for ColorCode and min value for effective date. So both of them are omitted from the json output string.

    If we haven't set it to ignore, then we will the output as shown below.

    {"ColorId":1,"ColorName":"Red","EffectiveDate":"0001-01-01T00:00:00","ColorCode":null}

  • Json.NET - Customizing Serialization Settings

    We can control the serialization/deserialization process using JsonSerializer class. Let's explore some of them

    Ignore Null Values

    In Json.Net we have the option to ignore values. Somtime during conversions, properties can be null and while doing the serilization, Json.Net will include that also in the result string.

    In the program we are not passing any data to ColorCode attribute and after serialization it's coming as null in produced string.

    So handle this one, I have created a new instance for JsonSerializer and set the NullValueHandling property to NullValueHandling.Ignore. When it's set to ignore, it will omit the property from writing to the string if the value is null. The value of the NullValueHandling attribute is set to NullValueHandling.Include by default and that's why it exists in the string in the earlier example.

    Missing Member Validation

    During deserialization we can prevent the process from completing if there are any missing members in the json input string. For example in the below example, there is no entry for the ColorName property in the string. But in the class it's decorated with Mandatory attribute. So if you want Json.NET to raise the exception during such scenario, you need to set the MissingMemberHandling property to MissingMemberHandling.Error so that the conversion won't go through successfully.

    By default the value MissingMemberHandling is set to MissingMemberHandling.Ignore, so that no exception are thrown even if members are missing


  • Json.NET - Serializing and Deserializing Data

    In this post, I am going to explain the process of converting json data to a .NET object and vice versa using Json.NET. 

    We will be using the SerializeObject and DeserializeObject methods in JsonConvert class for doing this. These methods encapsulates all the heavy listing done by JsonSerializer class which is actually doing the conversion under the hood.

    In the example given below, I am trying to convert a .NET object into json sting using the SerializeObject method. I have created a class which contains two string properties for Id and Name, created an instance of it and intialized the values.

    Serializing Data

    To use Json.NET , first you need to install the package via NuGet. I have already wrote a post on that subject earlier and you can refer it here. Then you need to import the namespace Newtonsoft.Json into the program.

    After that you can call the SerializeObject in JsonConvert class to do the conversion and the resulting json string is store in jsonOutput.

    Syntax

    JsonConvert.SerializeObject(T inputclass);

    Usage 

    String jsonOutput = JsonConvert.SerializeObject(clsInfo);

    When we call the SerializeObject method, Json.Net will take the properties name from the class definition to create the keys with the same name is the resulting json. The values for these keys are taken from the values in properties of the instance and that's the json string is formed.

    If you look at the class definition closely, you can see that I have specified string as type for both the properties and when the json string is formed, the value is enclosed in the double quotes. Let's change the type of the ColorId property to int and will see how will our json string look like

    If you look at the output now, the ColorId property is now not enclosed in double quotes. Json.net will always consider the type of property and based on that only it's building the json string.

    Deserializing Data

    For deserialization, we will make use of the DeserializeObject  method in JsonConvert class. It expects the json string that need to be converted as well the type to which it needs to be converted. Here also I'm making use of the class with two string properties and the magic happens here in this statement.

    Usage

    ColorInfo clsInfo = JsonConvert.DeserializeObject<ColorInfo>(jsonOutput);

    Syntax

    JsonConvert.DeserializeObject<T>(string inputString);

    As we done in the case of serialization, let's change the property of the ColorId property to int and see how deserialization goes

    You will be surprised that there are no error and conversion happened successfully. That's because Json.net will handle that conversion internally there by producing the desired output.


  • What's Json.NET

    What is JSON ?

    JSON(Javascript Object Notation) is a lightweight data format and is one of the widely used data format to transfer data between a server and a client. In JSON the data is transferred in text format and normaly in the form of Key Value Pairs. 

    Sample JSON

    {
      "FirstName": "Amal",
      "LastName": "Dev
    }
    

    So we developers most often stumble across scenarios where we need to map this attributes in JSON to domain entity.  Mapping each attribute in the JSON to the properties of a class is tedious as well as a repetitive job. That's where frameworks such as Json.NET comes in handy, it helps you map the items using one single statment.

    Json.NET

    Json.NET  is the most popular of them all and is widely used acros the world. Such is its performance and popularity that it became the defacto way of passing data in ASP.NET Web API. It started as a hobby project having very limited features and by 2006 it evolved into a great product with lot of features culminating with the release of the first version.

    Another great advantage of using Json.NET is that it's a open sourced project and is free for commercial use too.

    Features

    Has a great serializer for converting .NET objects to JSON

    High Performance

    Creates indented JSON

    Conversion from XML to JSON and vice versa

    Supports frameworks from .Net 2.0 to 4.5, Silverlight, UWP

    It's a free library and you can add to your project by either manually executing the command from the Package Manager Console window or by using the Package Manager in Visual Studio

    Using Package Manager Console

    Install-Package Newtonsoft.Json


  • Creating ASP.NET Core Web App Using VS Code

    VS Code is a brand new cross-platform open source editor from Microsoft which supports a variety of languages. You can read more about it in following posts I have blogged earlier

    Installing Visual Studio Code in Windows 10

    What is Visual Studio Code

    In this post, I am going to show you to create ASP.NET app targeting ASP.NET Core framework. ASP.NET Core which was earlier known as ASP.NET 5 is built from the scratch, is very lightweight, more modular and cross platform. 

    Before we get started with this, there are some pre-requisites which needs to be setup properly for our sample to work.

    1. VS Code Editor
    2. Node.js 
    3. Gulp
    4. Git for Windows

    You can refer the following links for installing Node, Gulp and Git

    Installing node.js in Windows 10

    Getting Started with Gulp

    Installing Git Client in Windows 10.


  • Creating Your First Application With Node.js

    In the earlier post, I showed you how to install Node.js in your local machine and how to verify whether it's running correctly or not. If you missed that one, you refer it here.

    A Node.js program contains mainly 3 blocks.

    1. Import Required Modules
    2. Create Server
    3. Intercept Request and Return Response

    Let's create a program and will explain the blocks in detail with examples.

    Basically our program will intercept the request and will send the IP address from where the request originated as the response back to the client. For that first we need to import the http module which can be done using the require attribute as follows

    var httpMod = require("http");

    Here the httpMod variable will store the http instance returned by the require module. This is the first block in the Node.js program where you import all your modules using the required directive.

    In the next block, we will create the server which will listen in the specified port for incoming request from the client and returns the response.

    httpMod.createServer(function(request,response)
        {
            response.writeHead(200, {'Content-Type': 'text/plain'});
            
            
            
            response.end("Requested From ->" + request.connection.remoteAddress);
        }
    ).listen(9095);
    

  • Installing node.js in Windows 10

    Node.js is an open-source, cross-platfrom runtime built using V8 engine, the same one powers Chrome's javascript engine. It helps you to create robust and scalable server-side and networking applications. Applications targeting node.js or node are created using Javascript and can be run within the runtime on Windows, Mac or Linux.

    According to the official documentation

    Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.

    Let's see how can we install node.js on your machine. First you to download the desired package from the node site. Since I am using Windows 10, am going to download the Windows flavor and will proceed with version 5.10.1 from stable line branch

     

    The installer size is around 10 MB and won't much time to download. Once it's finished downloading, go to the downloads folder and double click on the installer to start the installation.


  • Installing Visual Studio Code in Windows 10

    Visual Studio Code or VS Code is modern light weight editor from Microsoft for developing apps in a variety of languages. It's cross platform and can be run on Windows, Linux and Mac natively. Also it's free for all to use and the source is hosted publicly at GitHub.

    You can download the installer from code.visualstudio.com which is around 29 MB in size and will take around 115 MB in your disk when the installation is completed

    The full system requirements are here. Please make sure that you go through it before doing the installation on your machine.

    Let's begin the install by double clicking on installer

    Specify the location where VS Code needs to be installed. Will default the path in the drive where Windows is installed. If you want you change it to another location by typing in the box or using the browse button select the folder you want

    In this page , we will specify the caption for the text needs to be displayed in the Start menu. If you don't it to show up in the menu, tick the checkbox in the bottom


  • What is Visual Studio Code

    Visual Studio Code is new light weight free editor from Microsoft initially launched as a beta version around a year ago. Since then it has come by leaps and bounds and evolved into a truly cross-platform editor with loads of features.

    Since it's introduction more than 2 millions developers have installed the code and these days there are around 500,000 active users for the application. And in April 2016, Code came out of beta and version 1.0 was released worldwide. It's available for download from code.visualstudio.com and supports upto 9 langugages. As I mentioned earlier Visual Studio is cross-platform tool and native versions are available for Linux and Mac

    Visual Studio Code was initially targeted developers who were working on TypeScipt and Javascript. But when the product was made extensible and delivered to the community, they quickly created a lot of extentions that supports most of the languages and runtimes.VS Code is fully accesible, with full keyboard navigation, screen reading and accesible navigation for visually impared developers.


  • Difference between DNVM Install and Upgrade Commands

    In the last post I have explained the use of install and upgrade commands for managing the runtimes in DNVM. If you have missed that post or wants to recap it, refer it here

    The install and upgrade commands are mainly used for installing the runtimes, but there are some difference between those and let's examine what are those in this post.

    Let's first list all the environments in the machine using the command dnvm list and will try to install a new runtime.

    Install Command

    From the list we can see that we are missing the Release Candidate Update 2 based on 64-bit version for the clr framework. So let's install it using the following command.

    dnvm install -arch x64 -r   clr 1.0.0-rc1-update2

    When you run the command, it will download the packgage from the feed and installs it to the runtimes folder in your user profiles. Then it will add the path to the process path variable and also makes it as the active one which is indicated by the * sign in the below screenshot. 

    But the one disadavantage is that the selected runtime is active only for the duration of the current session in the command prompt. Meaning it will revert to none or an earlier one if I close the window and open it again.

    If you compare the screenshots for the output of dnvm list commands, you can see that before installing it, the active version was 1.0.0-rc1-update 2 targeting coreclr based on x86. But after installing it's now 1.0.0.-rc1-update2 targeting clr based on x64. But if I close and reopen the terminal window, the active one will be the former one

    Upgrade Command

    The upgrade command also installs the runtime, but the difference is that it downloads and installs the runtime version which is the latest one.

    dnvm upgrade -arch x64 -r  clr 

    It will download and install the latest 64-bit version of clr framework.

    The difference is that it will add to the user path as well as process variables as active version, so that the selection will be persisted and won't revert back when we close and open the command window. It will also add an alias for the runtime.

     


  • Manage Runtimes Using DNVM Install and Upgrade Commands

    DNVM Install and Upgrade commands can be used to install a new version of the runtime or to upgrade an existing version to a newer version of the runtime.

    Install command can be used to download a particular version of the runtime.

    Syntax

    dnvm install –arch <architecture name=""> –r<runtime name="">

    Example

    dnvm install –arch x64 –r coreclr 1.0.0-rc1-update2

    The above command will install the version 1.0.0-rc1-update2 targeting the Core CLR runtime for 64-bit. It installs into runtimes folder located in the user profiles folder and modifies the path variable too.


  • DNX - Using Commands option

    In DNX environment we are using dnx run command to run the program from the command line. I have already authored a post on this and you refer that from here

    In this post I am going to cover the custom command option avaliable in .NET core using which we can do named execution of our program. We can define commands in the project.json file in your project folder and is recognized by editors like Visual Studio and Visual Studio Code. The commands defined in the project folder is available in that project only. If you want you can have commands defined at a global level, then it is available for everthing that runs under a user profile. 

    Sample program 

    using System;
    using static System.Console;
    using System.Collections.Generic;
    namespace DnxCoreSample.Commands
    {
        public class Program
        {
            public void Main(string[] args)
            {
                var items = new List<string>() { "Red", "Blue", "White", "Green" };
                foreach (var item in items)
                {
                    WriteLine($"Color : {item}");
                }
            }
    
            
        }
    }
    

    Let's see how can we configure that in project.json file

    {
      "frameworks": {
        "dnx451": { },
        "dnxcore50": {
          "dependencies": {
            "System.Console": "4.0.0-beta-23516",
            "System.Collections": "4.0.11-beta-23516"
          }
        }
      },
      "commands": {
        "RunSample" : "dnxcommands"
    
      }
    }
    

  • The dnx run Command

    As we have seen in the earlier post, we can use the dnx run command to compile and immediately execute the program. To recap, when you execute the below command in the command prompt, it will execute the program which has an entry point defined in the current folder. 

    dnx run

    I have created a sample program  which outputs a message to the console.

    using System;
    using static System.Console;
    namespace DnxCoreSample.Commands
    {
     public class Program
        {
            public  void Main(string[] args)
            {
                WriteLine("Getting started with dnx commands");
    			
            }
        }
    }	
    

    So if we try to execute the dnx run command, will get an error as shown below.

    That's because we haven't created the configuration file yet, which is used by the DNX environment for managing the dependencies and other project settings. So let's create one with the needed dependencies and run the dnu restore command to download the packages. 

    So after downloading, run the program using dnx run in the command prompt and will get the result as shown below.


  • Hello From DNX

    In the earlier post, I have gone through in detail about setting up dnx environment in your machine without installing Visual Studio. Also I have gone though some of the commands which will help you to the bare necessities in DNVM(.NET Version Manager). If you haven't seen that post yet, please read it from here.

    So we have set up the dnx environment in our system, now let's see how can we compile and run programs using this.

    Let's create a sample C# program using any text editors like Notepad or Sublime or Visual Studio Code. 

    using System;
    namespace DnxCoreSample
    {
     public class Program
        {
            public static void Main(string[] args)
            {
    		Console.WriteLine("Hello World from DNX!");
            }
        }
    }	

    Our program when executed will print a message on to the console. So before compiling an running the code we need to do one more thing. That's setting up the configurations needed for DNX will use to compile and run this program. In .NET Core we have the project.json file where all the project related settings. So create a file named project.json file in your folder and add the following entries

    {
      "frameworks": {
        "dnx451": { },
        "dnxcore50": {
          "dependencies": {
            "System.Console": "4.0.0-beta-23516"
    
          }
        }
      },
    
      "commands": {
        "HelloDnx": "dnxcoresamples"
      }
    }
    

  • ASP.MVC 6 - Using dnu restore command

    Recently I was playing around with the new MVC 6 web application templates to create some sample websites for learning the new features in the latest version. And suddenly out of the blue got the following error while try to start a debugging session and won't allow you the run the application without resolving this issue.

    So I had no clue at first about, so I googled about the error and learned how this error came about and the ways to fix it too.

    Visual Studio has got a project.json file as well as project.lock.json file inside the project. The project.json file can contain ranged versions or with specific versions like the one below

        "Microsoft.AspNet.Mvc": "6.0.0-beta6-*",
        "Newtonsoft.Json": "7.0.1"
    

    The project.lock.json file will contain the specific version that is being used by the project. If we doesn't specified ranged versions in the project.json file, then both the files will be identical. The project.lock.json is used by dnx enviroment for loading the references for your project because using project.json file may cause to resolve the versions every time the application is run.

    The lock file contians a key the very top called locked and when it's set to true then dnu or nuget will always restore and use the specific versions of every dependency specified in the lock file.


  • Setting up dnx environment in your machine

    If you are not a die hard fan of Visual Studio and regularly uses command prompt and text editors like Notepad or Sublime text for doing coding in C# and compilation, then there is a good news for you. You can make of the DNVM(.NET Version Manager) from ASP.NET Core from now. 

    If you have Visual Studio in your machine, then you can skip the set up part and jump straight into the command sections. Becuase Visual Studion installs DNVM by default and no set up is needed.

    Pre-requisites

    1. .NET version 4.5.2 or higher. If you don’t have it in your machine, install it from here. Need around 3 GB on your Windows drive, also admin access is needed for install. Don’t forget to reboot after the installation
    2. PowerShell version 4.0 or higher. Upgrade it here if you are running an older version. Admin access is needed for installation and also reboot is necessary once the installation is completed
    3. Install Visual C++ 2013 distributable package from here if it’s missing from your machine. Admin access is needed for this one also and you need to install both x86 and x64 versions

     

    Let’s confirm now that we are having the required version of Powershell  by using the command below

    $PSVersionTable.PSVersion

    It should show 4 if you have upgraded using the link above. Basically the version should be 4 or higher.

    So we have everything needed for the dnx environment to be installed in your box, so let’s type in the following command in the Command Prompt window to install it

    @powershell -NoProfile -ExecutionPolicy unrestricted -Command “&{$Branch=’dev';iex ((new-object net.webclient).DownloadString(‘https://raw.githubusercontent.com/aspnet/Home/dev/dnvminstall.ps1′))}”

    This will install the DNVM(.NET Version Manager) in to your user folder

    You can verify the installation is happened correctly by typing the command

    dnvm

     in PowerShell or Command Prompt. It will display a help information screen as shown below.


  • ASP.MVC 6 Features - wwwroot folder

    Whenever we web develop applications in .NET framework the root directory of the website has always been the directory where our project is located. All our C# source files, html pages, js files, aspx pages, cshtml files all reside under this root. The file system based approach has got many disadvantages especially when it comes to protecting sensitive project resources. Normally people used black listing to lock out access to files such as Global.asax and web.config being served to the clients as response and this was being done at framework level. It is always advisable to use whitelisting technique rather than using a blacklisting method from a security perspective.

    Also we will have different version of the same file say web.config for developement , testing, staging and production. And coming to scripts files we normally use the readable version of the files during development, but when it goes to the production we deploys only the minified version of it. Handling of these scenarios were getting difficult with each version and that's how the structure was devised for web projects in MVC 6

    By default the wwwroot folder will act as the root for your website and all the static files such as images, scripts, styles will reside in this folder. And the sensitive files like project.json, appsettings.json etc are not under wwwroot folder and will never be accessible if our site is compromised. Thus instead of blacklisting, we are giving access only to those files which are accessible.


  • ASP.MVC 6 Features - Managing Packages

    As developers, one of the thing we do frequently is adding references in the project. All these added dll's are listed under the References folder. Also listed are the libraries added by NuGet package manager used in C# code. These are called server side dependencies and is used in server side coding part.

    Since it's now possible to target multiple frameworks, the refernces are now grouped under References folder based on the targeted environments.

    By default, it will list two items under References, DNX 4.5.1 is targeting .NET framework 4.5 and DNX Core 5.0 is targetting .NET Core framework. If you expand it, then all referenced dll's will be listed.

    If you look closely the icons for the references, you can see that it's having the icon of Nuget. It indicates that these are all NuGet packages and if you manually added a dll, then it will have a different icon.

    Apart from these we will making use of different types of client side libraries like jQuery, Kendo, Angular etc. In MVC 6 all of it are placed under the dependencies folder. Managing client side frameworks is more tedious when compared to the server side cousins and two of the great names in open source package management is now supported in MVC 6. Bower and npm packages will be listed under the Dependencies 


  • ASP.MVC 6 Features - In Memory Execution

    In one of the earlier post we have seen that in MVC 6 it's now possible to do edit-and-continue very much like what we do while developing a desktop application

    Similarly, another important feature shipped with MVC 6 is the ability to do in memory compilation of the code. That means while building the application, output is generated in the bin folder and the web server load the files from there to run the application. But in MVC 6 this is turned of  by default and the files are compiled and stored in memory. One advantage of doing this is that it reduces the start up time considerably since there is very little time spent on disk I/O operations.

    Let's create a sample MVC 6 web project by selecting the Web Application template under ASP.NET 5 from Visual Studio.

    Visual Studio will create MVC project with model, controllers and views out of the box and you will get a barebone site without writing a single line of code.