Thursday, July 4, 2019

ASP.NET Technical Guru - May 2019

Another month as a judge in Microsoft TechNet Guru Awards under ASP.NET category. The TechNet Guru Awards celebrate the technical articles on Microsoft TechNet.

Original Post,
ASP.NET Technical Guru - May 2019  
Happy Coding.

Regards,
Jaliya

Monday, July 1, 2019

Received Microsoft MVP Award in Developer Technologies

I am honored to receive the precious Microsoft Most Valuable Professional (MVP) Award for the sixth consecutive year.

As always looking forward to another great year on top of Microsoft Development Stack.
MVPLogo_thumb[2]
Microsoft Most Valuable Professional (MVP)
Thank you Microsoft for your appreciation and Thank you everyone for your continuous support.

Happy Coding.

Regards,
Jaliya

Sunday, June 30, 2019

Task.Wait() Vs Task.GetAwaiter().GetResult()

In this post, let's go through one of the best practices when using async/await.

In some cases, we might want to run an async method synchronously and wait for the execution to be completed. Let's consider the below code.
static void Main(string[] args)
{
    // 1
    RunSomeTask().Wait();
 
    // 2
    //RunSomeTask().GetAwaiter().GetResult();
}
 
private static async Task RunSomeTask()
{
    // some long running work
}
 So our options to call RunSomeTask synchronously would be something like below,
  1. Task.Wait() (or Task.Result to get the return value if it returns something)
  2. Task.GetAwaiter().GetResult()
What would you prefer?

So the best practice is, we should be using Task.GetAwaiter().GetResult() instead of Task.Wait()/Task.Result(). Let's see why.

For the purpose of this post, I am modifying the RunSomeTask() method to throw an exception.
private static async Task RunSomeTask()
{
    await Task.Delay(200);
 
    throw new Exception("Failed because of some reason");
}

Now let's have a look at 2 different outputs.

When used Task.Wait():
Task.Wait()
When used Task.GetAwaiter().GetResult():
Task.GetAwaiter().GetResult()
As you can see when used Task.Wait(), if the task threw an exception, it will be wrapped inside an AggregateException. But when we are using Task.GetAwaiter().GetResult(), it will throw the exception directly which will make things like debugging/logging easy.

That's a very simple tip, but can be really useful.

On a final note, we should avoid calling tasks synchronously as much as possible.

Hope this helps.

Happy Coding.

Regards,
Jaliya

Wednesday, June 19, 2019

Best of Build Viewing Party - Auckland 2019

Today we had the Build Viewing Party in Auckland announcing the best of Microsoft Build 2019.  We had a very good panel discussion talking about a variety of things such as AI, Power BI, Development Technologies etc.

And I delivered a talk on Introduction to .NET 5 which is one of the biggest announcements this year.
Panel Discussion


Happy Coding.

Regards,
Jaliya

Wednesday, June 5, 2019

Visual C# Technical Guru - April 2019

Another month as a judge in Microsoft TechNet Guru Awards under Visual C# category. The TechNet Guru Awards celebrate the technical articles on Microsoft TechNet.

Post in WikiNinjas Official Blog,
Visual C# Technical Guru - April 2019
Happy Coding.

Regards,
Jaliya

Tuesday, May 28, 2019

Wrote a post on Wiki Life at Official Blog of TechNet Wiki

Wrote a post in Wiki Ninjas - Official Blog of TechNet Wiki. The title of the post is TNWiki Article Spotlight - Blazor: Deploying An Application On Firebase.
TNWiki Article Spotlight - Blazor: Deploying An Application On Firebase
Read the rest on,
TNWiki Article Spotlight - Blazor: Deploying An Application On Firebase

Happy Coding.

Regards,
Jaliya

Tuesday, May 7, 2019

Introducing .NET 5

At this year's Microsoft Build conference, one of the biggest announcements for developers is what's going to be the future for .NET. In this post, let's see what that is.

Before talking about what's next for .NET, let's have a quick recap of the history of .NET. The first version of .NET is .NET Framework 1.0 which was released back in February 2002. It has come a long way since then, almost for more than 17 years and today, the latest version is .NET Framework 4.8. .NET Framework is only available in Windows machines.

In November 2014, .NET Core 1.0 was released. The main idea of introducing .NET Core is going cross-platform. .NET Core has evolved rapidly since then, as of today the latest version of .NET Core is .NET Core 2.2. .NET Core 3.0 is scheduled to be released on  September 2019, while the preview release, .NET Core 3.0 Preview 5 is already out there. For all this time, Microsoft was porting features of .NET Framework to .NET Core. .NET Core 3.0 embraces the desktop by adding WinForms, WPF and Entity Framework 6 making it possible to port desktop applications to .NET Core.

On the other hand, there is Mono framework, which is an open source implementation of Microsoft’s .NET Framework that originally targetted Linux. It is based on the open standards which has its own C# compiler and a Common Language Runtime. Mono 1.0 was released in June 2004 and as of today, the latest Mono release is 5.20.

So there are basically 3 implementations of .NET, .NET Framework, .NET Core and Mono. All these frameworks has its own Base Class Libraries. So what's next.

6th of May, 2019, Microsoft has announced .NET 5, which is the next release after .NET Core 3.0. Microsoft is skipping .NET Core 4.0 version name because it can cause confusion with .NET Framework 4.x versions which have been there for a long time. And with .NET 5, there will be just one .NET going forward, so there is no need for a special term "Core". But of course, you can use the “.NET Core” name if you like it.

.NET Core 3.0 will be the core for .NET 5 and great features from Mono will be moved in (currently Mono runs on more platforms than .NET Core like Android, iOS, PlayStation etc).

.NET Framework 4.8 will be the last major version of .NET Framework. But that doesn't mean it's completely abandoned, it will get service updates and support for years to come. But after .NET Core 3.0, Microsoft will not be porting any more features from .NET Framework.

So here is what's going to be new with .NET 5.
  • You will have two choices on runtime experiences.
    • CoreCLR or Mono
      • These two runtimes has it's own unique capabilities and you will be able to decide which runtime to use using very simple configuration
  • Java interoperability will be available on all platforms.
  • Objective-C and Swift interoperability will be supported on multiple operating systems.
  • CoreFX will be extended to support static compilation of .NET (AOT), smaller footprints and support for more operating systems.

Release Schedule


.NET 5 is scheduled to be released on November 2020, with the first preview available in the first half of 2020.
.NET Schedule
After November 2020, Microsoft will be shipping a major version of .NET once a year, every November and every even-numbered release will have LTS (Long Term Support).

Developers Take

  • New applications should be built on .NET Core.
  • If you are a Web Forms developer and want to build a new application on .NET Core, Microsoft recommends Blazor
  • If you are remoting or WCF Server developer and want to build a new application on .NET Core, Microsoft recommends using either ASP.NET Core Web APIs, gRPC (provides cross-platform and cross programming language contract based RPCs) or Core WCF.
  • If you are a Windows Workflow developer, Microsoft recommends Core WF

Exciting times ahead!
Happy Coding.

Regards,
Jaliya

Tuesday, April 30, 2019

Visual C# Technical Guru - March 2019

Another month as a judge in Microsoft TechNet Guru Awards under Visual C# category. The TechNet Guru Awards celebrate the technical articles on Microsoft TechNet.

Post in WikiNinjas Official Blog,
Visual C# Technical Guru - March 2019
Happy Coding.

Regards,
Jaliya

Saturday, April 27, 2019

Global Azure Bootcamp 2019 - Auckland, New Zealand

I was fortunate enough to support Global Azure Bootcamp 2019 - Auckland, New Zealand.

Global Azure Bootcamp is a worldwide event happening on every year, and this time the day was April 27, 2019. The entire day was filled with great sessions delivered by industry experts from a variety of areas. 
Global Azure Bootcamp 2019 - Auckland, New Zealand - Speakers

I couldn't deliver a session but managed to support the event at least. 
Support Team
Happy Coding.

Regards,
Jaliya

Wednesday, April 3, 2019

Live Share in Visual Studio 2019

Finally, Visual Studio 2019 is released and one of the nice features which is generally available now with Visual Studio 2019 is Live Share.

Live Share makes it possible to share the code that you are working on right now and collaborate with fellow developers without using a separate tool. In this post, let's see how we can use Live Share.

I have some solution opened in Visual Studio 2019. There you should be able to notice this new button titled Live Share located at the top right corner.
Live Share
Once you click on that, you will see a prompt saying Visual Studio will now initiate the Live Share and your firewall will prompt to grant access to required ports. Once that is done, you will see the title of the button changed to Sharing and a link will be copied to your clipboard. 
Sharing
You just need to share the link with the other user. Once he/she has the link, he/she need to open up the link in a browser.
Open Sharing
Now I am switching to my other machine and have Visual Studio 2019 installed there.

As soon as I navigate to the link from a browser, I am prompted to open the link in an application. Here the possible applications are either Visual Studio 2019 or Visual Studio Code. I am selecting Visual Studio.

Now the shared solution will get opened in Visual Studio and it's just like I have the original solution running in my machine. I can see when the other person is highlighting the code, when he is doing any changes etc, it's almost instantaneous. I can also see the email of the other user at the cursor point. So imagine there are many users connected to the session, I will see who is doing what.
Sharing
And if I switch back to the machine which I initiated sharing, you can also share the terminal with participants in Read-Only or Read/Write mode.
Options
And finally, you can end the Live Share session, and your participants will get notified.
Session Ended
Once the sharing session is ended, your participants will no longer have access to the solution.

This is a really handy feature. Do try it out.

Happy Coding.

Regards,
Jaliya

Tuesday, April 2, 2019

.NET Core Worker Services

With .NET Core 3.0, you can create long running services as background services. With .NET Core 3.0.100-preview3, a new template is introduced named Worker Service. These services can be used to do things like processing messages in a queue, as a watcher etc.

In this post, let's see how we can get started on creating a Worker Service. For this you will need to have Visual Studio 2019 and .NET Core 3.0.100-preview3 installed in your machine. Remember to use .NET Core 3.0 with Visual Studio, you'll anyway need Visual Studio 2019 (By the way, Visual Studio 2019 RTM is getting released today, which I am very excited about).

Once those are installed, you can create a new ASP.NET Core Web Application. If you are wondering why do you need to create a Web Application, the reason is, currently the Worker template is sitting inside Web Application template and this is going to get changed in the future. The Worker Service template will be available directly inside the create new project wizard.

ASP.NET Core Web Application
Configure your new project
After giving the solution and project name, in the next dialog, you can see the Worker Service template. Make sure you have selected .NET Core and ASP.NET Core 3.0 as the target framework.

Worker Service Template
When the project is created, you can see two classes are created, first one is the familiar Program.

Program.cs
public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }
 
    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureServices(services =>
            {
                services.AddHostedService<Worker>();
            });
}
This is similar to what we used to in ASP.NET Core Web Applications, instead it directly configures services adding a service of any type which implements IHostedService. Here it's a type of a Worker.

Worker.cs
public class Worker : BackgroundService
{
    private readonly ILogger<Worker> _logger;
 
    public Worker(ILogger<Workerlogger)
    {
        _logger = logger;
    }
 
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            _logger.LogInformation($"Worker running at: {DateTime.Now}");
            await Task.Delay(1000, stoppingToken);
        }
    }
}
Worker implementing an abstract class BackgroundService which in turn implements IHostedService. Now if you run this, the message will get displayed until we issue an cancellation token, for instance until you press Ctrl + C etc.

Now you can use this to create a Windows Service or to use as a Linux Daemon with some very little changes.

Hope this helps.

Happy Coding.

Regards,
Jaliya

Monday, April 1, 2019

Running SQL Server Insider a Docker Container

Most of the time when we are working with an application which connects to a Microsoft SQL Server database, we usually have Microsoft SQL Server installed in the local machine and have our test database/s there and doing our testing against that.

With SQL Server containers you can avoid the installation and you can set up a SQL Server in a matter of minutes.

In this post, let’s see how we can setup SQL Server 2019 inside a Docker container. As of today, the latest SQL Server 2019 image is CTP 2.4.

First, make sure docker daemon is running in your machine. I am on Windows and it’s making sure Docker Desktop is running.

Now pull up the image from MCR (Microsoft Container Registry). If you are not aware that Microsoft has started maintaining its own container registry (like Docker Hub) and has started serving container images from there. You can find more information on that from this blog post: Microsoft syndicates container catalog).

I am using PowerShell.
docker pull mcr.microsoft.com/mssql/server:2019-CTP2.4-ubuntu
Once the command is completed, you can run the following command to make sure the image is present.
docker images
docker images
Next, before starting a container from this image, you need to accept end user license and setup a sa password. You can do all this and start up a container by below command.
docker run -e 'ACCEPT_EULA=Y' -e 'SA_PASSWORD=1qaz!QAZ@' -p 1433:1433 --name sql2019 -d mcr.microsoft.com/mssql/server:2019-CTP2.4-ubuntu
After that if you check on running containers, you should see our sql2019 container is running.
docker ps -a
Now you have a container which has SQL Server is running. Next thing you might want is to try the connectivity.

In this post I am using Microsoft SQL Server Management Studio (SSMS). I just need to get the local IP address of my machine and use it as the server name, use SQL Server Authentication and use sa credentials.
SSMS - Connected
It should get connected without any issues. Now if you want to restore a database, you can use either SSMS or sqlcmd. For this post, I will use SSMS.

When I try to select a .bak file, of course, it’s empty.
Locate Backup File
I can easily copy the file I want using docker cp command.
docker cp C:\Users\Jaliya\Desktop\WideWorldImporters-Full.bak <containerId>:/var/opt/mssql/data
Once the command completed, if I refresh the Locate Backup File dialog, I can see the copied file there. And from there I can select the file and do the restoration.

A couple of important things,
  • You can stop the container (in this case: docker stop sql2019) and start (docker start sql2019) it later without losing the changes in SQL Server Configuration and your databases.
  • But if you remove the container by doing a docker rm, everything in the container is deleted, including your databases.
That’s pretty neat, isn’t it. Hope this helps.

Happy Coding.

Regards,
Jaliya

Sunday, March 31, 2019

Visual C# and ASP.NET Technical Guru - February 2019

Another month as a judge in Microsoft TechNet Guru Awards. And this it’s under both Visual C# and ASP.NET category. The TechNet Guru Awards celebrate the technical articles on Microsoft TechNet.

Post in WikiNinjas Official Blog,
Visual C# Technical Guru - February 2019
Well, this time under Visual C# there were not many articles as it was used to be. Got into judging ASP.NET Category as well.
ASP.NET Technical Guru - February 2019
Happy Coding.

Regards,
Jaliya

Monday, March 4, 2019

IAsyncEnumerable<T> in C# 8

Before C# 8, if you want to iterate over a collection, the data for that collection needs to be ready before iteration.

Basically, something like this was not possible prior to C# 8.
private static async IEnumerable<string> GetDataAsync()
{
    for (var i = 0; i < 10; i++)
    {
        yield return await GetDataAsync(i);
    }
}
What you can do is something like below.
private static IEnumerable<string> GetDataAsync()
{
    for (var i = 0; i < 10; i++)
    {
        yield return GetDataAsync(i).Result;
    }
}
But this will cause a thread block. With C# 8 comes the IAsyncEnumerable<T> which makes the yield return asynchronous.
private static async IAsyncEnumerable<string> GetDataAsync()
{
    for (var i = 0; i < 10; i++)
    {
        yield return await GetDataAsync(i);
    }
}
You can see that even though it’s an async method, it’s not returning a Task anymore. You can iterate over an IAsyncEnumerable<T> using await foreach making it an async stream.
await foreach (var item in GetDataAsync())
{     
     Console.WriteLine(item);
}
Isn’t it nice.

Happy Coding.

Regards,
Jaliya

Thursday, February 28, 2019

Visual C# and ASP.NET Technical Guru - January 2019

Another month as a judge in Microsoft TechNet Guru Awards. And this it’s under both Visual C# and ASP.NET category. The TechNet Guru Awards celebrate the technical articles on Microsoft TechNet.

Post in WikiNinjas Official Blog,
image
Visual C# Technical Guru - January 2019
Well, this time under Visual C# there were not many articles as it was used to be. Got into judging ASP.NET Category as well.
image
ASP.NET Technical Guru - January 2019
Happy Coding.

Regards,
Jaliya

Tuesday, February 19, 2019

Wrote a post on Wiki Life at Official Blog of TechNet Wiki

Wrote a post in Wiki Ninjas - Official Blog of TechNet Wiki. The title of the post is TNWiki Article Spotlight – Blazor: Creating A Reusable Grid Component.
image
TNWiki Article Spotlight – Blazor: Creating A Reusable Grid Component
Read the rest on,
TNWiki Article Spotlight – Blazor: Creating A Reusable Grid Component

Happy Coding.

Regards,
Jaliya

Sunday, February 3, 2019

Visual C# Technical Guru - December 2018

Another month as a judge in Microsoft TechNet Guru Awards under Visual C# category. The TechNet Guru Awards celebrate the technical articles on Microsoft TechNet.

Post in WikiNinjas Official Blog,
Visual C# Technical Guru - December 2018
Happy Coding.

Regards,
Jaliya

Saturday, February 2, 2019

.NET Core Tools

.NET Core Tools was initially introduced with .NET Core 2.1. Basically .NET Core tools are .NET Core console apps that are packaged and distributed as NuGet packages and is similar to NPM global tools. Up to the release of .NET Core 3 Preview 1.0 back in December 2018, .NET Core tools are global meaning once installed, they are available from any location on the machine for the current user. But this did not allow the different tools version to be selected per location. Say for one repository you want the specific tool version of A, and for another repository, you want the version B, it wasn’t possible, but that’s until the release of .NET Core 3 Preview 2.0.

With .NET Core 3 Preview 2.0 which was released last week (29th January 2019), you can now maintain .NET Core tools locally as well as globally.

In this post, let’s have a look at how we can achieve that.

dotnetsay is a very basic .NET Core tool Microsoft has developed (you can find some nice set of tools here in this repo: natemcmaster/dotnet-tools). For this demo, let’s use the tool dotnetsay.

.NET Core Global Tools

To install a tool globally you can use the dotnet tool install command with --global/-g flag.
dotnet tool install -g dotnetsay --version 2.1.4
To run the tool you can use just say dotnetsay from the command prompt. Note: this is the ToolCommandName which is configured in the tool.
dotnetsay
To list all of the tools, use dotnet tool list.
dotnet tool list -g

dotnet tool list -g
To update a tool, use dotnet tool update.
dotnet tool update -g dotnetsay
And to uninstall, dotnet tool uninstall.
dotnet tool uninstall -g dotnetsay
Basically --global/-g flag means the .NET Core tools at the machine level.

.NET Core Local Tools

To install a .NET Core tool to a specific location, you can use the --tool-path flag.
dotnet tool install dotnetsay --tool-path "C:\Users\Jaliya\Desktop\dotnet-tool-dotnetsay" 
The above command will install dotnetsay latest version to a folder named dotnet-tool-dotnetsay in my Desktop. With .NET Core Local tools, there comes this concept of a manifest file. You can define a manifest file which is a json file at your folder and define all the tools and their versions you like to have it there. To create the manifest file, you can run the following command.
dotnet new tool-manifest
Once you run this command, you can see a folder created named .config. There inside, you can see a json file created named dotnet-tools.json which has the following structure.
{
  "version": 1,
  "isRoot": true,
  "tools": {}
}
Now sitting inside your folder (dotnet-tool-dotnetsay here in my case) run the following command.
dotnet tool install dotnetsay
And now you should see the dotnet-tools.json file is updated as follows.
{
  "version": 1,
  "isRoot": true,
  "tools": {
    "dotnetsay": {
      "version": "2.1.4",
      "commands": [
        "dotnetsay"
      ]
    }
  }
}
To run local tools, you can’t execute ToolCommandName just like you did for global tools. For that, you need to use dotnet tool run command.
dotnet tool run dotnetsay
To see all your local tools, run dotnet tool list.
dotnet tool list
And you can see the following output.

dotnet tool list
There you can see which manifest is being used.

One of the important things to note is, if you don’t have a manifest file inside a folder, to install a local tool, you need to specify --tool-path flag.

Hope this helps.

Happy Coding.

Regards,
Jaliya

Tuesday, January 29, 2019

Visual Studio 2019 Preview 2.0 and .NET Core Tooling Update

As you might already know, Visual Studio 2019 Preview 2.0 was released and there were a couple of nice features got introduced.

In this post, let’s have a quick peek on two of the most interesting things.

Double click and open .csproj file

This is really handy work. We usually interact a lot with .csproj files in the solution and so far what we used to do is, right click on the project and click on Edit .csproj.
Edit .csproj
And this not that user-friendly. What if we can simply double click on the project file to open it. That will be super easy, isn’t it? And with Visual Studio 2019 Preview 2.0, that’s possible. No more right clicking on the project and select Edit .csproj, just double click on the project and the project file gets opened.

New Integrated Console

Say you are trying or testing some piece of code, what we often do is creating a console application and write the code there (sometimes I use dotnetfiddle, but that’s for some basic code). And if you are just running the code and if you missed adding a Console.Read() at the end, the program will execute and the console will exit. But with the new integrated console, the program will execute and the console will stay open. And all the subsequent runs, the same window will be used, meaning you won’t have multiple consoles open for each session which can be annoying.
Microsoft Visual Studio Debug Console
And if you want to opt-out from having the console window opened, you can do so by going to Tools –> Options –> Debugging –> General and selecting Automatically close the console when debugging stops.
Automatically close the console when debugging stops
Hope this helps.

Happy Coding.

Regards,
Jaliya

Wednesday, January 9, 2019

.NET Core 2.2: Runtime Events

In this post let’s go through one of the features which got introduced with .NET Core 2.2 which is the ability to capture .NET Core runtime events within your .NET Core application.

Prior to .NET Core 2.2, these CoreCLR events were unable to be consumed within your .NET Core application, it was only available to be observed in ETW (Event Tracing for Windows) on Windows or from LTTng on Linux.

With .NET Core 2.2, these events are getting routed through an EventListener, so within your EventListener, you can decide what to do with it. It basically doesn’t matter on which OS you are on, it works on all Windows/MacOS and Linux.

Let’s have a look at an example. I have created an ASP.NET Core Web API Application targetting .NET Core 2.2.
<Project Sdk="Microsoft.NET.Sdk.Web">
 
  <PropertyGroup>
    <TargetFramework>netcoreapp2.2</TargetFramework>
    <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
  </PropertyGroup>
  
  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.App" />
  </ItemGroup>
 
</Project>
There I have the following EventListener.
public class SimpleEventListener : EventListener
{
    private readonly ILogger<SimpleEventListener> _logger;
 
    public SimpleEventListener(ILogger<SimpleEventListener> logger)
    {
        _logger = logger;
    }
 
    // Called whenever an EventSource is created.
    protected override void OnEventSourceCreated(EventSource eventSource)
    {
        // Watch for the .NET runtime EventSource and enable all of its events.
        if (eventSource.Name.Equals("Microsoft-Windows-DotNETRuntime"))
        {
            EnableEvents(eventSource, EventLevel.Verbose, (EventKeywords)(-1));
        }
    }
 
    // Called whenever an event is written.
    protected override void OnEventWritten(EventWrittenEventArgs eventData)
    {
        // Write the contents of the event to the console.
        _logger.LogInformation($"ThreadID = {eventData.OSThreadId} ID = {eventData.EventId} Name = {eventData.EventName}");
 
        for (var i = 0; i < eventData.Payload.Count; i++)
        {
            string payloadString = eventData.Payload[i] != null ? eventData.Payload[i].ToString() : string.Empty;
            _logger.LogInformation($"\tName = \"{eventData.PayloadNames[i]}\" Value = \"{payloadString}\"");
        }
 
        _logger.LogInformation("\n");
    }
}

Now I am enabling the SimpleEventListener from Startup.ConfigureServices method.
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
 
    ServiceProvider provider = services.BuildServiceProvider();
    var simpleEventListener = new SimpleEventListener(provider.GetRequiredService<ILogger<SimpleEventListener>>());
}

That’s it. Now if you run the application, you should be able to see all the CoreCLR events.
image
.NET Core 2.2: Visual Studio on Windows: CoreCLR Events
I just ran the same application inside MacOS, it works the same.
image
.NET Core 2.2: Rider on MacOS: CoreCLR Events
Now, if I change the target framework to 2.1 and return the application, we can’t see CoreCLR events.
image
.NET Core 2.1: Visual Studio on Windows: No CoreCLR Events
This is some awesome piece of work.

Happy Coding.

Regards,
Jaliya

Friday, December 28, 2018

Visual C# Technical Guru - November 2018

Another month as a judge in Microsoft TechNet Guru Awards under Visual C# category. The TechNet Guru Awards celebrate the technical articles on Microsoft TechNet.

Post in WikiNinjas Official Blog,
image
Visual C# Technical Guru - November 2018
Happy Coding.

Regards,
Jaliya

Thursday, December 20, 2018

Visual Studio 2019: Start Window

I am sure most of you are already experiencing the new Visual Studio 2019, and you definitely must have seen the new Start window.
image
Visual Studio 2019: Start Window
Personally, I like the previous Start Page, and if you feel like you are missing it in Visual Studio 2019, you are not. Go to Tools –> Options –> Environment –> Startup and change On startup, open to Start Page.
image
Startup Options
Now restart Visual Studio, and when starting up, you will see that Visual Studio will open the Start Page and not the Start window.

Hope this helps.

Happy Coding.

Regards,
Jaliya

Thursday, December 13, 2018

.NET Core 2.2: Executing Code Prior to Main Method

Last week .NET Core 2.2 was released with some nice features and in this post, let’s see one of them which is executing code before the Main method.

As we all know the Main method is the entry point of a program. But .NET Core 2.2 is introducing this feature called Host startup hook and it provides a mechanism to execute code before executing the Main method.

I have created two class library projects named StartupHook1 and StartupHook2 and both of them are targeting .NET Core 2.2. Inside both of the projects, I am adding a class named StartupHook.
using System.Diagnostics;
using System.Reflection;
 
internal class StartupHook
{
    public static void Initialize()
    {
        Debug.WriteLine($"{Assembly.GetExecutingAssembly().GetName().Name} is called.");
    }
}

Note: The type must be named StartupHook without any namespace and it should be internal. And inside the class, we should have a static method named Initialize. For the sake of the post, I am just logging a message inside the method.

When I build the projects, I will have two dlls, StartupHook1 and StartupHook2.

Now take an existing .NET Core 2.2 application. For the demo, let’s just create an ASP.NET Core 2.2 Web Application. And to link the web application and the two class libraries (which are startup hooks), we need to add an environment variable named DOTNET_STARTUP_HOOKS to the web application as follows. We can easily do that by going to web application project properties and adding an environment variable.

image
ENVIRONMENT VARIABLE
It’s basically something like below.
DOTNET_STARTUP_HOOKS=SomePath\StartupHook1.dll;SomePath\StartupHook2.dll
Now I will just modify the web applications Main method to add some logging.
public static void Main(string[] args)
{
    Debug.WriteLine("Main is called.");
 
    CreateWebHostBuilder(args).Build().Run();
}

Now if I run the ASP.NET Core web application, I am seeing the below.

image
Debug Output
You can see that the Initialize methods in both StartupHook1 and StartupHook2 has been called before the actual entry point. And the execution order is the order we have defined the hooks in the environment variable.

Isn’t it nice.

For more information,
   Host startup hook

Happy Coding.

Regards,
Jaliya