Blazor now in official preview

Some days ago, the ASP.NET team announce the official preview of Blazor, the Microsoft framework for building Single Page Application. Note that in the post, they declare that Server-Side Blazor will ship as part of .NET Core 3.0, announced for second half 2019, while Client-side Blazor will ship as part of a future .NET Core release.

Upgrade to Blazor preview

To upgrade your existing Blazor apps to the new Blazor preview first make sure you’ve installed the prerequisites listed above then follow these steps:

  • Update all Microsoft.AspNetCore.Blazor.* package references to 3.0.0-preview4-19216-03 by changing the PackageReference in csproj with this: <PackageReference Include="Microsoft.AspNetCore.Blazor" Version="3.0.0-preview4-19216-03" />
  • Remove any package reference to Microsoft.AspNetCore.Components.Server
  • Remove any DotNetCliToolReference to Microsoft.AspNetCore.Blazor.Cli and replace with a package reference to Microsoft.AspNetCore.Blazor.DevServer
  • In client Blazor projects remove the <RunCommand>dotnet</RunCommand> and <RunArguments>blazor serve</RunArguments> properties
  • In client Blazor projects add the <RazorLangVersion>3.0</RazorLangVersion> property
  • Rename all _ViewImports.cshtml files to _Imports.razor
  • Rename all remaining .cshtml files to .razor
  • Rename components.webassembly.js to blazor.webassembly.js
  • Remove any use of the Microsoft.AspNetCore.Components.Services namespace and replace with Microsoft.AspNetCore.Components as required.
  • Update server projects to use endpoint routing:

Replace this:

app.UseMvc(routes =>
{
    routes.MapRoute(name: "default", template: "{controller}/{action}/{id?}");
});

With this:

app.UseRouting();

app.UseEndpoints(routes =>
{
    routes.MapDefaultControllerRoute();
});

Run dotnet clean on the solution to clear out old Razor declarations.

https://devblogs.microsoft.com/aspnet/blazor-now-in-official-preview/

Enjoy!

Goodbye TLScrollView. Welcome BindableLayout!

Three years ago I wrote a blog post about my Xamarin.Forms component TLScrollView, a simple horizontal scrollview with bindable feature. The post was one of the most viewed and commented, and I’m really happy about that, but now, with the latest version of Xamarin.Forms, you can use the new BindableLayout feature.

Move TLScrollView to BindableLayout

Looking back, in my post you can see how to use the TLScrollView control:

<controls:TLScrollView Orientation="Horizontal" ItemsSource="{Binding Items}" HeightRequest="100">
    <controls:TLScrollView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <StackLayout Padding="5">
                    <controls:TLImageCircle Source="{Binding Image}" HeightRequest="80" WidthRequest="80" />
                </StackLayout>
            </ViewCell>
        </DataTemplate>
    </controls:TLScrollView.ItemTemplate>
</controls:TLScrollView>

Change the code to support the BindableLayout is really simple. You don’t need to use my custom control since the BindableLayout is applicable to all Layout Xamarin.Forms controls. So, using the StackLayout, add the BindableLayout.ItemsSource attribute and the BindableLayout.ItemTemplate attribute to implement the binding. Here you can see the new code:

<StackLayout Orientation="Horizontal" BindableLayout.ItemsSource="{Binding Items}" HeightRequest="100">
    <BindableLayout.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <StackLayout Padding="5">
                    <controls:TLImageCircle Source="{Binding Image}" HeightRequest="80" WidthRequest="80" />
                </StackLayout>
            </ViewCell>
        </DataTemplate>
    </BindableLayout.ItemTemplate>
</StackLayout>

Check here how the BindableLayout works.

Enjoy!

Using C# 8 on Visual Studio 2019 for Mac Preview

With Visual Studio 2019 Preview you can start to play with C# 8 and its great new features. While on Windows you only needs to install Visual Studio 2019 and .NET Core 3.0, on Mac you needs some additionally trick to make it works. In this post we’ll see how you can use C# 8 Preview with Visual Studio 2019 for Mac Preview.

Prepare your Mac

First of all, you need to download and install the following packages:

After installation is complete, start Visual Studio 2019 for Mac Preview and create a .NET Core Console Application:

Create Console Application

Setting up your project

Now, click on projects Options > General and then set Target Framework to .NET Core 3.0:

Set Target Framework

To successfully build the project, you need to add the Microsoft.Net.Compilers package, preview version, from NuGet:

Add Microsoft.Net.Compilers package

Finally, edit the .csproj and add the following xml elements:

<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
  <LangVersion>Preview</LangVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
  <LangVersion>Preview</LangVersion>
</PropertyGroup>

You can check the full list of LangVersion here.

Start to play with C# 8

Ready to write you first C# 8 app? Go!

Your first C# 8

Check here what’s new in C# 8 and give it a try!

Note Most of the C# 8.0 language features will run on any version of .NET, but a few of them, like Async streams, indexers and ranges, all rely on new framework types that will be part of .NET Standard 2.1

UPDATE Visual Studio 2019 for Mac Preview 3

With the recently released Preview 3, you can set the C# language to Preview directly on project options:

Visual Studio 2019 Preview 3

Update it if you have already installed!

Auto generate AssemblyInfo.cs in .NET Core

As you can see in my last post, I’m moving my TitiusLabs.Core PCL to .NET Standard. After project migration, you can choose to maintain AssemblyInfo - and in my previous post you can see how to do it - or move to an auto generation model, as we’ll see in this post.

To auto generate the AssemblyInfo.cs, simply put the following PropertyGroup element in your .csproj:

<PropertyGroup>
  <Company>TitiusLabs</Company>
  <Authors>Fabio Cozzolino</Authors>
  <PackageId>TitiusLabs.Core</PackageId>
  <Version>1.0.0</Version>
  <AssemblyVersion>1.0.0.0</AssemblyVersion>
  <FileVersion>1.0.0.0</FileVersion>
</PropertyGroup>

To avoid the Duplicate 'System.Reflection.AssemblyCompanyAttribute' attribute (CS0579) remove the AssemblyInfo.cs and set to true the GenerateAssemblyInfo in .csproj:

<PropertyGroup>
   <GenerateAssemblyInfo>true</GenerateAssemblyInfo>
</PropertyGroup>

And that’s all!

Update Portable Class Library project to .NET Standard

Recently, I decided to upgrade my TitiusLabs.Xamarin library to the latest version of Xamarin.Forms and to .NET Standard 2.0. Here a small guide you need to follow if you want to upgrade your project from a very old version.

Update your project to .NET Standard 2.0

The first step in my path is the update of the TitiusLabs.Core project, a Portable Class Library (PCL) project, to a .NET Standard Library. To proceed, you need to be sure to have the right .NET Core version installed so, if not, go to the download page and install it!

Now, simply open the .csproj file and full replace it with the following xml:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <Folder Include="Properties\" />
  </ItemGroup>
</Project>

Check your solution

Reopen your solution, or refresh it, and check if all projects correcly loads and reference your .NET Standard project. Most probably, you’ll get the following errors:

.NET Standard errors

If you want to still use AssemblyInfo.cs, then add the following xml element into the .csproj:

<PropertyGroup>
   <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
</PropertyGroup> 

Now your code will work fine. To choose the correct version, be sure to check .NET Standard compatibility on this page.

That’s all!

Use Azure Functions from Microsoft Blazor app

Azure Functions is a great way to build serverless applications in really few minutes. You can create a new API and host in Azure without worrying about server infrastructure. That sounds really good!

Just few steps

To build your Azure Functions, you can just follow these steps:

  1. Go to the Azure Portal and login by using your credentials or create a new account
  2. Click on New Resources and then write Function App

Function App

  1. Select the Function App item and then click on Create button

Function App

  1. Now set your function name

Function App

  1. Finally you’ll find the new Azure Function in the relative section

Function App

Now it’s time to write code

In Azure Function App, you can click in + button to create a new HTTP function:

Add Function

select the in-portal mode and then WebHook + API to quickly create a function online:

Function App Function App

Now click on HttpTrigger1 on left panel:

HttpTrigger1

On the right panel, you’ll see the startup code on file run.csx

#r "Newtonsoft.Json"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;

public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    string name = req.Query["name"];

    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    dynamic data = JsonConvert.DeserializeObject(requestBody);
    name = name ?? data?.name;

    return name != null
        ? (ActionResult)new OkObjectResult($"Hello, {name}")
        : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
}

You can adapt and change the above code as you like to meet your needs.

Run, run your code

Finally, it’s time to press on RUN button and see the result in the right panel:

Function Result

And that’s all! You can write Azure Function triggered by HTTP requests by using the online portal editor.

Wait … and Blazor?

As said, Azure Functions give you the ability to create a serverless application architecture. This means that you can call your function from anywhere. Since it is exposed via REST API, you can call it in a Blazor app, and it is really simple. The HttpClient is registered by default in the Blazor IoC, so you can simply write @inject HttpClient http after the @page directive and then use it in your code:

@page "/"
@inject HttpClient http

<!-- My HTML Code -->

@functions
{
    protected override async Task OnParametersSetAsync()
    {
        var url = "https://myawesomefunc.azurewebsites.net/api/HttpTrigger1?code=hIxLyOrcHlliT...W8aGprWLNLQ==";
        var awesomeResponse = await http.GetJsonAsync<string>(url);
    }
}

Enjoy!

Blazor 0.8.0 Released!

As reported in MSDN blog post, Blazor 0.8.0 was just released! It is still an experimental framework, but now the path is clear since the team made a big announce: Server-side Blazor is now ASP.NET Core Razor Components in .NET Core 3.0

As was recently announced, server-side Blazor is now shipping as ASP.NET Core Razor Components in .NET Core 3.0. We’ve integrated the Blazor component model into ASP.NET Core 3.0 and renamed it to Razor Components. Blazor 0.8.0 is now built on Razor Components and enables you to host Razor Components in the browser on WebAssembly.

So … stay tuned!

How to enable Face ID on Xamarin.iOS

With iPhone X, Apple release a new biometric authentication way: Face ID. Like others things, you need to obtain access to that feature. To achieve this, you must add the NSFaceIDUsageDescription key to the info.plist file:

Enable Face ID

The, optional, description will be good if you want to explain why your app request the ability to authenticate with Face ID.

After that, you will be able to use Face ID authentication:

var context = new LAContext();
if (context.CanEvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, out NSError authError))
{
    var replyHandler = new LAContextReplyHandler((success, error) =>
    {
        InvokeOnMainThread(() =>
        {
            if (success)
            {
                // user authenticated
            }
            else
            {
                // user not authenticated
            }
        });
    });
    context.EvaluatePolicy(LAPolicy.DeviceOwnerAuthenticationWithBiometrics, "Authenticate", replyHandler);
}

the above code will works for both Touch ID and Face ID.

Enjoy!

Deploy a Blazor app on GitHub Pages

In my previous post, I’ve introduced Blazor and how you can create a new project by using Visual Studio Code on MacOS. Now we’ll see how to publish our Blazor app to GitHub Pages. This is possible since Blazor is a frontend framework and you can deploy it on any static web server host, just like GitHub Pages.

Create deployment files

As you already know, with .NET you can use the CLI (Command Line Interface) to do a lot of things, like create or build a project from Terminal. By using the same approach, we can create the deployment files with the dotnet publish -c Release command:

Publish Blazor app

now, as you can see in the last row, you’ll find the output in the publish folder. Now go on yourprojectname folder, and then open the dist folder. Here you’ll find the deployment files.

Deployment files

Deploy on GitHub Pages

Now, the final steps:

You need to create your GitHub Pages repository before continue, see this page

  1. Clone your GitHub Pages repository https://github.com/yourusername/yourusername.github.io
  2. Copy the deployment files from the dist folder to your GitHub local repository
  3. Add an empty .nojekyll file to disable the default Jekyll interpreter for GitHub Pages

You can also manage 404 error or handling redirect by creating the 404.html page

That’s all, you are ready to run your GitHub Pages build with Blazor.

Enable Tls 1.1 or Tls 1.2 on WCF 4.0

Windows Communication Foundation 4.0 support Ssl3/Tls1.0 out-of-the-box. If you need to support Tls1.1 or Tls1.2, you must update to .NET Framework 4.6. If you can’t do that, try the following workaround just before establish the secure connection:

Set the SecurityProtocol to 768 if you want to use Tls1.1

System.Net.ServicePointManager.SecurityProtocol = (System.Net.SecurityProtocolType)768;

or set to 3072 if you want to use Tls1.2

System.Net.ServicePointManager.SecurityProtocol = (System.Net.SecurityProtocolType)3072;

Note

Be sure to have .NET Framework 4.5 or above installed on the client machine!

Enjoy!