Start writing C# apps on a Raspberry Pi in 5 minutes or less
I decided to play around with running C# on a Raspberry Pi for a variety of reasons. First and foremost: I’ve been wanting to branch out into another language for a while. JavaScript is great, and it will always be my true love. But I have been feeling pretty limited lately about what I can accomplish knowing only one language. And I’ve always heard that learning the second language is much easier than learning the first.
But why C#? The honest reason is that C# is really popular around OKC. Lots of companies use it, and in an effort to be competitive, I figured I would pick it up too. Plus I know a lot of people who know C# whom I could ask for help.
But once I selected C#, a problem arose. I use a Mac, and that doesn’t jive with C#. There were some solutions I found including getting Parallels and installing Windows on a VM and writing the C# in my Windows VM. But even typing that sentence just now made my head spin. I was looking for something simple that would allow me to lean on what I already know as much as possible.
Enter: My Raspberry Pi.
I was able to set up my Raspberry Pi to run C# apps without much trouble. This solved a few problems. I’m able to remote into my Pi from my Mac, and I didn’t have to install anything on my Mac. I wasn’t too worried about breaking my Raspberry Pi, because it was only $35. It would be far easier to replace than my Mac, and if anything were corrupted it would likely be as simple as replacing the SD card. Easy-peasy. Also the set up to be able to run C# apps was incredibly easy. I joke around about things taking 5 minutes, but this literally took less than 5 minutes.
** I should note here that this process assumes you are already able to ssh into your Raspberry Pi. Or learn how to set up a pi from scratch. **
1. ssh into your Raspberry Pi using the terminal
Pretty easy: ssh username@pi
and then enter your password.
2. Install Mono
Mono is an implementation of the .NET framework that can be installed on Linux. Since the Pi is running a flavor of Linux, this is what we’ll use to run our apps.
sudo apt-get update
sudo apt-get install mono-complete
And that’s all you need!
3. Get a text editor && write your app!
Usually I prefer to use an IDE, but since I was writing a super simple Hello World
app, I didn’t think I needed one. I chose nano, but you can use whichever terminal text editor you like. I just liked nano because it comes with bash, which is already on the Pi. Also, a side note: writing your app might take more than 5 minutes. Don’t @ me.
Use this command to create and edit a file: nano yourFileName.cs
.
If you aren’t familiar with nano, it can be a little confusing. The thing I always fumble for is saving my work and closing. This is done with cmd-X
. You’ll get a prompt to save and get kicked back into the directory the file lives in. If you want to see the contents of a file, you can use: cat yourFileName.cs
.
** Remember to use the .cs
extension since we’re writing C# apps! **
4. Compile to .exe
This is where Mono comes in.
Use this command: mcs yourFileName.cs
That will create: yourFileName.exe
in the same directory. Pretty cool, right?
5. Run it!
To run the program use this command: mono yourFileName.exe
. Just make sure you target the .exe
and not the .cs
file.
Extra credit:
Let’s pretend for a moment that you don’t like writing apps in the terminal. (It’s ok, I don’t either!) There must be a way to write the app in an IDE and then run it, right? You’re in luck!
There are two options. First, you could simply plug your Pi into a monitor and download Visual Studio Code. VS Code is compatible with Linux (at least, according to the VS Code website) and you can write C# with it. This keeps you in the Pi 100% of the time.
However, I was looking for another solution. I’m very comfortable writing code on my Mac and wanted to stay there. Solution: Use VS Code for C# apps, and transfer the files to the Pi via scp
. Scp comes included with bash, and is very easy to use.
scp /path/to/your/local/file remoteUser@some_address:/home/remoteUser/Documents
And there you have it! You’re ready to write C# apps and run them on a Raspberry Pi. Happy hacking! Be sure to let me know what cool projects you come up with!
Write your first React app in 10 minutes
Since React is getting so much buzz these days, I decided I wanted to try it out. But the problem was, where do I start? Getting started with React has always seemed so daunting because of all of the tools you need. Webpack, Redux, ES6, JSX, crazy build processes and more. It is a pretty big task just to get started.
Enter: create-react-app. create-react-app is a boilerplate app starter from Facebook. There are pros and cons in that since the build process isn’t configurable, it might not be good for a React veteran who wants a specific build process. However I think the simplicity of the build process is what makes it great for a beginner.
Once I installed the module I was able to download a new sample app and immediately start building. Exactly what I wanted!
The first thing I built (after Hello World
, of course) was a sweet movie countdown timer. You can get out the code here and see the live site here. AND! This is probably the coolest part, James England used my countdown timer to make his own countdown to the Oscars.
Let’s get started!
My First Component
React components are basically modules. You can export them and use them anywhere through out your app. React is a little weird at first because the render()
function is where your HTML lives. It’s uncomfortable at first, but also a pretty neat idea.
Component.js
export default class Hello extends React.Component {
render() {
return(
<h1>Hello World!</h1>
);
}
}
App.js
import Hello from './Components/hello.js';
class App extends React.Component {
render() {
return (
<Hello></Hello>
);
}
}
The things you should notice here is the render()
function that returns Hello World
wrapped in <h1>
tags in the component.
Next we’ll talk about props. A prop is an argument that is passed into the react function through the Component. It might look like this:
Component.js
export default class Hello extends React.Component {
render() {
return(
<h1>Hello {this.props.name}!</h1>
);
}
}
App.js
import Hello from './Components/hello.js';
class App extends React.Component {
render() {
return (
<Hello name="Carmen"></Hello>
);
}
}
Oftentimes your app is going to have data that changes and then the DOM needs to be re-rendered. First the data needs to be attached to state, which is where the constructor comes in.
Constructor.js
export default class Movie extends React.Component {
constructor() {
super();
this.state = {
name: 'Carmen'
};
}
changeNameThroughForm(newName) {
this.setState({name: newName});
}
render() {
return(
<h1>Hello {this.state.name}!</h1>
);
}
}
You probably will be getting data from an external source like an API. The process for rendering the API data is identical. Once you have the data back from the API you’ll use this.setState.
export default class Movie extends React.Component {
constructor() {
super();
this.state = {
name: null
};
this.getNameFromAPI = this.getNameFromAPI.bind(this);
}
componentDidMount() {
this.getNameFromAPI().then(function(response) {
this.setState({name: response.data.name});
}.bind(this));
}
render() {
return(
<h1>Hello {this.state.name}!</h1>
);
}
}
Notice I am binding to this
in the constructor, as well as in the then. If you don’t use arrow functions in react, this
will default to window. The way around that is the .bind(this) that I am using.
Next let’s talk about Lifecycle Events. Lifecycle Events take place at different points while your app is loading.
componentDidMount() {
this.getNameFromAPI().then(function(response) {
this.setState({name: response.data.name});
}.bind(this));
}
componentDidMount
is called directly after the component is rendered, so this is a good place to make an API call. There are several different Lifecycle Events including componentWillMount
, which is called before the component is rendered, and componentWillUnmount
which runs after the component is removed. You can see the Lifecycle Events documentation here.
This is what I used to get started with React. I’m really looking forward to working with it more!
What did you use to learn React? Are there any resources that I should include?
How to set environment variables on a Mac
In this post I’m going to briefly describe how to set and use environment variables.
You might be wondering why you need environment variables. Here’s an example: recently I wrote a twitterbot. The bot’s credentials were stored in a config file within the project. However, for security reasons, I couldn’t deploy the files to GitHub or to Heroku because anyone with access to those credentials would have unfettered access to my account.
So in searching for a solution, I found environment variables.
To set an environment variable in Mac is very simple. Open your terminal and type in the following command:
export NAME=CARMEN
And that’s it!
To verify that the variable was added you can use the env
command to list out all of your environment variables.
Now that you’ve set your environment variable, how do you access it? Node makes this easy. Just use:
var whoAmI = process.env.NAME;
console.log(whoAmI); // CARMEN
This is extra handy because I was able to add environment variables to my Heroku project as well, and those variables can be accessed the exact same way. Meaning, I don’t need two separate sets of logic for my home machine versus my production app.
If you add an environment variable and need to remove it, that is simple too.
unset NAME
That’s all there is to it! Just be very careful and only use unset
for variables that you’ve added. Otherwise you could easily break your machine by removing something important.
Another option, if you don’t want to add environment variables to your home machine (and I wouldn’t blame you if this were the case) is to use dotenv. This handy plugin takes key-value pairs from a .env
file within your project and adds them to process.env
.
If you decide to go this route, it is very important that you add the .env
file to your .gitignore
file so that your credentials aren’t shared with the world.
I hope you’ve enjoyed this post and learned something new!
Promise?
If you’ve worked with JavaScript for any length of time, you’ve probably run into promises. And if you’re like me, you probably shake your head and wonder why JavaScript has to let you down like that.
Promises are a pretty difficult thing to wrap your mind around. Andy Shora has a pretty great cartoon about promises that I’ve referenced a bunch of times trying to wrap my head around promises.
Basically you use promises when you need one thing to complete before the next function runs. If you’re thinking that this sounds very similar to callbacks, you’d be right. So why would we use a promise over a callback? Well there are a few reasons, but I think the most compelling reason is clarity. For example, a complex set of callback functions may look like this:
getData(function () {
convertData(function () {
convertDataAgain(function () {
outputData(function () {
})
})
})
})
That’s pretty icky, right? Whereas the same code written as a promise might look like this:
getData
.then(convertData)
.then(convertDataAgain)
.then(outputData)
Wow, what a difference! When you compare callbacks to promises, promises are much clearer about what is actually happening, and the order in which the functions are executed.
But how does one actually use a promise?
Let’s take a closer look. Sometimes you’re already working with something that will return a promise. Angular’s $https
is a good example of this. In that case, your promise might look like this:
$https.get('someUrl').then(
function success(data) {
doSomeCoolStuff(data);
},
function error(err) {
oops(err);
});
Since $https
already returns a promise, we don’t need to do anything special and we can just include our success and error functions and we’re good to go.
But what if we aren’t using anything that already returns a promise? Well that isn’t really a problem because we can create our own promises. Recent I built a Twitterbot which makes use of promises. The code looks like this:
var pickTheQuote = new Promise(function(resolve, reject) {
getQuotes();
if(quotesArr <= 0) {
reject(pickTheQuote);
return;
} else {
resolve(pickTheQuote);
}
});
function chooseQuote() {
// return random quote
}
function postToTwitter() {
// post quote to twitter
}
pickTheQuote
.then(chooseQuote)
.then(postToTwitter)
The first thing I did up there was create a new promise. Then, based upon the contents of an array, I either reject or resolve the promise. In the event that my array is empty, I reject the promise and stop the function entirely. In the event that I have contents in my array, I resolve the promise.
Once the promise is resolved, I call the chooseQuote
function and after that, I call the postToTwitter
function. Obviously these functions need to execute in this specific order, otherwise, I might not have a quote to tweet.
And that’s the basics of promises. After you create a promise, based on certain criteria you can either resolve or reject your promise. Then you can execute functions after your promise has been fulfilled.
I hope that helps clear up promises for you!
Many thanks to Devin Clark for helping proofread this post and writing some example code. Thank you, Devin!
Live coding is hard
I’ve done a weird amount of live coding lately, and unsurprisingly I’ve been really terrible at it. Live coding is hard. And like so many other things in life that are hard, the only real way to get better at is to practice. The unfortunate thing about live coding? There aren’t very many opportunities to practice.
I am friends with a lot of smart people and when I asked them for advice on live coding, the most common advice I got was to not live code.
They listed off several alternatives that I’ll go into here, but ultimately the advice I got was to avoid live coding.
Morgan Estes suggested using do it live or something similar to give the illusion of live coding without the live debugging. Paul Dawson suggested using a cheatsheet, or recording the live coding at home to then show during the live coding session. Mark Wissler suggested using the “cooking show approach.” Explain how you would write the file, and then show the completed file.
My personal ideal for a demo is to comment out your account and comment it back in during the demo to show off the functionality. This can be more tedious to prepare, but it gives the audience an idea of what each commented chunk of code contributes to the final product.
And even so, all of these are great, but what if you can’t fake the live coding? What if you have a job interview and you must do some live coding during the interview? Well I’ve been in that situation lately too, and I’m here to tell you I didn’t do well in those interviews. It is a super hard thing to pull off. In addition to having to code in front of another person – which by itself is never fun – you have the added stress of this being a job interview. In my experience those are never fun either.
So what do you do in this case? You can’t really fake it because you don’t really know what you’re going to be asked to do. You can try to prepare by doing some random code challenges in front of friends or family, but it’s not really going to reproduce the stress.
Well, I’ve put together some tips for dealing with this. Hopefully they’ll help you if you find yourself in a live-coding interview.
1. Try to relax
It is definitely the most overused piece of advice out there. Maybe the hardest to follow too. But it’s important to remember. Remember to breathe and avoid getting so worked up you lash out or shut down.
2. Talk through it
It’s not only awkward for you to sit in silence trying to come up with the answer, it’s likely awkward for your interviewer to sit there staring at you. Talk through what is going on in your mind as you try to come up with the solution to the problem. Do they have a whiteboard? Ask if you can use it to brainstorm a little bit.
3. Comments, comments, comments
I think this was the favorite piece of advice I got for this. Jesse Harlin suggested doing an outline of your program in comments before coding it. This allows the person interviewing you to see how you would solve it in case you run out of time, as well as give you something to go back to in case you go blank.
4. Ask lots of questions
Ask if there is something specific they are wanting you to show with this. Are they wanting you to use .map()
or does it matter? Or perhaps use an object over an array. If your function is going to be accepting parameters, which types will be input? A string or an object or perhaps both? All of these are completely valid questions that will show you are thinking about the problem, and will save you some time writing the program.
5. Ask how you can improve
This can be really hard to do, especially if you feel like you didn’t do very well in the interview. But you might get some really good information that helps you in the future. I was told that I should slow down and think out the entire problem before jumping into the code. Pretty good advice since most interviews last an hour, and I spent a lot of that time writing what turned out to be wrong program because I hadn’t asked the right questions.
Most of all, remember that pretty much everyone comes out of a live coding interview feeling like they didn’t do well. It’s a tough thing to do in a very stressful scenario. No one really wants to admit that, but it is true. Live coding isn’t indicative of you as a programmer, it’s just indicative of how you did under pressure in this one very stressful 45-minute interview. So don’t beat yourself up too badly.
Do you have more tips for live coding? Let me know in the comments!
There are a lot people I talked to and sought advice from before writing this blog post. Here they are in no particular order: Rob Sullivan, Jesse Harlin, Mark Wissler, Devin Clark, Adam Rackis, Morgan Estes, Paul Dawson, David Roberts, and Ryan Hoegg. Thanks so much to all of these guys for chatting with me and giving their insights!