Click here to Skip to main content
15,880,427 members
Articles / Web Development / Blazor

Are You Ready to Learn Blazor for Cross-Platform Mobile Development using Mobile Blazor Bindings

Rate me:
Please Sign up or sign in to vote.
4.96/5 (12 votes)
4 Feb 2020CPOL12 min read 38.1K   308   16   2
In this article, we will learn how to getting started and work with new Mobile Blazor Binding for developing Cross-Platform Mobile application using Blazor.

Introduction

Image 1

In this article, we will learn how to get started and work with new Mobile Blazor Binding for developing Cross-Platform Mobile application using Blazor. We will cover the following topics.

  • How to install Mobile Blazor Binding
  • Create our first Mobile Blazor Binding Application
  • Create a simple Mobile Game application to Find my Name within 5 attempts
  • Add Text to Speech functionality using the Xamarin Essentials

On 14th January, 2020, Microsoft introduced new Experimental Mobile Blazor Binding for developing Cross-Platform Mobile application using Blazor. Yes, for now, this is only an experimental release but still we can start working and play to learn on Mobile Blazor Binding to develop our Mobile application using the Blazor code. For all C# programmers, this will be a great start to develop a mobile application using C# Code and there is not much need to know about Xamarin, Android or IOS development.

Mobile Blazor Binding is the combination of Blazor and Xamarin.Forms. UI design part is based on the Xamarin.Forms UI Controls and the components and code part is based on Blazor. The combination of Blazor, and Xamarin.Forms allows the user to create Native Mobile app development for both IOS and Android using the Web programming pattern. All the design and code part for both Android and IOS can be made from the Blazor project and using the Android and IOS project, the app can be run on appropriate emulator or device.

For more details, refer to this link.

Getting Started with Mobile Blazor Binding Application

When we create the Mobile Blazor Binding Blazor application, we can see by default, 3 projects will be added in our solution. In the solution, we can find 3 projects as:

1. Blazor Project

This is where we design our page UI and do all business logic for mobile application development using Blazor. Note for the UI design part, we will be using the same Xamarin.Forms UI controls in our Razor pages. In our code part, we can see more in detail about adding new page creating our own Game using Blazor code.

2. Android Project

We can also see the Android project has been added in our solution and this project is used for building and running the Blazor application in Android Emulator or on the Android Device.

3. IOS Project

We can also see the IOS project has been added in our solution and this project is used for building and running the Blazor application in IOS Simulator or on the IOS Device.

Image 2

Background

Prerequisites

In order to work with Mobile Blazor Binding, you need to have .NET Core 3.0 or higher version SDK. You need to have Visual Studio or Visual Studio for Mac, ASP.NET Web Development and Mobile Development with Xamarin.Forms Workloads installed in your computer. Here for my article, I have installed Visual Studio 2019 latest version and used .NET Core 3.0 SDK:

Installing Mobile Blazor Binding Template

After installing the prerequisites, you are ready to work with Mobile Blazor Binding, but for working with Mobile Blazor Binding, we need the template to be installed. For this, open your command prompt.

Click Windows Start: Type CMD and press Enter in the command prompt.

In the command prompt, enter the below code to install the Microsoft MobileBlazorBindings Templates.

We need to run the below code in CMD or from the shell and copy the code and past and hit enter.

dotnet new -i Microsoft.MobileBlazorBindings.Templates::0.1.173-beta

Wait for a few seconds for the template to be installed.

Image 3

Using the Code

Creating Mobile Blazor Binding Application

Click Windows Start: Type CMD and press Enter in the command prompt.

From the Command prompt, go to your Drive and Folder where you want to create the application.

Here, I have created folder under D:> Drive and I will create my project under the Android/Blazor folder.

For creating the Project in the command prompt, run the below command:

dotnet new mobileblazorbindings -o ShanuMobile

Note that ShanuMobile is the projectName. You can add your needed project name over there.

Image 4

Mobile Blazor Binding Solution Structure

Image 5

When we create the Mobile Blazor Binding Blazor application, we can see by default 3 projects will be added in our solution. In solution, we can find 3 projects as:

1. Blazor Project

This is where we design our page UI and do all business logic for mobile application development using Blazor. Note for the UI design part, we will be using the same Xamarin.Forms UI controls in our Razor pages. In our code part, we can see more in detail about adding new page creating our own Game using Blazor code.

Image 6

Here, we have created the project name as “ShanuMobile” has been created as the Blazor project and in this project, we can see the Microsoift.MobileBlazorBinding and Xamarin.Forms Packages has been added by default. Also, the Blazor project contains the files as:

  • Imports.razor

    The Import.razor file has the default needed import of Xamarin.Forms and MobileBlazorBindings to create native mobile app for Android and IOS using the Xamarin.Forms with Blazor code.

    Image 7

  • App.cs

    In the App.cs class, we will give the default razor page to be loaded, here in the below code, we can see as HelloWorldRazor page has been added to show by default.

    Image 8

  • Counter.Razor

    By default, we can see the Counter.Razor page has been added. Here in this page, we can see the Xamarin.Form's UI controls have been used in the example like StackLayout also we can see the Blazor code functions have been added to perform the increment in the button click event.

    Image 9

  • HelloWorld.Razor

    In the HelloWorld Razor page, we can see as the page was made as the ContentPage and this page will be loaded first and added the Counter page inside the content page of Helloworld to perform the Increment functions.

    Image 10

2. Android Project

We can also see the Android project has been added in our solution and this project is used for building and running the Blazor application in Android Emulator or on the Android Device.

Image 11

Here, we have created the project name as “ShanuMobile” and the Android project was been created by default as ShanuMobile.Android.

Here, we don’t have much part to deal with as we will be adding our Blazor App in MainActivity to run our mobile application in the Android, We can also add the App display Name in Label here by default, the project name has been added in the Label. You can change it if needed, also we can change the icon for the app from the MainActivity. In order to run our Blazor app in Android mobile Device or in Emulator, set the Android project as Startup Project.

Image 12

3. IOS Project

We can also see the IOS project has been added in our solution and this project is used for building and running the Blazor application in IOS Simulator or on the IOS Device.

Image 13

Here, we don’t have much part to deal with as we will be adding our Blazor App in AppDelegate to run our mobile application in the IOS. In order to run our Blazor app in IOS mobile Device or in Simulator, set the IOS project as Startup Project.

Image 14

Run the Blazor APP in Android

Now we can see the Counter Demo in Android Device or in the Android Emulator. For this, first set the Android project as Startup Project. For this, right click the Android project and click on “Set as Startup Project”. You can run the application in the Android connected Device via USB or by the installed Android Emulator.

Image 15

Here, I have connected my Samsung Galaxy Note 10 mobile via USB and selected my mobile device to run the Blazor Mobile Application. You can connect to your Android device or select or Install Android Emulator to run in the emulator.

Once selected, our Android Device runs the application and waits for few seconds. We can see our mobile application will be running in our connected Android mobile device.

Image 16

Find My Name Mobile Game Creation using Blazor

What is Find My Name Puzzle Game

Image 17

Find My Name Puzzle Game is a quiz game where the user needs to select my total character of name from the Hidden Character. I have a set of 12 characters, for example “ABSDEHGZNXCU”. In this total character, my name characters “SHANU” has been added. Whenever the user clicks on a New Puzzle Game button, I will shuffle all the characters and make 12 buttons with the “?” symbol for all the characters and in button click event, we will pass the character from 12 char as array from 0 to11 for each button starting from the button 1 to 12 .

The rule is simple as the user will have only 5 chances and within these 5 chances, he/she needs to find my name as “SHANU” each button will have one character within the “ABSDEHGZNXCU”. The first button will have the first character and the second button will have the second character, like this up to 12 buttons will have one character from 1 to 12. The tricky thing is whenever the user clicks on the start game, we will shuffle the 2 characters arrangement and randomly bind the character to buttons. The button will not show the hidden character and the button will have the text as “?” The user needs to find exactly my name as “Shanu” from the 5 attempts. If he found means he/she won the Game, else lost the Game. There is no limit as user can try any number of times and play the game. This is a kind of Puzzle fun game.

In this game, we will also use the Xamarin.Essentials for using the Text to Speech functionality in order to use speech functionality in Game Start and Won/Loss message announcement. By adding the speech functionality, the game will be more interactive and fun to play by the end users.

Step 1: Game.Razor Page Add

Right click the Blazor Project and click on Add New Item and select the Razor Component and give the name as Game.razor and click Add.

Image 18

Step 2: Adding Xamarin.Essentials Package to the Blazor Project

For using the Text to speech functionality in our Mobile Game App, we need to install the Xamarin.Essentials packages to the blazor project. For this, right click on the Blazor project and click on Manage NUGet Packages.

Image 19

Select Browse and search for the Xamarin Essentials and click on Install. Wait for a few seconds for the packages to install on your project.

Step 3: Game Design Part Coding

Now open the Game.Razor page and replace the code with the below code for our mobile game design.

Here in the below code, first we add the Game Title as “Find My Name Game” in label. Next, in the label, we display the return result values from the blazor code part of the game. Next we add the Start Game button which calls the ShowButton method from the code to shuffle the puzzle string and bind the result to buttons and to use the Text to speech functionality. Next, we add one more label to show the final result message as the user Won or Lost the game. And finally, we check for the New game and display 12 buttons to play the game and in each button click, we call the Find Result by passing parameter as character Array from 0 to 11 for each button starting from 1 to 12. In the findResult method, we check for the result and announce the result using text to speech also display the message as Won or Loss to the user.

XML
<Frame CornerRadius="10" BackgroundColor="Color.Gold">

    <StackLayout Orientation="StackOrientation.Horizontal" 
     HorizontalOptions="LayoutOptions.Center">
        <Label Text="Find My Name Game!"
               FontAttributes="FontAttributes.Bold"
               VerticalTextAlignment="TextAlignment.Center" FontSize="25" /> 
    </StackLayout>

</Frame>

<Frame CornerRadius="10" BackgroundColor="Color.LightBlue">

    <StackLayout Orientation="StackOrientation.Horizontal" 
     HorizontalOptions="LayoutOptions.Center">
        <Label Text="Result : "
               FontAttributes="FontAttributes.Bold"
               VerticalTextAlignment="TextAlignment.Center" FontSize="25" />

        <Label Text="@results"
               FontAttributes="FontAttributes.Bold"
               VerticalTextAlignment="TextAlignment.Center" FontSize="25" />

    </StackLayout>

</Frame>

<Button Text="Start Game" OnClick="@showButtons" BackgroundColor="Color.LightSkyBlue" />

<Frame CornerRadius="10" BackgroundColor="Color.DeepPink">

    <StackLayout Orientation="StackOrientation.Horizontal" 
     HorizontalOptions="LayoutOptions.Center">

        <Label Text="@messages"
               FontAttributes="FontAttributes.Bold"
               VerticalTextAlignment="TextAlignment.Center" FontSize="25" />

    </StackLayout>

</Frame>

@if (findmyNameChar.Length > 0)
{
    <Frame CornerRadius="10" BackgroundColor="Color.DarkBlue">
        <StackLayout Orientation="StackOrientation.Horizontal" 
         HorizontalOptions="LayoutOptions.Center">
            <Button Text="?" BackgroundColor="Color.LightSkyBlue" 
             OnClick="() => findResult(findmyNameChar[0].ToString())" />

            <Button Text="?" BackgroundColor="Color.LightSkyBlue" 
             OnClick="() => findResult(findmyNameChar[1].ToString())" />

            <Button Text="?" BackgroundColor="Color.LightSkyBlue" 
             OnClick="() => findResult(findmyNameChar[2].ToString())" />
        </StackLayout>
    </Frame>

    <Frame CornerRadius="10" BackgroundColor="Color.DarkBlue">
        <StackLayout Orientation="StackOrientation.Horizontal" 
                     HorizontalOptions="LayoutOptions.Center">
            <Button Text="?" BackgroundColor="Color.LightSkyBlue" 
                             OnClick="() => findResult(findmyNameChar[3].ToString())" />

            <Button Text="?" BackgroundColor="Color.LightSkyBlue" 
                             OnClick="() => findResult(findmyNameChar[4].ToString())" />

            <Button Text="?" BackgroundColor="Color.LightSkyBlue" 
                             OnClick="() => findResult(findmyNameChar[5].ToString())" />
        </StackLayout>
    </Frame>

    <Frame CornerRadius="10" BackgroundColor="Color.DarkBlue">
        <StackLayout Orientation="StackOrientation.Horizontal" 
        HorizontalOptions="LayoutOptions.Center">
            <Button Text="?" BackgroundColor="Color.LightSkyBlue" 
            OnClick="() => findResult(findmyNameChar[6].ToString())" />

            <Button Text="?" BackgroundColor="Color.LightSkyBlue" 
            OnClick="() => findResult(findmyNameChar[7].ToString())" />

            <Button Text="?" BackgroundColor="Color.LightSkyBlue" 
            OnClick="() => findResult(findmyNameChar[8].ToString())" />
        </StackLayout>
    </Frame>

    <Frame CornerRadius="10" BackgroundColor="Color.DarkBlue">
        <StackLayout Orientation="StackOrientation.Horizontal" 
        HorizontalOptions="LayoutOptions.Center">
            <Button Text="?" BackgroundColor="Color.LightSkyBlue" 
            OnClick="() => findResult(findmyNameChar[9].ToString())" />

            <Button Text="?" BackgroundColor="Color.LightSkyBlue" 
            OnClick="() => findResult(findmyNameChar[10].ToString())" />

            <Button Text="?" BackgroundColor="Color.LightSkyBlue" 
            OnClick="() => findResult(findmyNameChar[11].ToString())" />
        </StackLayout>
    </Frame>
}

Step 4: Game Design Part Coding

Now open the Game.Razor page and replace the code with the below code for our mobile game design.

First, declared all the needed variables and in the ShowButtons method, we shuffle the namePuzzle randomly during each call and stored in the FinmyNameChar. Also, clear all the values for first time game start.

Also using the Xamarin.Essentials.TextToSpeech.SpeakAsync, we send the text as the "Five Chance to find Shanu" to convert the text to speech and make it as the announcement for the user as the game is going to start. Each time the user clicks on the Start game method, this function will be called and the speech announcement will be made.

The findResult method will be called from the 12 buttons which has the “?” and send the parameter as the findmyNameChar[0] array value start from 0 to 11 to the function and check the logic for finding the name as “Shanu”, also check for 5 attempts and finally display the result to the users.

C#
@code {

    int CharCount = 0; // To check and maintain the user click on each button

    int findvalue = 5; // To check the result count which is less than the find value 
        // here I have used 9 so the user can check their name trail only for 9 times.

    string namePuzzle = "ABSDEHGZNXCU";

    string findmyNameChar = "";
    string tofind = "SHANU";
    string results = "";
    string messages = "";

    void showButtons()
    {
        // to shuffle the character and reorder the characters for new Puzzle Game start

        Random rnd = new Random();

        findmyNameChar = new string(namePuzzle.ToCharArray().
                       OrderBy(s => (rnd.Next(2) % 2) == 0).ToArray());

        results = "";
        CharCount = 0;
        messages = "Start Your Game";

        Xamarin.Essentials.TextToSpeech.SpeakAsync
                ("Five Chance to find Shanu").ContinueWith((t) =>
    {
}, TaskScheduler.FromCurrentSynchronizationContext());

    }

    private void findResult(string puzzleChar)
    {
        CharCount = CharCount + 1;
        if (CharCount <= findvalue)
        {
            results = results + puzzleChar;
            if (CharCount >= tofind.Length)
            {
                if (results == tofind)
                {
                    messages = "You Won :)";
                    Xamarin.Essentials.TextToSpeech.SpeakAsync
                                       ("Wow You Won").ContinueWith((t) =>
                      { 
                    }, TaskScheduler.FromCurrentSynchronizationContext());
                }
                else
                {
                    messages = "You Loss :(";
                    Xamarin.Essentials.TextToSpeech.SpeakAsync
                                        ("Sorry You Loss").ContinueWith((t) =>
                     { 
                    }, TaskScheduler.FromCurrentSynchronizationContext());
                }
            }
        }
        else
        {
            results = "";
            CharCount = 0;
            messages = "Try Again :(";
        }
    }
}

Step 5: Add the Game.razor Page to the Main Content Page

In HelloWorld, we add the Game razor page in content page to load the game. Also, we change the Title from the Hello World to “Shanu Blazor Mobile!

Image 20

Step 6: Run the Application in Android Device or in Emulator

Here, we have used the Samsung Galaxy Note 10 Android app to run my game. You can run in any Android Device on your installed Android emulator.

Image 21

Points of Interest

Mobile Blazor Bindings is a experimental release and not for production use. But for now, it will be a good place for getting started and work with Mobile Blazor Bindings for developing native mobile app using Blazor. This is really needed for all the Web Developers as well for C# lovers who are not very familiar with Native app development even not much familiar with Xamarin. We, as C# lovers, will always love to work with this kind of native mobile application development, that too with Blazor means it's like a cake with more honey for us. Let's wait for the production release. Till then, let's experiment more with Mobile Blazor Bindings.

History

  • 22nd January, 2020: ShanuMobile.Zip

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader
India India
Microsoft MVP | Code Project MVP | CSharp Corner MVP | Author | Blogger and always happy to Share what he knows to others. MyBlog

My Interview on Microsoft TechNet Wiki Ninja Link

Comments and Discussions

 
QuestionWebview in mobile Blazor Bindings Pin
Member 1341944127-Mar-20 0:55
Member 1341944127-Mar-20 0:55 
QuestionTrying to run this sample on iOS Pin
tim larson17-Feb-20 6:44
tim larson17-Feb-20 6:44 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.