Skip to contentSkip to author details

.NET

A 11-post collection

Running a .NET Core 2.0 WebApi app on the Raspberry Pi (Raspbian)

Written by Michael Earls
 .NET Core  .NET  WebAPI  raspberry pi  programming

I wanted to create a web api app that answered calls on my Raspberry Pi. The first step I learned was how to install and configure .NET core 2.0 on the Raspberry Pi.

Note - .NET Core only runs on the Raspberry Pi 2 or 3. It will not run on the Raspberry Pi Zero or Zero W.

To get this working, I followed these great instructions from Jeremy Lindsay:

Running a .NET Core 2 app on Raspbian Jessie, and deploying to the Pi with Cake

Once I had this template installed, I simply created a new .NET Core web api app:

Note - Make sure you install the .NET core 2.0 SDK before attempting any of this. .NET Downloads

dotnet new webapi -n WebApiApp

I added the following line of code to the Program.cs file. This will ensure that the Pi answers to all host names (so I can access it from other computers other than localhost).

WebHost.CreateDefaultBuilder(args)  
    .UseStartup()
    .UseUrls("http://*:5000") // add this line
    .Build();

I then copied the following files and folders from the directory created in the sample from the article above to my new WebApiApp folder:

  • build.cake
  • tools
  • publish

I opened up build.cake and changed the correct app name to the name of the project. Here are my configuration settings:

///////////////////////////////////////////////////////////////////////  
// ARGUMENTS (WITH DEFAULT PARAMETERS FOR LINUX (Ubuntu 16.04, Raspbian Jessie, etc)
///////////////////////////////////////////////////////////////////////
var runtime = Argument("runtime", "linux-arm");  
var destinationIp = Argument("destinationPi", "192.168.1.113");  
var destinationDirectory = Argument("destinationDirectory", @"/home/pi/DotNetConsoleApps/WebApiApp");  
var username = Argument("username", "pi");  
var sessionname = Argument("sessionname", "Raspberry Pi");  
var executableName = Argument("executableName", "WebApiApp");

I ensured that the /home/pi/DotNetConsoleApps/WebApiApp directory existed on the Raspberry Pi and then ran the build script from the Powershell terminal:

../build

This used cake to clean, build, and deploy my web api app onto my Raspberry Pi.

Once this was complete, I switched to my PuTTY terminal and typed in ./WebApiApp to start the Web Api app. It started listening on port 5000. I was able to access the Web Api from a browser on my PC by using the IP address of the Raspberry Pi:

http://192.168.1.113:5000/api/values

This displayed the default project api controller output of the template app created in the earlier step.

I can't believe how easy this was. .NET core is really improving the development workflow immensely over previous versions of .NET. This was so much better than what came before.

Update: I was able to get an LED wired up to the WebApi by using this great article from Carlos Mendible:

Toggle Raspberry Pi GPIO Pins with ASP.NET Core 2.0

I wired the LED to physical pin 11 on the Pi. Here's my controller (not much different from his sample):

using System.Collections.Generic;  
using Microsoft.AspNetCore.Mvc;  
using Unosquare.RaspberryIO;  
using Unosquare.RaspberryIO.Gpio;

namespace WebApi.Controllers  
{
    [Route("api/[controller]")]
    public class GpioController : Controller
    {
        // GET api/values
        [HttpGet]
        public IEnumerable Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        [HttpGet("{value}")]
        public string Get(bool value)
        {
            var pin = Pi.Gpio.Pin00;
            pin.PinMode = GpioPinDriveMode.Output;
            pin.Write(value);
            return $"pin {pin.BcmPinNumber} set to {value}";
        }
    }
}

Raspberry Pi with LED wired to WebApi (not pictured) The state of the LED after sending a true to the gpio api method.

Better property names using the DataMember attribute

Written by Michael Earls
 development  json  C#  .NET  serialization

In my previous post, I demonstrated creating a class to serialize the data returned from the Lipsum.com JSON feed. I wasn't happy with the final result as it used JavaScript formatting for the property names (camel cased).

I prefer Pascal casing on my object properties in C#, so I wanted to quickly show how to change the name of the property on the class.

Here is the new LoremIpsum class definition:

public class LoremIpsum
{
    public Feed Feed { get; set; }
}

[DataContract]
public class Feed
{
    [DataMember(Name ="lipsum")]
    public string Lipsum { get; set; }

    [DataMember(Name = "generated")]
    public string Generated { get; set; }

    [DataMember(Name = "donatelink")]
    public string DonateLink { get; set; }

    [DataMember(Name = "creditlink")]
    public string CreditLink { get; set; }

    [DataMember(Name = "creditname")]
    public string CreditName { get; set; }
}

You'll first need to add a reference to System.Runtime.Serialization to your project. Then, include the System.Runtime.Serialization namespace in your using declarations.

The main() method now looks like this:

static void Main(string[] args)
{
    for (int i = 0; i < 10; i++)
    {
        // toggle between words and paragraphs
        bool isEven = (i % 2).Equals(0); // used this because markdown had trouble with double equal signs
        bool isThird = (i % 3).Equals(0);
        LipsumType lipsumType = isEven ? LipsumType.Paragraphs : LipsumType.Words;

        // only start with Lorem Ipsum every third call
        Debug.WriteLine(LoremIpsumUtil.GetNewLipsum(lipsumType, 7, isThird).Feed.Lipsum + Environment.NewLine);

        // sleep for 1 second to give the server a rest
        Thread.Sleep(1000);
    }
}

The main difference is that now, we use LoremIpsumUtil.GetNewLipsum(lipsumType, 7, isThird).Feed.Lipsum.

As you can see, our properties are now Pascal cased, so they look more in line with what you'll see throughout the other .NET libraries.

My presentation was accepted for the Atlanta Code Camp in October

Written by Michael Earls
 .NET  atlanta  Azure  Code Camp  pebble

I will be speaking at the 2015 Atlanta Code Camp on Saturday, October 24th.

Developing Apps for the Pebble Smartwatch using Windows Azure

You can get more information about the code camp and register on the Code Camp Website.

It’s been awhile since I’ve been involved in the Atlanta .NET community. I think my last presentation was in 2004 or 2005. It has taken awhile, but I’m starting to get back in the game.

I’ve been working with Bruce Thomas, Satya Cherukumilli, and Doug Huff to get the Montgomery, AL .NET user group back up and running. We had our first meeting last week and it went very well. We had 44 developers show up for the first meeting – and we didn’t even advertise that food would be provided until after the meeting had already started.

Decorating an enum with the Description attribute for later use in C# with .NET

Written by Michael Earls
 .NET  C#

I had the need today to set a string value based on the value of an enum. Rather than creating the following code:

Edit: I added a generic method that works on all enums

string myString = null;  
switch(myEnum)  
{
    case myEnum.Value1: 
        myString = "value 1"; 
        break; 
    case myEnum.Value2: 
        myString = "value 2"; 
        break; 
    case myEnum.Value3: 
        myString = "value 3"; 
        break; 
}

I wanted to do something simpler. So, I decided to add the System.ComponentModel.Description attribute to my enum, like so:

using System.ComponentModel; 

public enum MyEnum  
{ 
    [Description("value 1")] 
    Value1, 
    [Description("value 2")]
    Value2, 
    [Description("value 3")]
    Value3
}

Then, to make it easy to use, I added an extension method to all enums:

public static string GetDescription<T>(this T e) where T : IConvertible  
{
    string description = null;

    if (e is Enum)
    {
        Type type = e.GetType();
        Array values = System.Enum.GetValues(type);

        foreach (int val in values)
        {
            if (val == e.ToInt32(CultureInfo.InvariantCulture))
            {
                var memInfo = type.GetMember(type.GetEnumName(val));
                var descriptionAttributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
                if(descriptionAttributes.Length > 0)
                {
                    // we're only getting the first description we find
                    // others will be ignored
                    description = ((DescriptionAttribute)descriptionAttributes[0]).Description;
                }

                break;
            }
        }
    }

    return description;
}

This will allow you to easily get the description of the current enum value. Here is how you would do that:

string description = null;  
MyEnum testEnum = MyEnum.Value2;  
description = testEnum.GetDescription(); // description will be "value 2"

As you can see, it’s pretty easy to decorate your enum values with string descriptions. This allows you to have a central location to set the value.

I can even see a custom description attribute class that retrieves the description from a database. The use cases are there.

Another, more common use case for this method is to localize the values returned by using resource files representing the languages you want to display. You could have one for en-US, en-GB, es-ES, es-MX, etc, using the description Name as the key to the resource file.

Upgrading ASP.NET Identity in NuGet

Written by Michael Earls
 .NET  Code-First  EntityFramework  Identity

This morning, when I went to upgrade the Identity system in my MVC application from NuGet, I ran into issues. When I ran the application that attempted to access roles, I got an error that the model backing the dbContext had changed and that I needed to run a code first migration.

I have very little experience with code-first EntityFramework as I have always used database-first. I just find it easier to set up my database with all the foreign keys and then create my data model from that. I haven’t yet learned the benefits of code-first.

So, to continue, I found the following two resources on the web that pointed me in the right direction:

Upgrading from EntityFramework Identity 1.0 to 2.0

and

Automatic Code-First Migrations

Within those articles, I found the following package manager console commands that helped me:

Enable-Migrations –EnableAutomaticMigrations Add-Migration Nuget-Update-ASPNet-Identity

Since I had two contexts, it gave me a message that I needed to choose one or the other and even told me the exact command to use to do it. I just copied and pasted the command in the console and ran it.

Once I told it which context was my identity context, I then had to update the database. That was simple enough as all I had to do was use the following command:

Update-Database

That updated the identity database and allowed me to run my application again.

Now, whenever the identity system changes, I can easily update the data model. Though, I’m not quite sure what to do in situations where the changes are destructive (I could lose data). I need to learn more about this.

Calling DataBind() on a GridView within an UpdatePanel to handle a row delete command

Written by Michael Earls
 .NET  ASP.NET  C#  VB.NET

I was working on maintaining a site that used a GridView within an UpdatePanel and had difficulties with the DataBind() call. I added a delete button (using a CommandField) to the grid and wired up the command logic to delete from a generic list that I was keeping up with. The grid was bound to the List. It just wasn’t updating the contents of the Grid when I removed records from the source.

It turns out that when I added the Delete command, I was also supposed to handle the OnRowDeleting event. I didn’t receive an error message to let me know this until I removed the UpdatePanel and tried it again. Once I added the handler for the event, it worked just fine. So I added the UpdatePanel back and everything now works as it should.

.Net - Creating a generic extension of "Contains" to see if there's something in a generic collection

Written by Michael Earls
 .NET  C#  DTO  Extension Methods  featured  Generics

Update: Added reference links at bottom of entry.

I was working with some code today and needed to see if a list of custom DTOs contained an object based on a string value I had. Here is my solution.

Some background…

Our Architecture uses a base abstract class called DtoBase:

public abstract class DtoBase { public string Id { get; set; } public string Description { get; set; } public DtoBase() { } public string ToJson() { StringWriter w = new StringWriter(); JsonSerializer s = new JsonSerializer(); s.Serialize(new JsonTextWriter(w), this); return w.ToString(); } }

All classes that derive from DtoBase have their own properties, but they all benefit from Json serialization using the ToJson method. This helps us in various ways in the application.

I am working with a generic list of a subclass of DtoBase (AccessoryGroup):

public class AccessoryGroup : DtoBase { public bool QCFlag { get; set; } }

With this list, I wanted to see if it contained a DTO with an ID based on a given string. Unfortunately, the built-in Contains extension method on the list (in the System.Linq namespace) does not allow this behavior. It would require me to create an instance of AccessoryGroup containing the values I want to compare (and implement the IEquatable interface on DtoBase. No big deal, but another requirement). What I needed was a version of the Contains extension method that let me pass in a string.

So, my first attempt was to create my own extension method using List as the type to extend:

public static bool Contains(this List list, string val) { foreach(DtoBase dto in list) { if dto.Id val.Trim() { return true; } } return false; }

Aside from the use of the foreach (which I refactored in the final code), this code did not work.

Here is some test code:

List accessoryGroupList = new List(); accessoryGroupList.Add(new AccessoryGroup { Id = "test", Description = "This is just test data" }); if(accessoryGroupList.Contains("test")) { // this should be true }

However, this code did not work. In fact, it didn’t even build. I got invalid arguments exceptions with my Contains call.

What to do? It then occurred to me that I’m working with a generic list, so I need to take a generic approach to this. Here’s the final code taht implements my new extension method as a generic method:

public static bool Contains(this List list, string val) where TDto : DtoBase { return list.Any(a => a.Id.Trim() val.Trim()); }

Not only have I refactored to remove the ugly foreach loop, but I’ve converted the method to a generic method.

I thought I was going to have to write my code like this:

List accessoryGroupList = new List(); accessoryGroupList.Add(new AccessoryGroup { Id = "test", Description = "This is just test data" }); if(accessoryGroupList.Contains("test")) { // this should be true }

But I did not. It seems that because the accessoryGroupList is already a generic list of AccessoryGroup DTOs, it automatically knows that the Contains method will use the same type. Nice, huh?

So, my original code worked:

List accessoryGroupList = new List(); accessoryGroupList.Add(new AccessoryGroup { Id = "test", Description = "This is just test data" }); if(accessoryGroupList.Contains("test")) { // this is true }

As you can see, using generics and extension methods has saved the day again. There is a lot of generic code in our architecture using the DtoBase class. This is just another example of why generics and extensions are so important.

Our server repositories that feed our REST API use the same DTOs that our portable class library containing our client libraries uses. Because of the shared class library, I can use this new extension method on the server or on the client.

References:

MSDN Extension methods guide
List.Contains() method

Code Refactoring - Converting an array with blanks to a List in C#

Written by Michael Earls
 .NET  C#  Refactoring

Update: It seems I could have simply used StringSplitOptions.RemoveEmptyEntries:

userFunctions.AccessoryGroups = reader["AccessoryGroups"].ToString().Trim().Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries).ToList();

to reduce it to a single line of code.

I was writing some code the other day and I had the feeling that there was an easier way to do it. I was converting an array to a List, but I wanted to eliminate any blank strings, so I couldn’t just call myArray.ToList().

Old code:

List accessoryGroupsList = new List(); string accessoryGroups = reader["AccessoryGroups"].ToString(); string[] accessoryGroupsArray = accessoryGroups.Split('|'); foreach(string accessoryGroup in accessoryGroupsArray) { // get rid of any blank strings if(accessoryGroup.Trim() != string.Empty) { accessoryGroupsList.Add(accessoryGroup); } } userFunctions.AccessoryGroups = accessoryGroupsList;

As you can see, that’s a lot of code. It just seemed like overkill to me, so I had to refactor.

Here’s the final code:

string[] accessoryGroups = reader["AccessoryGroups"].ToString().Trim().Split('|'); userFunctions.AccessoryGroups = accessoryGroups.Where(a => a.Trim() != string.Empty).ToList();

From 7 functional lines of code to 2. I’d say that’s an improvement. It also looks more elegant. And in the end, isn’t it all about elegant code? :)