Wednesday, August 21, 2019

C# 8.0: notnull Generic Constraint

A couple of months back I wrote a post about C# 8.0: Nullable Reference Types which is a feature coming with C# 8.0. A few days back Microsoft has released .NET Core 3.0 Preview 8. And from .NET Core 3.0 Preview 7 onwards, C# 8.0 is now considered feature complete.

In this post, let's go through this nice feature added regarding Nullable Reference Types which is notnull generic constraint. This feature was released with .NET Core 3.0 Preview 7. Nullable Reference Types is an opt-in feature, meaning it's not enabled by default. In this post, I am not going to explain how you can enable it, you can refer to the old post linked above for that. 

Consider the following code. I have a generic interface, a class that implements it. Even though I have added the interface and the class in the same file, consider this an external library. Now from the Main, I am creating an object of MyClass of type nullable string and calling its method. Note: I have enabled Nullable Reference Types.
#nullable enable
 
namespace ConsoleApp1
{
    interface IMyInterface<TIn>
    {
        void MyMethod(TIn input);
    }
 
    public class MyClass<TIn> : IMyInterface<TIn>
    {
        public void MyMethod(TIn input)
        {
            // some code which uses input
        }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            string? myString = null;
 
            var myClass = new MyClass<string?>();
            myClass.MyMethod(myString);
        }
    }
}
The above code will not show any warnings. Now imagine for some reason, I don't want to allow the generic type to be nullable. Enter notnull Generic Constraint.

I can update the code as follows.
interface IMyInterface<TIn>
    where TIn : notnull
{
    void MyMethod(TIn input);
}
 
public class MyClass<TIn> : IMyInterface<TIn>
    where TIn : notnull
{
    public void MyMethod(TIn input)
    {
        // some code which uses input
    }
}
We need to add the constraint to both the interface and the class. As soon as we do that, the following line will issue a warning.
// Warning CS8714  The type 'string?' cannot be used as type parameter 'TIn' in the generic type or method 'MyClass<TIn>'.
// Nullability of type argument 'string?' doesn't match 'notnull' constraint.

var myClass = new MyClass<string?>();
We can fix the warning by update the code as follows.
var myClass = new MyClass<string>();
And then we will need to fix the next warning of trying to pass a nullable string to MyMethod.

I really find this a really handy feature. One of the best examples would be, Microsoft has already constrained Dictionary<TKey, TValue>, where TKey is now to be notnull, which disallows using null as a key.

Hope this helps.

Happy Coding.

Regards,
Jaliya

Thursday, August 1, 2019

ASP.NET Technical Guru - June 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,

Regards,
Jaliya

Tuesday, July 30, 2019

ASP.NET Core Hosting Models with IIS

With the introduction of ASP.NET Core 2.2, ASP.NET team has introduced 2 hosting models when we are hosting the ASP.NET Core application in IIS.

One is In-process and the other is Out-of-process. In-process hosting is made possible with the introduction of aspNetCoreModuleV2 which is a required to host ASP.NET Core applications targeting 2.2 or higher. You will get this once you install .NET Core Runtime & Hosting Bundle which is a prerequisite.

You can configure the hosting model pretty easily through one of the following approaches.

1. Through Project Properties in Visual Studio, Under Debug
Visual Studio
2. From the csproj file
csproj file
If the <AspNetCoreHostingModel> property isn't present in the file, the default value is OutOfProcess.

By doing this when the project is published, the web.config file will contain information on whether to run the application In-Process or Out-of-process.
<aspNetCore processPath="dotnet" arguments=".\HelloWorld.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="InProcess" />
So what’s is In-process and Out-of-process hosting.

In-process

In process basically means the ASP.NET Core application will get run inside IIS Worker process (w3wp.exe) and hence the naming. So here IS HTTP Server (IISHttpServer) is used instead of Kestrel server.

Out-of-process

When on Out-of-process, ASP.NET Core application does not run on IIS Worker process, instead it will be running on Kestrel and all the requests are being forwarded to Kestrel.

So what is preferred and why. In-process is the preferred hosting model in IIS. In-process hosting provides improved performance because requests don’t get proxied over to a separate dotnet process. Microsoft states there is an improved throughput of up to 400% on when In-process hosting model is IIS.

More Information,
Host ASP.NET Core on Windows with IIS

Hope this helps.

Happy Coding.

Regards,
Jaliya

Friday, July 5, 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

Tuesday, July 2, 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

Monday, July 1, 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

Thursday, June 20, 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

Wednesday, May 8, 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