Step by step installation of .Net Core 2.0

core26

In my previous post, I have explained how to set up for .Net Core 2.0 which you can find here.

But in that post, it mainly focuses on how to do the setup if you already have .Net Core. So in this post, I will explain how to install .Net core 2.0(Without having Core 1.0) on your machine.

First of all, you need to install .Net Core 2.0 sdk from here.

Once you double click on the exe, it will start the process as below:

core21

Once the process is done, it will show below window:

core22

Once this is done, Open Visual Studio command prompt as below and run the command:

dotnet new console -o console-app

core23

It shows that .Net Core 2.0 has been installed on your machine. For more information, you can go through the documents by clicking on the links shown in the console.

Now we will run a console application from the command prompt.

One sample application is already provided which resides on below path(It may change):

C:\Windows\System32\console-app

Now run the command:

dotnet run

core25

Which will return “Hello World”, it shows your installation is successful.

You can even run below command to verify the version:

dotnet –version

It should return 2.0

You can open this sample project on Visual Studio 2017.

To Create new Core 2.0 project, you need to select the version in the drop down as shown below:

core27

 

 

 

 

 

Advertisements

Razor pages compilation on Publish: A .Net Core 2.0 feature

core5

.Net Core 2.0 is announced last week and it came up with some awesome features.

I am going to explain its one of the best features which is the compilation of views and pages on Publish.

Till now(before .Net core 2.0) whenever we publish any MVC application, Razor files are published as .cshtml files and they get compiled at runtime.

Which means:

  • It takes a bit more time just to compile all those cshtml files
  • Publish output size increases

.Net Core 2.0 has one inbuilt functionality which compiles page and views on publish.

It means:

  • Our Razor pages and views would get published with our app as a compiled assembly instead of being published as .cshtml source files that get compiled at runtime

So it has advantages as:

  • Reduces application startup time
  • Reduces Publish output size

So the conclusion is, our .Net Core 2.0 applications are faster than the older applications.

Please note that we can disable this feature if we do not require this.

It can be done by simply updating below property in csproj file:

<MvcRazorCompileOnPublish>false</MvcRazorCompileOnPublish>

Have a look here if you require more details.

 

C# 8.0 expected features Part – I

c#8

We all know that Microsoft always delivers awesome features in all the releases and they are already planning for the features of C# 8.0

As per a video on Channel 9, Mads Torgersen has explained about the possible features of C# 8.0

There are possibly 4 features till now which are as below:

  • Nullable reference types
  • Async Streams(Foreach Async)
  • Default Interface Implementations
  • Extension Everything

In this post, I will explain about the Async Streams.

For normal Async methods we write it as below:

async Task(int) Test()
{
    return x;
}

and we call it by:

await Test();

What it does is, it waits until the things returned from Test method and after that only, it goes to the next step.

But it works with only one resource.

Now imagine we want to work with some live stream where we get data in the continuous live stream. For example, some IoT where data comes every moment. But we want to process them in our own time like one at a time.

Here comes the Async version of IEnumerable:

IAsyncEnumerable<T>

So basically, it is just like an enumerable except that when you move next in an enumerable way, that is Async.

It is kind of a way of Lay loading enumerability in Async way.

When defining an async iterator, you would use this function signature:

async IAsyncEnumerable<string> MethodName()
{
   yield return "Test";
}

And can be used as:

foreach await (string s in asyncStream)

Above is nothing but the combination of Async and Enumerable, you wait inside it and you return inside it.

Though it looks like IObersable but it is different. The benefit of using this instead of IObservable<T> from Reactive Extensions is that the consumer controls the flow rate. This is referred to as a “pull model” and IObservable<T> is a “push model”.

In Foreach Async, consumers tell when it is ready and then it processes the next one.

I hope you liked this future feature of C#.

 

 

 

 

.Net Core 2.0 deployment on AWS

core 7

In my previous post, I have explained how to setup your .Net Core 2.0 which you can find here.

In this post, I will explain how to deploy your .Net Core 2.0 application into AWS Elastic Beanstalk.

First of all, let us see what is AWS Elastic Beanstalk?

AWS Elastic Beanstalk is an orchestration service offered from Amazon Web Services for deploying infrastructure which orchestrates various AWS services, including EC2, S3, Simple Notification Service (SNS), CloudWatch, autoscaling, and Elastic Load Balancers.

Please note that Elastic Beanstalk currently has Core 1.0 and it will be soon updated to have Core 2.0

If you want to know about the .Net Core 1.0 deployment then have a look here.

So I will explain what can be done to deploy your Core 2.0 application on Elastic Beanstalk until the platform is updated to support Core 2.0

All we need to do is to add aws-windows-deployment-manifest.json file into our Core 2.0 application.

aws-windows-deployment-manifest.json is used to instruct Beanstalk to install .NET Core 2.0 on the instance during deployment.

Add below lines into to aws-windows-deployment-manifest.json file:

{
  "manifestVersion": 1,
  "deployments": 
  {
    "aspNetCoreWeb": [
    {
      "name": "app",
      "parameters": {
      "appBundle": ".",
      "iisPath": "/",
      "iisWebSite": "Default Web Site"
    },
      "scripts": {
      "preInstall": {
      "file": "./Scripts/installnetcore20.ps1"
       }
     }
   }
  ]
 }
}

Basically, above lines instruct Elastic Beanstalk to deploy .Net Core application.

But we want to deploy .Net Core 2.0 application, so for that we need to execute the ./Scripts/installnetcore20.ps1 PowerShell script which is already mentioned in above json file.

Now we need to add this ./Scripts/installnetcore20.ps1 Powershell file into Core 2.0 application.

Add below lines into PowerShell file:

$localPath = 'C:\dotnet-sdk-2.0.0-win-x64.exe' if(!(Test-Path $localPath)) { Invoke-WebRequest -Uri 'https://download.microsoft.com/download/0/F/D/0FD852A4-7EA1-4E2A-983A-0484AC19B92C/dotnet-sdk-2.0.0-win-x64.exe' -OutFile $localPath & $localPath /quiet /log c:\InstallNetCore20.log }

Above script downloads the .NET Core 2.0 installer and run the installer from the Microsoft site.

As we know that many times it is possible that link is broken or changed so in this case another option is to put Core 2.0 installer into the S3 bucket of AWS application (I did that way)

Our .Net Core 2.0 application looks as below:

core6

Another way is using Docker image if your application is Docker basked.

If you know any other way then please suggest in below comment section.

Setup for Asp .Net Core 2.0

core2

Microsoft has announced Core 2.0 and it has some awesome features which I will explain in future blog posts.

For now, let us see how to converts your Core 1.0 application into Core 2.0

First of all, we will change the .Net core version in global.json file as shown below:

{
   "sdk": {
   "version": "2.0.0-preview3-006912"
  }
}

After that we need to change the target library to Core 2.0 as shown below:

1-TargetFramework

Also, change and update below line in .csproj file:

<TargetFramework>netcoreapp2.0</TargetFramework>

Once it is done, we need to add below package in the .csproj file:

<ItemGroup>

<PackageReference Include=“Microsoft.AspNetCore.All” Version=“2.0.0” />

</ItemGroup>

This new metapackage contains references to all of the AspNetCore packages and maintains a complete line-up of compatible packages.  You can still include explicit references to specific Microsoft.AspNetCore.* package versions if you need one that is outside of the lineup

Now we need to change PackageTargetFallback in same .csproj file as below:

<AssetTargetFallback>$(AssetTargetFallback);portable-net45+win8+wp8+wpa81;</AssetTargetFallback>

Here we added AssetTargetFallback instead of earlier PackageTargetFallback

Now let us jump to the Main method in Program.cs class. In Core 1.0 we used to add different extended methods like .UseKestrel(), .UseIISIntegration() etc.

For Core 2.0 it is more simplified as shown below:

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;

namespace AspNetCoreDotNetCore2._0App
{
   public class Program
   {
     public static void Main(string[] args)
     {
       BuildWebHost(args).Run();
     }

   public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
     .UseStartup()
      .Build();
  }
}

Now your application is converted into Core 2.0 from Core 1.0

Query string in .Net core and MVC 6

download

As you all know that from MVC6 we are seeing some changes in our regular coding techniques.

We were using below lines in MVC5 for getting values from query string:

var myQueryString = Request.QueryString[“myQueryString”]

But in MVC6, above lines will throw errors in your code.

So, you might be wondering how can we achieve this in MVC6.

Below is the way:

We can use Request.Query which is new in ASPNET 5 and MVC6.

var myQueryString = Request.Query;

For example, you have an URL like:

http://www.myWebsite.com/Home/Index?myQueryString1=abc&myQueryString2=xyz

So to get all keys we will write below code:

var myQueryString = Request.Query;

Here myQueryString.keys contains all the keys which are there in your query string.

Now to take those keys out one by one, we will write below code:

foreach(var key in myQueryString.Keys)
{
   //// Do the operations as per your need with the key
}

That is it. You can easily get your values from the Query string in MVC6 and .Net core.

MVC6 (.Net core) applications are self hosted : Optional IIS integration

All ASP.NET Core applications are self-hosted.

Yes you read it right!

So does it mean IIS is not required?

Yes, I mean we can host MVC6 application even without IIS.

Wow…but How?

I assume you have already downloaded .Net core from here.

Next step would be to create sample MVC6 project.

For now you can directly clone it from Github by below commands:

git clone git@github.com:aspnet/cli-samples.git
cd cli-samples\HelloMvc

Then we would restore and run the project as below:

dotnet restore
dotnet run 

That is it!

Now navigate to localhost:5000 in your web browser and you can see your application hosted there.

You must be wondering how it happened?

You can check it by yourself in code.

Open Program.cs class and you can see below code there:

public class Program
{
    public static void Main(string[] args)
    {
        var config = new ConfigurationBuilder()
            .AddCommandLine(args)
            .AddEnvironmentVariables(prefix: "ASPNETCORE_")
            .Build();

        var host = new WebHostBuilder()
            .UseConfiguration(config)
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration() //// Here IIS integration is optional
            .UseStartup()
            .Build();

        host.Run();
    }
}

As you can see in above comments, IIS integration is optional in .Net core.

Happy coding!