Tool Spotlight

Electron.NET: Tray Icon

This post is a continuation of my exploration of Electron.NET which started with this post. Today I’m going to take the existing sample project and expand it to include a tray icon. As with the post on customizing the application level menus, this post relied heavily on the Electon.NET API Demos repo.

Add an Icon

The first step I took was to find an icon I wanted to show in the tray area. Since this is just a sample application I didn’t spend a lot of time on this. Once you have your icon it needs to be added to your project. Following the example, in the API Demo, I add an Assets directory to the top level of the project and copied in my Stock-Person.png file. This directory and file need to end up in the output of the builds which can be done by adding the following to the csproj file.

<ItemGroup>
  <None Update="Assets\Stock-Person.png">
    <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
  </None>
</ItemGroup>

In Visual Studio this can be done via the UI, but since I am sticking to VS Code for this project I did the edit manually.

Tray Controller

Add a TrayController to the Controllers directory which will be used to hold all the code needed to add the tray icon. The following is the full class.

public class TrayController : Controller
{
    public IActionResult Index()
    {
        if (!HybridSupport.IsElectronActive ||
            Electron.Tray.MenuItems.Count != 0)
        {
            return Ok();
        }

        var menu = new MenuItem[] {
            new MenuItem 
        { 
          Label = "Create Contact", 
          Click = () => Electron
                            .WindowManager
                        .BrowserWindows
                .First()
                .LoadURL($"http://localhost:{BridgeSettings.WebPort}/Contacts/Create")
        },
            new MenuItem 
        { 
          Label = "Remove", 
          Click = () => Electron.Tray.Destroy()
            }
        };

        Electron.Tray.Show("/Assets/Stock-Person.png", menu);
        Electron.Tray.SetToolTip("Contact Management");

        return Ok();
    }
}

Most of the code above is dealing with building an array of MenuItem which will be options when right-clicking the tray icon. In this case of this sample, there will be two menu items one for creating a contact and the other to remove the tray icon.

Electron.Tray.Show is the bit that actually shows the tray icon and it takes a path for the icon to display and the menu items to show. The last bit is a call to Electron.Tray.SetToolTip which, not surprisingly, sets the tooltip on the tray icon.

Include the tray icon

The final change is to make sure the code to show the tray icon gets run when the application starts. Open the _Layout.cshtml file in the Views/Shared directory. In the head tag add the following which will cause the application to call the Index action on the TrayController.

<link rel="import" href="Tray">

Wrapping Up

As with everything I have tried so far, Electon.NET makes it easy to add a tray icon to your applications. If you are a .NET developer so far I haven’t found any downsides to using Electron.NET. If you have hit any walls with this tool leave a comment. The finished code for this post can be found here.

Electron.NET: Tray Icon Read More »

Electron.NET: Custom Application Menus

This post will take the existing sample Electron.NET application used in Create a Desktop Application using ASP.NET Core and Electron.NET and Electron.NET with a Web API and expand it to customize the application menu. I leaned heavily on the Electron.NET API Demos repo to guide how this should be done. The code before any changes can be found here.

Menu Controller

While not a requirement I follow the API Demo example of putting the application level menus in its own controller. Add a MenusController to the Controllers directory. The following is the full class.

public class MenusController : Controller
{
    public IActionResult Index()
    {
        if (HybridSupport.IsElectronActive)
        {
            var menu = new MenuItem[] {
            new MenuItem { Label = "Edit", Submenu = new MenuItem[] {
                new MenuItem { Label = "Undo", Accelerator = "CmdOrCtrl+Z", Role = MenuRole.undo },
                new MenuItem { Label = "Redo", Accelerator = "Shift+CmdOrCtrl+Z", Role = MenuRole.redo },
                new MenuItem { Type = MenuType.separator },
                new MenuItem { Label = "Cut", Accelerator = "CmdOrCtrl+X", Role = MenuRole.cut },
                new MenuItem { Label = "Copy", Accelerator = "CmdOrCtrl+C", Role = MenuRole.copy },
                new MenuItem { Label = "Paste", Accelerator = "CmdOrCtrl+V", Role = MenuRole.paste },
                new MenuItem { Label = "Select All", Accelerator = "CmdOrCtrl+A", Role = MenuRole.selectall }
            }
            },
            new MenuItem { Label = "View", Submenu = new MenuItem[] {
                new MenuItem
                {
                    Label = "Reload",
                    Accelerator = "CmdOrCtrl+R",
                    Click = () =>
                    {
                        // on reload, start fresh and close any old
                        // open secondary windows
                        Electron.WindowManager.BrowserWindows.ToList().ForEach(browserWindow => {
                            if(browserWindow.Id != 1)
                            {
                                browserWindow.Close();
                            }
                            else
                            {
                                browserWindow.Reload();
                            }
                        });
                    }
                },
                new MenuItem
                {
                    Label = "Toggle Full Screen",
                    Accelerator = "CmdOrCtrl+F",
                    Click = async () =>
                    {
                        bool isFullScreen = await Electron.WindowManager.BrowserWindows.First().IsFullScreenAsync();
                        Electron.WindowManager.BrowserWindows.First().SetFullScreen(!isFullScreen);
                    }
                },
                new MenuItem
                {
                    Label = "Open Developer Tools",
                    Accelerator = "CmdOrCtrl+I",
                    Click = () => Electron.WindowManager.BrowserWindows.First().WebContents.OpenDevTools()
                },
                new MenuItem
                {
                    Type = MenuType.separator
                },
                new MenuItem
                {
                    Label = "App Menu Demo",
                    Click = async () => {
                        var options = new MessageBoxOptions("This demo is for the Menu section, showing how to create a clickable menu item in the application menu.");
                        options.Type = MessageBoxType.info;
                        options.Title = "Application Menu Demo";
                        await Electron.Dialog.ShowMessageBoxAsync(options);
                    }
                }
            }
            },
            new MenuItem { Label = "Window", Role = MenuRole.window, Submenu = new MenuItem[] {
                 new MenuItem { Label = "Minimize", Accelerator = "CmdOrCtrl+M", Role = MenuRole.minimize },
                 new MenuItem { Label = "Close", Accelerator = "CmdOrCtrl+W", Role = MenuRole.close }
                 }
            },
            new MenuItem { Label = "Contacts", Role = MenuRole.window, Submenu = new MenuItem[] {
                 new MenuItem { Label = "Create", 
                                Accelerator = "Shift+CmdOrCtrl+C",
                                Click = () => Electron.WindowManager.BrowserWindows.First().LoadURL($"http://localhost:{BridgeSettings.WebPort}/Contacts/Create")
                              }
                 }
            }
        };

            Electron.Menu.SetApplicationMenu(menu);
        }

        return Ok();
    }
}

What the above comes down to is building an array of MenuItem types and then using Electron.Menu.SetApplicationMenu(menu) to pass the array to Electron which handles replacing the default set of menus with the ones defined in the array.

For most of the items that were on the default set of menus all that is needed to add back the default functionality is to set the Role to the function you want. For example in the above for a Copy menu item, we can assign Role to MenuRole.copy and Electron will handle the implementation of a copy without us having to write any additional code.

Navigate to a page from the application menu

One thing I wanted to be able to do was from a menu create a new contact. It was easy enough to add a top-level menu for Contacts and a sub-item for Create. It took me a while, but I finally figured out how to build a URL that would work. The following code is the menu items for the Contacts menu.

new MenuItem { Label = "Contacts", Role = MenuRole.window, Submenu = new MenuItem[] {
     new MenuItem { Label = "Create", 
                    Accelerator = "Shift+CmdOrCtrl+C",
                    Click = () => Electron.WindowManager.BrowserWindows.First().LoadURL($"http://localhost:{BridgeSettings.WebPort}/Contacts/Create")
                  }
     }
}

The ASP.NET Core backend is running on localhost, the key that took me a while to locate was the port. In the end, I found that the port being used can be found using BridgeSettings.WebPort.

Include the menu

The final change that is needed is to make sure the new set of menus get rendered. For the sample application open the _Layout.cshtml file in the Views/Shared directory. Inside the head tag add the following line which will force a call to the MenusController when the application loads.

<link rel="import" href="menus">

Wrapping Up

Customizing the application menu ended up being pretty easy. If I hadn’t wanted to navigate to a specific page I would have been done in no time, but hitting the issue with navigation helped me learn more about how Electron.NET is working. You can check out the finished code here.

Electron.NET: Custom Application Menus Read More »

Electron.NET with a Web API

This post will be expanding on the introduction to Electron.NET that I did here to add in a Web API hit to pull some data as well as the UI on the Electron side to use this data. The code before any changes can be found here.

API Creation

To create the API I used the following from the command prompt in the folder where I wanted the new project to be created.

dotnet new webapi

API Data

Now that the API project is created we need to add in the ability to interact with a database with Entity Framework Core. Adding in Entity Framework Core ended up turning into a post of its own when you can read here.

The model and DB Context of the API project match what was in the blog post I linked above, but I am going to include them here. The following is the model.

public class Contact
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string Subregion { get; set; }
    public string PostalCode { get; set; }
    public string Phone { get; set; }
    public string Email { get; set; }
}

Next, is the DB Context, which is empty other than the DB Set for the contacts table.

public class ContactsDbContext : DbContext
{
    public DbSet<Contact> Contacts { get; set; }

    public ContactsDbContext(DbContextOptions<ContactsDbContext> options)
        : base(options)
    {

    }
}

With our model and context setup, we can run the following two commands to add the initial migration and apply the migration to the database.

dotnet ef migrations add Contacts
dotnet ef database update

API Endpoints

The API is just going to handle the basic CRUD (create, read, update, delete) operations for contact. Instead of hand coding the controller we are going to use some code generation provided by Microsoft. First, we need to add the Microsoft.VisualStudio.Web.CodeGeneration.Design NuGet package to the API project using the following command in a command prompt set to the root of the API project.

dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design

Now with the above package installed, we can use the following command to generate a controller with the CRUD operations already implemented.

dotnet aspnet-codegenerator controller -name ContactsController --model Contact --dataContext ContactsDbContext -outDir Controllers -api

There is a lot of switches when using aspnet-codegenerator. The following is a rundown of the ones used above.

  • controller tells the code generator we are creating a controller
  • name defines the name of the resulting controller
  • model is the model class that will be used for the generation
  • dataContext is the DB Context that will be used for the generation
  • outDir is the directory the output will be in relative to the current directory of your command prompt
  • api tells the code generator this controller is for a REST style API and that no views should be generated

With the code generation complete the API should be good to go.

Electron Model

Over in the Electron project, we need a model to match the data the API is returning. This could be the point where a third project is added to allow the API and the Electron app to share common items, but just to keep the example simple I’m just going add a copy of the contact model from the API project to the Electron project.  The following is the full contact model class.

public class Contact
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string Subregion { get; set; }
    public string PostalCode { get; set; }
    public string Phone { get; set; }
    public string Email { get; set; }
}

Electron Views

Now that we have a model in our Electron project we need to create the views that go along with it. Start by adding the code generation package like we did above using the following command.

dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design

Unfortunately, controller generation needs a DBContext to work which our project doesn’t have, so we have to take the long way about to generate our views and then manually create a controller to go with them. In order to get view generation to work, I had to add references to the Entity Framework Core Tools package using the following command.

dotnet add package Microsoft.EntityFrameworkCore.Tools

In the csproj file add the following .NET CLI tool reference.

<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.2" />

Now the project is ready to use the command prompt to generate the views we will need for our CRUD operations related to our contacts. Use the following commands to create the full range of views needed (Create, Edit, List, Delete, Details).

dotnet aspnet-codegenerator view Create Create --model Contact --useDefaultLayout -outDir Views/Contacts

dotnet aspnet-codegenerator view Edit Edit --model Contact --useDefaultLayout -outDir Views/Contacts

dotnet aspnet-codegenerator view Index List --model Contact --useDefaultLayout -outDir Views/Contacts

dotnet aspnet-codegenerator view Delete Delete --model Contact --useDefaultLayout -outDir Views/Contacts

dotnet aspnet-codegenerator view Details Details --model Contact --useDefaultLayout -outDir Views/Contacts

Again there is a lot of switches when using aspnet-codegenerator. The following is a rundown of the ones used above.

  • view  tells the code generator we are creating a view
  • the next two items are the name of the view and the name of the view template
  • model is the model class that will be used for the generation
  • useDefaultLayout uses the default layout (surprise!)
  • outDir is the directory the output will be in relative to the current directory of your command prompt

The Index.cshtml generated above comes with links for Edit, Details, and Delete that won’t work as generated. Open the file and make the following changes to pass the key of the contact trying to be opened.

Before:
@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new {/* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })

After:
@Html.ActionLink("Edit", "Edit", new {  id=item.Id }) |
@Html.ActionLink("Details", "Details", new { id=item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id=item.Id })

Electron Controller

With the views complete let’s add a ContactsController.cs to the Controllers directory. The code for the controller follows, but I’m not going to go into the details. I took a controller from another contact base project and just replaces all the Entity Framework stuff with calls to the API we created above. Please don’t use this as an example of how something like this should be done it is just quick and dirty to show that it can work.

public class ContactsController : Controller
{
    private string _apiBaseUrl = "http://localhost:5000/api/contacts/";

    // GET: Contacts
    public async Task<IActionResult> Index()
    {
        using (var client = new HttpClient { BaseAddress = new Uri(_apiBaseUrl) })
        {
            return View(JsonConvert.DeserializeObject<List<Contact>>(await (await client.GetAsync("")).Content.ReadAsStringAsync()));
        }
    }

    // GET: Contacts/Details/5
    public async Task<IActionResult> Details(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        using (var client = new HttpClient { BaseAddress = new Uri(_apiBaseUrl) })
        {
            var contact = JsonConvert.DeserializeObject<Contact>(await (await client.GetAsync(id.ToString())).Content.ReadAsStringAsync());

            if (contact == null)
            {
                return NotFound();
            }

            return View(contact);
        }
    }

    // GET: Contacts/Create
    public IActionResult Create()
    {
        return View();
    }

    // POST: Contacts/Create
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("Id,Address,City,Email,Name,Phone,PostalCode,State")] Contact contact)
    {
        if (ModelState.IsValid)
        {
            using (var client = new HttpClient { BaseAddress = new Uri(_apiBaseUrl) })
            {
                await client.PostAsync("", new StringContent(JsonConvert.SerializeObject(contact), Encoding.UTF8, "application/json"));
            }

            return RedirectToAction("Index");
        }
        return View(contact);
    }

    // GET: Contacts/Edit/5
    public async Task<IActionResult> Edit(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        using (var client = new HttpClient { BaseAddress = new Uri(_apiBaseUrl) })
        {
            var contact = JsonConvert.DeserializeObject<Contact>(await (await client.GetAsync(id.ToString())).Content.ReadAsStringAsync());

            if (contact == null)
            {
                return NotFound();
            }

            return View(contact);
        }
    }

    // POST: Contacts/Edit/5
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(int id, [Bind("Id,Address,City,Email,Name,Phone,PostalCode,State")] Contact contact)
    {
        if (id != contact.Id)
        {
            return NotFound();
        }

        if (ModelState.IsValid)
        {
            using (var client = new HttpClient { BaseAddress = new Uri(_apiBaseUrl) })
            {
                await client.PutAsync(id.ToString(), new StringContent(JsonConvert.SerializeObject(contact), Encoding.UTF8, "application/json"));
            }
            return RedirectToAction("Index");
        }
        return View(contact);
    }

    // GET: Contacts/Delete/5
    public async Task<IActionResult> Delete(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        using (var client = new HttpClient { BaseAddress = new Uri(_apiBaseUrl) })
        {
            var contact = JsonConvert.DeserializeObject<Contact>(await (await client.GetAsync(id.ToString())).Content.ReadAsStringAsync());

            if (contact == null)
            {
                return NotFound();
            }

            return View(contact);
        }

    }

    // POST: Contacts/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> DeleteConfirmed(int id)
    {
        using (var client = new HttpClient { BaseAddress = new Uri(_apiBaseUrl) })
        {
            await client.DeleteAsync(id.ToString());
            return RedirectToAction("Index");
        }
    }

    private async Task<bool> ContactExists(int id)
    {
        using (var client = new HttpClient { BaseAddress = new Uri(_apiBaseUrl) })
        {
            return JsonConvert.DeserializeObject<Contact>(await (await client.GetAsync("id")).Content.ReadAsStringAsync()) != null;
        }
    }
}

Electron Add Link To Navigation

The final step to add a link to the list of contacts to the navigation bar of the application. Open the _Layout.cshtml and in the unordered list for the nav bar add the following line.

<li><a asp-area="" asp-controller="Contacts" asp-action="Index">Contacts</a></li>

Wrapping Up

That is all the changes to get the application up and running. If you run the API and then use dotnet electronize start from a command prompt in the ElectronTest project root all should be good to go.

The completed code can be found here.

Electron.NET with a Web API Read More »

Run Multiple Projects in Visual Studio Code

While expanding the sample used in the Electron.NET post to include an API I hit a snag with Visual Studio Code. I have used multiple projects with Visual Studio Code before, but never two distinct applications that I need to run at the same time.  Sample code that contains the two projects, but before any modifications covered in this post can be found here.

Building Multiple Projects

The first issue to tackle was getting both projects to build since they are technically independent. As I’m sure you are aware VS Code doesn’t need a solution file like full Visual Studio does. What I learned during this process was that while a solution file isn’t required once can be used to ensure multiple projects all get built. Using VS Code’s Terminal I ran the following commands to create a new solution and add my two projects to that solution.

dotnet new sln -n ElectronTest
dotnet sln add src/ElectronTest/ElectronTest.csproj
dotnet sln add src/ContactsApi/ContactsApi.csproj

With the solution file in place, I then opened the tasks.json file found in the .vscode directory. In the build task, I removed the path to a specific csproj file and just used the workspace folder.

Before:
"label": "build",
"command": "dotnet",
"type": "process",
"args": [
    "build",
    "${workspaceFolder}/src/ElectronTest/ElectronTest.csproj"
]

After:
"label": "build",
"command": "dotnet",
"type": "process",
"args": [
    "build",
    "${workspaceFolder}"
]

This is just one option on how to handle the builds. I believe another way would be to have two build tasks (one for each project) and use the individual build task in your launch configurations (which we are going to talk about next).

Debugging Multiple Projects

Open up your launch.json file in the .vscode directory. By default you will see a couple of configurations more than likely you will see one named .NET Core Attach and another named .NET Core Launch (web). It is the .NET Core Launch (web) configuration that we are interested in. This configuration controls how our application is launched. If you notice the program property points to the dll created during the build process, in the sample code this is  ${workspaceFolder}/src/ElectronTest/bin/Debug/netcoreapp2.0/ElectronTest.dll. This is all fine but doesn’t give us a way to run both of our projects. Let’s tweak the env property to set the ASPNETCORE_URLS which will control the URL the application is launched with.

Before:
"env": {
    "ASPNETCORE_ENVIRONMENT": "Development"
}

After:
"env": {
    "ASPNETCORE_ENVIRONMENT": "Development",
    "ASPNETCORE_URLS": "http://localhost:5001"
}

Now that the original application’s launch configuration is set we need to add a second launch configuration for our second application. The following is the full configuration section for my second application (the API).

{
    "name": ".NET Core Launch (API)",
    "type": "coreclr",
    "request": "launch",
    "preLaunchTask": "build",
    "program": "${workspaceRoot}/src/ContactsApi/bin/Debug/netcoreapp2.0/ContactsApi.dll",
    "args": [],
    "cwd": "${workspaceRoot}/src/ContactsApi",
    "stopAtEntry": false,
    "launchBrowser": {
        "enabled": false,
        "args": "${auto-detect-url}",
        "windows": {
            "command": "cmd.exe",
            "args": "/C start ${auto-detect-url}"
        },
        "osx": {
            "command": "open"
        },
        "linux": {
            "command": "xdg-open"
        }
    },
    "env": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "ASPNETCORE_URLS": "http://localhost:5000"
    },
    "sourceFileMap": {
        "/Views": "${workspaceRoot}/Views"
    }
}

I started with a copy of the original application and just modified a couple of things. First, the name property is now .NET Core Launch (API) which will help us know which application we are launching later. In the launchBrowser section, I set enabled to false since this is an API and I don’t need to launch the browser when the application starts. The final difference is in ASPNETCORE_URLS to make sure the URLs of the two applications are different. I used http://localhost:5000 in this example.

Now that all our configurations are good to go hop over to the debug section in VS Code.

On the debug you will notice that both of our launch configurations are listed. If you select the API one and hit the green play button it will start the API. With the API running you can then select the web configuration and hit the green play button and you will have both of your applications running in debug mode.

Wrapping Up

While it is not obvious at all how to get multiple applications to run in a single instance of VS Code the process isn’t hard after you do it the first time. I think my Visual Studio experience made figuring this out harder than it should have been. My key to learning how to get this going was on this GitHub issue.

Hopefully, this saved you some of the struggles I went through. Please leave a comment if there are different ways to accomplish this. The code with the final configuration can be found here.

Run Multiple Projects in Visual Studio Code Read More »

Create a Desktop Application using ASP.NET Core and Electron.NET

Electron is a cross-platform (Windows, Linux, and Mac) library for building desktop applications using JavaScript, HTML, and CSS. Even if you have never head of Electron I’m sure you have used some of the desktop applications it has been used to build such as Visual Studio Code, Atom, Slack.

Electron.NET provides a wrapper around Electron with an ASP.NET Core MVC application in the mix. Here is the reason why this was done from the creates of the project.

Well… there are lots of different approaches how to get a X-plat desktop app running. We thought it would be nice for .NET devs to use the ASP.NET Core environment and just embed it inside a pretty robust X-plat enviroment called Electron. Porting Electron to .NET is not a goal of this project, at least we don’t have any clue how to do it. We just combine ASP.NET Core & Electron.

Project Creation

Seems only fitting to use VS Code for this post since it is built using the same base library. From the command line create a new ASP.NET Core MVC application using the following command.

dotnet new mvc

Make note that it is important at this time that you use the MVC template when attempting this and not a Razor Page application. This is more of a warning if you are using Visual Studio to do your project creation and not the CLI command above.

Next, we need to reference the ElectronNET.API NuGet package which can be added using the following command.

dotnet add package ElectronNet.API

Then, open the csproj and add a reference for the Electron.NET CLI tool which should match the following.

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

After that make sure and restore packages using the following command.

dotnet restore

Wire-up Election.NET

Open Program.cs and add UseElectron(args) to the WebHost builder chain.

WebHost.CreateDefaultBuilder(args)
    .UseElectron(args)
    .UseStartup<Startup>()
    .Build();

Net, open Startup.cs and add the following line to the bottom of the Configure function. This is what will open the Electron window on startup.

Task.Run(async () => await Electron.WindowManager.CreateWindowAsync());

Finally, run the following from the command prompt to get the project ready to run under Electron. This should only need to be done once.

dotnet electronize init

Run the application

At this point, the application is ready to go. The neat part is you can just hit F5 and it will run like any normal ASP.NET Core application (this would change when you get into Electron specific calls I’m sure) or if you run the following command it will run inside of the Electron shell.

dotnet electronize start

Wrapping up

It was surprisingly simple to get a new application up and running, of course so far the app isn’t anything other than a web site hosted in Electron. My plan is to take this base application and create my normal basic contacts application, which will be the next post. From there I may look into layering in some Electron features.

The completed code can be found here.

Create a Desktop Application using ASP.NET Core and Electron.NET Read More »

Refit Basics

A few weeks ago I was watching this episode of the ASP.NET Community Standup and they had Ryan Nowak on to talk about the new HttpClientFactory coming in the 2.1 release and a question came up about compatibility with Refit. I had been meaning to check out Refit but had honestly forgotten about it. This post is going to be a very basic introduction to Refit.

What is it?

In the author’s (Paul Betts) words, Refit is the automatic type-safe REST library for .NET Core, Xamarin and .NET. Cool, but what does that mean? Basically, Refit allows you to define an interface for an API that your application wants to call and using that is hides way all the HTTP and JSON serialization/deserialization bits.

Sample project creation

To test Refit out I created a very simple .NET Core console application. To do the same open a command prompt in the directory you want the project using the following command.

dotnet new console

For this project, I am using Visual Studio Code as my editor. Since VS Code doesn’t have a NuGet UI build in (maybe there is an extension?) I used the following command to add Refit to the project.

dotnet add package Refit

Or if you prefer you can add the following to your csproj file.

<ItemGroup>
  <PackageReference Include="Refit" Version="4.3.0" />
</ItemGroup>

The API

Instead of creating an API I searched the internet for a free one I could use. I ended up using CountryAPI. The following is a sample of what a response from the API looks like.

{  
   "IsSuccess":true,
   "UserMessage":null,
   "TechnicalMessage":null,
   "TotalCount":1,
   "Response":[  
      {  
         "Name":"Afghanistan",
         "Alpha2Code":"AF",
         "Alpha3Code":"AFG",
         "NativeName":"افغانستان",
         "Region":"Asia",
         "SubRegion":"Southern Asia",
         "Latitude":"33",
         "Longitude":"65",
         "Area":652230,
         "NumericCode":4,
         "NativeLanguage":"pus",
         "CurrencyCode":"AFN",
         "CurrencyName":"Afghan afghani",
         "CurrencySymbol":"؋",
         "Flag":"https://api.backendless.com/2F26DFBF-433C-51CC-FF56-830CEA93BF00/473FB5A9-D20E-8D3E-FF01-E93D9D780A00/files/CountryFlags/afg.svg",
         "FlagPng":"https://api.backendless.com/2F26DFBF-433C-51CC-FF56-830CEA93BF00/473FB5A9-D20E-8D3E-FF01-E93D9D780A00/files/CountryFlagsPng/afg.png"
      }]
}

Classes

Now that we know what the API response looks like classes can be created to match its structure. In this case, I have two classes one for response and one for the actual country data.

public class ApiResponse<T>
{
    public bool IsSuccess {get; set;}
    public string UserMessage {get; set;}
    public string TechnicalMessage {get; set;}
    public int TotalCount {get; set;}
    public List<T> Response {get; set;}
}

public class Country
{
    public string Name { get; set; }
    public string Alpha2Code { get; set; }
    public string Alpha3Code { get; set; }
    public string NativeName { get; set; }
    public string Region { get; set; }
    public string SubRegion { get; set; }
}

API Interface for Refit

With the classes for the response setup, we can now define the interface that will be used by Refit when calling the API. The following interface defines a function to get all countries and another function that gets countries that speak a specific native language.

public interface ICountryApi
{
    [Get("/v1/Country/getCountries")]
    Task<ApiResponse<Country>> GetCountries();
    
    [Get("/v1/Country/getCountries")]
    Task<ApiResponse<Country>> GetCountriesByLanguage([AliasAs("pNativeLanguage")]string language);
}

The attributes on the functions are part of the magic of Refit. In the cases above both of the calls are HTTP Get requests which is why they are using the Get attribute. Refit does support other verbs as well.

The other thing of note here is the AliasAs on the parameter of the second function call. This attribute can be used to control what gets put in the query string and keeps cryptic names from the API from spreading to other places in your code.

Calling the API

The following is the full code from my Program class that shows the usage of Refit with both of the API calls defined above.

public static async Task Main(string[] args)
{
    var api = RestService.For<ICountryApi>(" http://countryapi.gear.host");
    
    var countries = await api.GetCountries();
    OutputCountires(countries.Response);

    Console.WriteLine("Enter a language to filter by:");    
    var language = Console.ReadLine();
    var filteredCountries = await api.GetCountriesByLanguage(language);
    OutputCountires(filteredCountries.Response);

    Console.ReadLine();
}

private static void OutputCountires(List<Country> countries)
{
   countries.ForEach(c => Console.WriteLine($"{c.Name} - {c.Region} - {c.SubRegion}"));
}

The following line is defining a call to a rest API for a specific interface.

var api = RestService.For<ICountryApi>(" http://countryapi.gear.host");

Now that we have a reference to the API it can be called asynchronously to get the data from the API.

var countries = await api.GetCountries();

The rest of the app is more of the same just using the other API call.

Gotchas

In order to use async Task Main a change is needed to the project file to set the LangVersion. I just set it to latest, but I believe the minimum for this feature is 7.1.

<PropertyGroup>
  <OutputType>Exe</OutputType>
  <TargetFramework>netcoreapp2.0</TargetFramework>
  <LangVersion>latest</LangVersion>
</PropertyGroup>

If you are using VS Code and are using Console.ReadLine() like I am above then a change will be needed for the launch.json file found in the .vscode directory. Look for the console property and set the value to either integratedTerminal or externalTerminal otherwise, the app will be connected to the debug console which will show the output of the application, but doesn’t allow for input.

Wrapping up

Using Refit to makes using APIs super simple. There is a level of magic that I would like to dig into more. I would also like to see how it handles issues and what sort of hooks are provided to address those issue. Based on the Github page Paul has addressed a wide range of the challenges faced with dealing with an API.

As part of writing this posts, I came across two other posts on Refit that might be helpful, one by Jerrie Pelser and the other from Scott Hanselman.

 

Refit Basics Read More »

Change ASP.NET Core from npm to Yarn

Over the past couple of months, I have been having some issues with npm. Between the upgrading of npm Windows begin a pain and a version incompatibility with node I have just gotten frustrated with it. This post is going to cover the steps to use Yarn as a replacement for npm in an ASP.NET Core application.

Installation

The first step is to get Yarn installed. Head over to this site and download and run the installer for your operating system.

For Visual Studio, Mads Kristensen created an extension for Yarn that makes the integration much better. The installer for the extension can be downloaded from here.

Conversion

Open a command prompt in the same directory as your project’s package.json file and run the following command.

yarn

This will create a yarn.lock and lay out the node_modules folder using Yarn’s resolution algorithm.

I did hit the following error when I did the yarn command. I left out the specific file that it had an issue with because I am sure yours would be different.

Error: EPERM: operation not permitted, copyfile...

To clear the issue I just deleted the node_modules directory and let Yarn recreate it. It might also work to use a command prompt with administrator privileges.

Visual Studio

With the Yarn extension installed there are a couple of settings that are helpful to change. All the setting we will be changing can be found under the Tools > Options menu. The first is to have yarn install run when the package.json is saved. Look under Web > Yarn Installer for this option.

The second setting is to turn off automatic NPM restore so packages are restored twice. This requires the options under NPM to be set to false. The options can be found in Projects and Solutions > Web Package Management > Package Restore.

The extension helps with Yarn integration, but the integration still isn’t as full-featured as using NPM. At my current level of frustration having to manually restore package when I open a project on a new PC is totally worth it.

Wrapping Up

So far Yarn has been great and I have not hit any issues, but my usage has also been limited. It seems like a solid alternative to NPM.

Make sure and check out Yarn’s official post on migrating from NPM which can be found here. Of specific interest will be the CLI command comparison which can be found here.

Change ASP.NET Core from npm to Yarn Read More »

Swagger and Swashbuckle: Disable Try It Out

In last week’s post, I walked through adding Swagger support to an ASP.NET Core 2 API using the Swashbuckle. One of the awesome things about Swashbuckle is it provides an integration with swagger-ui.

Try it out!

One of the features of the UI integration is the ability to invoke an end point using the “Try it out!” button. This feature is awesome during development but may not be something you want to allow, depending on the use case, for a production end point.

Disable Try it out!

I tried googling lots of different things to find the option to disable the “Try it out” button and had a really hard time finding an answer. It didn’t help that I want the button text to be “Try it now” for some reason. Thankfully it truly was a failure on my part and there is a provided way to disable “Try it out” and it is much more flex able than what I was initially looking for.

In the Configure function of the Startup class find the call to app.UseSwaggerUI. Adding c.SupportedSubmitMethods(new string[] {}); will completely disable “Try it out”. The following is the full call to app.UseSwaggerUI just to provide context.

app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "Contacts API V1");
    c.SupportedSubmitMethods(new string[] {});
});

The great thing about the way this is set up if you can allow some actions and not others. For example, say you wanted to allow get actions but disable the rest. The following would allow for that.

c.SupportedSubmitMethods(new [] {"get"});

One word of caution the above is case sensitive and if you use Get instead of get “Try it out” will remain disabled.

Swagger and Swashbuckle: Disable Try It Out Read More »

Swagger and Swashbuckle with ASP.NET Core 2

This post is going to be very similar to a post from last December which can be found here. A lot has changed since then and this post is going to add Swagger to an existing ASP.NET Core application using Swashbuckle much like the one from last year. The starting point of the code can be found here.

What is Swagger?

Swagger is a specification used to document an API. As I am sure we all know API documentation tends to get out of date fast and a lot of times is a low priority.  Swagger aims to help solve that problem using a format that is both human and machine readable which can be maintained in either JSON or YAML. The documentation can be auto generated using a tool like Swashbuckle which provides away to keep your consumers up to date. Check out this post by the Swagger team for the full introduction.

What is Swashbuckle?

Swashbuckle provides auto generation of Swagger 2.0, a UI, etc. The project takes all the pain out of getting going with Swagger as well as providing tools and hooks for using and customizing Swagger related items. The full description can be found here.

Adding Swashbuckle

Using your favorite method of NuGet interaction, add the Swashbuckle.AspNetCore NuGet package to your project. Personally, I have gotten where I edit the csproj file to add new packages. If that is your style you would need to add the following package reference.

<PackageReference Include="Swashbuckle.AspNetCore" Version="1.0.0" />

This one package provides all the functionality we will need.

Wiring up Swashbuckle

Now that the Swashbuckle package is installed, there are a few changes that are needed in the Startup class to get everything wired up. First, in the ConfigureServices function, the Swagger generator needs to be added to DI.

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new Info { Title = "Contacts API", Version = "v1"});
});

AddSwaggerGen allows for configuration of options, but here we are just setting a name and a minimal amount of information.

In the Configure function Swagger needs to be added to the request pipeline in order to expose the Swagger generated data. I placed this after UseMvc.

app.UseSwagger();

At this point, the Swagger generated JSON would be available at {yourBaseUrl}/swagger/v1/swagger.json. To take a step further let’s expose the UI that comes with Swashbuckle. Add the following just below app.UseSwagger().

app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "Contacts API V1");
});

Now a UI based on your API is available at {yourBaseUrl}/swagger with zero extra work on your part. The following is the UI for the post contact route in the example project.

As you can see the UI provides a great view of your API as well as ways to try it out and the potential responses that should be expected from a call.

Controller Considerations

All of this wonderful functionality doesn’t come for free of course. In order for Swashbuckle to pick up your routes, your controller will need to use attribute based routing instead of depending on convention based routing.

In order for Swashbuckle to know the return types and of your controller actions may need to have some attributes added. This won’t be required if your action return a specific type, but if you are returning an IActionResult you should attribute your action with all the ProducesResponseType you need to cover the results of your action. For example, the following is the action definition for the Post in the screen shot above.

[HttpPost]
[ProducesResponseType(typeof(Contact), 200)]
[ProducesResponseType(typeof(IDictionary<string, string>), 400)]
[ProducesResponseType(typeof(void), 400)]
[ProducesResponseType(typeof(void), 404)]
[ProducesResponseType(typeof(void), 409)]
public async Task<IActionResult> PostContact([FromBody] Contact contact)

Wrapping up

Swashbuckle makes it easy to add Swagger to a project. I feel that it also provides a huge value for anyone trying to consume an API. It is of course not a magic bullet and communication with your API consumers about API changes will still be critical.

Microsoft’s docs have a great walk through which can be found here. It does more in-depth on customizing your setup and as far as modifying the look of the UI. I also recommend checking out the GitHub page for the project which can be found here.

The finished code can be found here.

Swagger and Swashbuckle with ASP.NET Core 2 Read More »

NDepend Spotlight

Today I am going to be doing a tool spotlight on NDepend. NDepend has a ton of features to help you keep a handle on your applications including the following plus much more.

  • Code Rules
    • 200 default rules with ability to add custom rules using LINQ
  • Quality Gates
  • Visual Studio Integration
  • Build Process Integration
  • Dependency Graph
  • Dependency Matrix
  • Technical Debit Estimation

For full disclosure, NDepend reached out to me to give their tool a try. I am writing based on my experiences with their tool and will be including both the positive and negative aspects of my experience. None of the links in this post are referrals that would in any way provide me any sort of payment.

Installation

The download is a zip file that you then have to find out what you want to do with. This was the first negative I hit with the product. While it isn’t hard to figure out it would be much nicer if this were an installer where I could select what I wanted to install instead of having to look at the getting started docs right away. For non-build usage, the options to run the tool is either via a Visual Studio extension (NDepend.VisualStudioExtension.Installer) or as a stand alone application (VisualNDepend.exe).

I chose to go explore with the Visual Studio extension. As a hint that I didn’t notice until later, VisualNDepend provides an option to install the Visual Studio extension in addition to providing all the functionality of the Visual Studio extension.

Visual Studio Extention

After installing the NDepend extension there will be a new top level NDepend menu in Visual Studio.

With the solution you want to analyze already open select the NDepend > Attach New NDepend Project to Current VS Solution.

This will launch a dialog that allows you to select which assemblies you would like to analyze preloaded with the assemblies for the current application.

As you can see from the dialog there are a lot of options. If your project has other assemblies or solutions that you would like to be included as part of the analyses they are easy to add. When finished adding items to analyze click the Analyze button at the bottom. I am using a small project for this entry and the process took less than 10 seconds. I also tried it on a large project (500k+ lines of code) and it took less than 30 seconds.

After the analyses are complete the extension shows a dialog asking what to do next as well as launching a web page with the results of the analyses if you kept the Build Report check box checked. Following are the options in the dialog.

From here I chose to View NDepend Dashboard, but also make sure and check out the report that the analyses generated as it provides a great summary at the end of all the issues found. The following is a part of the dashboard.

There is a ton of data provided. If you notice at the top there is a Choose Baseline option which would allow comparisons of solutions over time. I can see this view of a project over time is very helpful, but not a feature I will get to explore here.

Exploration

Exploration of the data NDepend provides is something I could spend hours looking at even on a small project. For example, the following is an output to HTML (their output is much prettier than the version that is shown here) of the issues that make up the critical group in the Rules box in the dashboard above.

4 rules Issues Debt Annual Interest Breaking Point Category Full Name
Avoid methods with too many parameters 1 issue 1h 9min 5min 4 522d Project Rules \ Code Smells Rule
Avoid non-readonly static fields 12 issues 32min 4h 0min 48d Project Rules \ Immutability Rule
Avoid namespaces mutually dependent 2 issues 30min 1h 1min 179d Project Rules \ Architecture Rule
Avoid having different types with same name 3 issues 30min 1h 0min 182d Project Rules \ Naming Conventions Rule
Sum: 18 2h 41min 6h 6min 4 933d
Average: 4.5 40min 1h 31min 1 233d
Minimum: 1 30min 5min 48d
Maximum: 12 1h 9min 4h 0min 4 522d
Standard deviation: 4.39 16min 1h 28min 1 899d
Variance: 19.25 34d 979d overflow

Here is the same view inside the Queries and Rules Edit window.

Double click any line will take you to a detail view showing a listing of the rule broken down by project, namespace, and class.

The same window also shows the query that was used to find the rule violations. For example, the above is powered by the following query.

warnif count > 0
from f in Application.Fields
where f.IsStatic && 
     !f.IsEnumValue && 
     !f.IsGeneratedByCompiler &&
     !f.IsLiteral &&
     !f.IsInitOnly

let methodAssigningField = f.MethodsAssigningMe

select new { 
   f, 
   methodAssigningField,
   Debt = (2+8*methodAssigningField.Count()).ToMinutes().ToDebt(),
   Severity = Severity.High
}

The above is CQLinq or Code Query LINQ which is used to query the code model that the NDepend analysis creates. The detail of CQLinq are outside the scope of this post, but based on the above you can see how powerfully this could be.

Other considerations

Based on my usage to get the best value from NDepend your whole team would need to be licensed and making sure new code satisfies with all the rules your team wishes to follow. NDepend has a component that can be used as part of server based build processes which is needed, but I would want to use that component as a fail safe, not as a way to avoid buying licenses. If you use multiple computers it seems that you will need multiple licenses which will cause issues for some users.

Wrapping up

After trying NDepend out for awhile I am still amazed at the amount of data it provides. Not to mention the ability to add new queries and rules of your own. One blog post is never going to be enough to cover even a fraction of what this tool does. It feels like Resharper in it does so much that it takes a lot of time to learn and take advantage of the full set of features it provides.

NDepend Spotlight Read More »