DEV Community

Jay Malli
Jay Malli

Posted on

Develop & Publish .NET MAUI Application for Windows using Visual Studio Code

Hello Developers,

=> So today we are developing a basic app using .NET maui framework & we'll publish it for the Windows platform.

=> .NET MAUI, which stands for .NET Multi-platform App UI, is an open-source, cross-platform framework for building native mobile and desktop applications. It is an evolution of the Xamarin.Forms framework and is part of the broader .NET ecosystem.

Before we start our work , let's install required tools.

Step - 1 : Installation task

-> Add required Extensions in vs code

  • C# (by Microsoft)
  • .NET Runtime Install Tool (by Microsoft)

-> after that open settings & search Omnisharp , make sure that
"Use Omnisharp" checkbox is enabled.

C# extension omnisharp
omnisharp auto start

-> check above tools are installed successfully or not by following commands from terminal.

dotnet --list-sdks
dotnet --list-runtimes

dotnet sdk

-> Check whether maui workload is exist not.

dotnet workload list

maui workload

-> List all available workloads.

dotnet workload search

workload list

-> Install maui workload

dotnet workload install maui

-> Check installed workload

dotnet workload list

maui workload

Step - 2 : Create Maui Project

-> Create Maui Template.

dotnet new maui

Maui Template

-> open the [project_name].csproj file & perform following acions

comment this tag net7.0-android;net7.0-ios;net7.0-maccatalyst

target framework

dotnet restore (add nuget packages,mentioned in .csproj file)

restore

dotnet build

build

Step - 3 : Let's do some code

=> Add fonts :

-> Add OpenSans-Regular.ttf & OpenSans-Semibold.ttf fonts file in the Resources/Fonts folder. (check out my github repo for required resources : Repo)

font

=> AppShell.xaml :

// remove title from header
<ShellContent
    ContentTemplate="{DataTemplate local:MainPage}"
    Route="MainPage"
    Shell.NavBarIsVisible="False" 
/>
Enter fullscreen mode Exit fullscreen mode

=> MainPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Groot_App_Maui.MainPage">

    <ScrollView>
        <VerticalStackLayout
            Spacing="25"
            Padding="30,0"
            VerticalOptions="Center">

            <Image
                Source="groot_img.jpg" // Add this image in resources folder
                SemanticProperties.Description="Cute groot waving hi to you!"
                HeightRequest="400"
                HorizontalOptions="Center" />

            <Label
                Text="I am Groot!"
                SemanticProperties.HeadingLevel="Level1"
                FontSize="32"
                HorizontalOptions="Center" />

              <Button
                FontAttributes="Bold"  
                Text="Click Me"  
                FontSize="{OnPlatform WinUI=16, MacCatalyst=18}"
                HorizontalOptions="Center"
                Clicked="OnClickBtn"  
             /> 

        </VerticalStackLayout>
    </ScrollView>

</ContentPage>

Enter fullscreen mode Exit fullscreen mode

-> Please add the Groot image to the Resources/Images folder and the Groot app icon to the Resources/AppIcon folder. You can obtain these files from this repository.

resources

app icon

=> MainPage.xaml.cs :

// remove unnecessary code

namespace Groot_App_Maui;

public partial class MainPage : ContentPage
{

    public MainPage()
    {
        InitializeComponent();
    }

        public async void OnClickBtn(object sender, EventArgs e)
    {
        await 
 Application.Current.MainPage.DisplayAlert(null, "Again I am Groot :)", "OK");
    } 
}

Enter fullscreen mode Exit fullscreen mode

=> [project_name].csproj :

// other code
<ItemGroup>
        <!-- App Icon -->
        <MauiIcon Include="Resources\AppIcon\app_icon.png"/>
</ItemGroup>
Enter fullscreen mode Exit fullscreen mode

app icon

Step - 4 : Lets run our app

dotnet run -f net7.0-windows10.0.19041.0 (from .csproj file)

Profile error

Groot happy

-> yaa yaa! "I know Groot; I forgot to modify the launch settings file of the app."

-> The launchSettings.json is used to configure various settings related to the debugging and launching of your application for different environments and configurations.

=> Modify Properties/launchSettings.json file

{
  "profiles": {
    "Windows (Debug)": {
      "commandName": "Project",
      "commandLineArgs": "--device windows --theme Light",
      "workingDirectory": "$(ProjectDir)",
      "launchBrowser": true,
      "launchUrl": "",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "Windows (Release)": {
      "commandName": "Project",
      "commandLineArgs": "--device windows --theme Light",
      "workingDirectory": "$(ProjectDir)",
      "launchBrowser": true,
      "launchUrl": "",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Production"
      }
    },
    "Mac (Debug)": {
      "commandName": "Project",
      "commandLineArgs": "--device macos --theme Light",
      "workingDirectory": "$(ProjectDir)",
      "launchBrowser": true,
      "launchUrl": "",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "Mac (Release)": {
      "commandName": "Project",
      "commandLineArgs": "--device macos --theme Light",
      "workingDirectory": "$(ProjectDir)",
      "launchBrowser": true,
      "launchUrl": "",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Production"
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

-> Again run app

dotnet build
dotnet run -f net7.0-windows10.0.19041.0

-> If the app is not launched or running, then check the Events Log in the Event Viewer,

Search Menu >> Event Viewer >> Windows Logs >> Application

-> If you encounter this error, add the following code to the .csproj file.

Event logs

=> .csproj file :

<WindowsAppSDKSelfContained>true</WindowsAppSDKSelfContained><WindowsPackageType>None</WindowsPackageType>
Enter fullscreen mode Exit fullscreen mode

csproj file

-> Again run app

dotnet build
dotnet run -f net7.0-windows10.0.19041.0

  • Yaahh! app o/p

Step - 5 : Its time to publish our app

-> We will create an MSIX package to publish the app. For that, we need to create a self-signed certificate to demonstrate our app.

-> If you want to learn more about the MSIX package, please visit: MSIX Docs

=> Create Self Signed Certificate :

-> Open PowerShell as an administrator and execute the following commands:

New-SelfSignedCertificate -Type Custom
-Subject "CN=<PublisherName>"

-KeyUsage DigitalSignature
-FriendlyName "My temp dev cert"

-CertStoreLocation "Cert:\CurrentUser\My" `
-TextExtension @("2.5.29.37={text}1.3.6.1.5.5.7.3.3", "2.5.29.19={text}")

// replace PublisherName with name of author e.g. CN=JayMalli

-> You will receive the thumbprint of the certificate upon successful creation. Copy that thumbprint.

certificate thumbprint

-> Execute this command in PowerShell to get all thumbprints.

Get-ChildItem "Cert:\CurrentUser\My" | Format-Table Subject, FriendlyName, Thumbprint


=> Export Certificate :

-> Open the 'Manage User Certificates' dialogue box using the search menu.

Manage User Certificates

-> Go to Personal>>Certificates>> tab

not trusted certificate

-> The self signed certificate is not verified & valid for 1 year.

-> Export the certificate by following these steps.

-> Navigate to the details tab in that certificate dialogue box ,

Click on Copy to file button >> Next
do not export private key >> Next
DERbinary Encoded >> Next
Specify location & file name by browse option >> Next
Finish

Image description

-> You can find the exported certificate at the specified location in the file system.


=> Verify Certificate :

-> Open manage computer certificates

Image description

-> Navigate to the 'Trusted Root Certification Authorities.

Right click on Certificates tab
All task>> import
Local machine should be checked >> Next
Click on browse button
Select certificate from location where you previously stored
Place all ecrtifcates in following store should be enable
Next >> Finish

-> Now, go back to 'Manage User Certificates' and check that the certificate is verified

Image description

=> Sign our app using created certificate :

-> add below code in .csproj file

// Replace your_certificate_thumbprint with the previously created thumbprint, which was generated in PowerShell.

csproj file

-> update below code in .csproj file

// comment this tags for production mode of app
// Update the App ID to the appropriate name.

csproj file


=> Configure resources for production app:

-> Create an 'Assets' folder and place all resources in it. Please check this repository for reference.

-> Modify Package.appxmanifest file with below code.

// Replace 'Your_Name' with the name you want to display as the publisher in the app.

// Replace 'Your_thumbprint_Name' with the name which was provided in the creation of thumprint.

csproj code

csproj code

-> Reference this repo for code.

=> Publish App:

-> execute following command in the terminal

// Replace 'your_certificate_thumbprint' with the previously created thumbprint, which was generated in PowerShell.

dotnet build /restore /t:publish /p:TargetFramework=net7.0-windows10.0.19041.0 /p:configuration=release /p:GenerateAppxPackageOnBuild=true /p:AppxPackageSigningEnabled=true /p:PackageCertificateThumbprint=your_certificate_thumbprint

published app msix package

-> Open the MSIX package in the file storage and launch it

installation wizard

Install app

app section

Launch app

=> finally Groot is here! :)

production app

=> The example above demonstrates how to develop & publish .NET maui app for windows platform , you can find the necessary code in the repository mentioned below.

=> GithHub Repository

Thank you for joining me on this journey of discovery and learning. If you found this blog post valuable and would like to connect further, I'd love to connect with you on LinkedIn. You can find me at LinkedIn

If you have thoughts, questions, or experiences related to this topic, please drop a comment below.

Top comments (0)