Electron.NET – Create a minimal MusicPlayer App with ASP.NET Core 2 for the Desktop

Electron.NET – Create a minimal MusicPlayer App with ASP.NET Core 2 for the Desktop

Actually, this blog is addressed to Cross-Platform development with JavaScript. But this time, I have a very special treat for you: Electron.NET! A new open source project which I developed in cooperation with my Microsoft MVP colleague and friend Robert Muehsig.

As the name confirms, we developed an Electron derivation for .NET Core. This allows to develop Cross-Platform desktop applications with C# and ASP.NET Core. We haven´t reinvented the wheel. The runtime is based on Electron. So Electron.NET is build on an advanced and solid platform.

This article shows on a plain sample how easy it is, to develop Cross-Platform desktop software with Electron.NET and ASP.NET. We will develop a MusicPlayer, which has access to the music list to play any song we want.

Preperations for the start:

A new ASP.NET Core 2 project

First of all, we create a new ASP.NET Core Web Application. Then choose the empty template and make sure you got ASP.NET Core 2.0 selected.

New ASP.NET Core Project
Empty Template

Picture 1 – Create a new ASP.NET Core 2 project

Next, we need to install MVC via NuGet Package Manager:
Install-Package Microsoft.AspNetCore.Mvc -Version 2.0.0

Once installed there is a little work to do, before we can start. We will need to add a little something to the Startup.cs. At first we need to configure the app to use the MVC framework.

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
}

In the next step we have to configure the app to use the MVC request execution pipline (routing), with a default route.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{ 
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });

    // ...
}

Now that the MVC framework has been added we can add a Controller and a View to the project. Therefore we add a new folder, which we call Controllers. Then, right click on it to add a new Controller.

New Controller
Empty Controller
Controllername

Picture 2 – Add a new Controller

The HomeController will be added with a default method called Index. To add a view we need to right click on View() and select AddView.

New View
Viewname

Picture 3 – Add a new View

A new views folder including the Index.cshtml has been created automatically. The ASP.NET MVC Core project is now ready to implement some logic.

Add Electron.NET

There are just a few more things to do, so we can run the ASP.NET MVC Core 2 application with Electron.NET. Of course we´ll need to install Electron.NET API through the NuGet Package Manager:
PM> Install-Package ElectronNET.API

The UseElectron WebHostBuilder-Extension will be added to Program.cs then.

public static IWebHost BuildWebHost(string[] args)
{
    return WebHost.CreateDefaultBuilder(args)
        .UseElectron(args)
        .UseStartup<Startup>()
        .Build();
}

That´s it! Now Electron.NET can be used in our project. So far, nothing would happen, if we would run the project now. The application would just run in the background. Because we do not want to develop any background processes, we´ll add some bootstrap code to Startup.cs, so an MainWindow will appear. Additionally we want the security option to be disabled. This will allow us to get access to the music list.

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

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

    Bootstrap();
}

public async void Bootstrap()
{
    var options = new BrowserWindowOptions
    {
        WebPreferences = new WebPreferences
        {
            WebSecurity = false
        }
    };

    await Electron.WindowManager.CreateWindowAsync(options);
}

Access to the file system

We will need access to the file system within the HomeController now. To do so, the Electron.NET API gives us the opportunity to detect the path of the current platform of the music list. With .NET Core we get access to the filenames within the list. We´ll pass the results to the view then.

using ElectronNET.API;
using ElectronNET.API.Entities;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

namespace MyElectronMusicPlayer.Controllers
{
    public class HomeController : Controller
    {
        public async Task<IActionResult> Index()
        {
            string musicPath = await Electron.App.GetPathAsync(PathName.music);
            string[] mp3Files = Directory.GetFiles(musicPath, "*.mp3", SearchOption.TopDirectoryOnly);
            string[] mp4Files = Directory.GetFiles(musicPath, "*.mp4", SearchOption.TopDirectoryOnly);

            List<string> musicFiles = new List<string>();
            musicFiles.AddRange(mp3Files);
            musicFiles.AddRange(mp4Files);

            return View(musicFiles);
        }
    }
}

The View

The view and functionality is easy and not that much spectacular in this example. So there will just be shown a list of the music files which will play by button click. To do this, the HTML5 audio class will be used.

@model List<string>

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>My Electron Music Player</title>
    <meta charset="utf-8" />
</head>
<body>
    <h3>My Music</h3>
    <ul>
        @foreach (string musicFile in Model)
        {
            <li>
                 @System.IO.Path.GetFileNameWithoutExtension(musicFile)

                <button onclick="playMusic('@musicFile.Replace(@"\", "/")')">Play</button>
            </li>
        }
    </ul>

    <script>

        function playMusic(musicFile) {
            let audio = new Audio(`file:///${musicFile}`);
            audio.play();
        }

    </script>
</body>
</html>

Start of the Electron.NET Application

The Electron.NET CLI is necessary to execute the Electron.NET application. Unfortunately, we need to install the CLI by adding a reference to .csproj file instead of an installation via NuGet as usual.

<ItemGroup>
       <DotNetCliToolReference Include="ElectronNET.CLI" Version="*" />
</ItemGroup>

Then run dotnet restore in the console.

If it´s a new Electron.NET project, it is necessary to run dotnet electronize init once. For that there will be a electron.manifest.json file generated an a new debugging profile will be provided.

The command dotnet electronize start will start the ASP.NET MVC Core 2 application as a desktop software.

Important! The first start may take a while. We are working on a solution to speed this up.

Electron.NET Music Player

Picture 4 – The Electron MusicPlayer application

Building the application

The Electron.NET CLI also makes it possible to build an executable application for Windows, Mac and Linux. Every platform does this with the dotnet electronize build command:

dotnet electronize build win
dotnet electronize build osx
dotnet electronize build linux

Important! A Mac or Linux device is required to build Mac applications.

Summary

We´ve seen in this sample, how easy it is to create a desktop software using ASP.NET MVC Core 2. We get access to the files by using C# and send those information to the MVC view, which is actually not possible through a Web-Browser.

You´ll find additional examples in the API demo app. You can try to access an OpenFile dialog so the sample application can read other files as well, if you want to. And maybe there could be a little shortcut to select songs randomly. Just as a little extra 😊 Leave a comment below if managed it.

Here´s the MusicPlayer on GitHub
Here you´ll find the Electron.NET API Demo App on GitHub

How do you like Electron.NET? I´m excited about your feedback in the comments.

Gregor Biswanger

Gregor Biswanger
Gregor Biswanger (Microsoft MVP, Intel Black Belt and Intel Software Innovator) is a freelance lecturer, consultant, trainer, author and speaker. He is a consultant for large and medium-sized companies, organizations and agencies for software architecture, web- and cross-platform development. You can find Gregor often on the road attending or speaking at international conferences.

Interview with webpack founder Tobias Koppers

Webpack is used by millions of developers worldwide. We had the chance to get an exclusive interview with the Author of webpack, Tobias Koppers. Continue reading