Dependency Injection – Unity and MVC with .NET

I have spent most of my career developing solutions in .NET and will always have a soft spot for C#.  I decided to create a fun blog on Dependency Injection since most of my earlier blogging have been leveraging Java.

The first time I was trying to apply or even understand the abstract concept of Dependency Injection (DI) or Inversion of Control (IoC), I was completely lost.  If you are the same person who I was then I hope this blog really helps you out.

So our objective in this blog is to create a quick .NET MVC project and add Dependency Injection to it.  We will then go over the benefits of doing this; hopefully you will quickly understand why most if not all projects should have some sort of DI or IoC.

Lets get started by creating a basic MVC Application using Visual Studio.  If you need Visual Studio then please google “Visual Studio Community Edition”!  Its free!

Now that we have a basic project created, we need to add Unity to our project using NuGet.  (Tools –> NuGet Package Manager –> Manage NuGet Packages for Solution…)

Search for “Unity.MVC”, select and install it on your website project

We have all of the tools we need installed so lets go over our objective now.  We are going to create a Business Layer that we will return some data from our pretend database since the data layer is the most common object that is put into DI.   You know you have a good solution if you can completely unplug your PC from the network and still run all of your test scripts for your database methods, etc.  This is our goal in this Blog.

Lets start by adding a simple business layer to our application. (Right click your solution, Add –> New Project)

Now we will create a quick interface and class.  The interface will be used by the Web Project and the Test Project.  The class in the business layer will implement the interface on the Web project which is where you would wire up your database.

A couple of house cleaning items after you create the project; it will automatically put a class in your project called “Class1.cs”.  I am renaming that to DataLayer.cs for this demo.  For the sake of simplicity, I will not be wiring this up to an actual database but creating a function that will return data.  The data source at this point is irrelevant mostly because we are demonstrating how to put a class/object into DI and overriding it for our test project.

Lets just create a super basic data layer that delivers data from an int constant and pretend that it got that data from the worlds largest and fastest database server!  Here is the code for our DataLayer and Interface that we need to toss into our business layer.

Interface: (IDataLayer.cs)

namespace MVC_DI_BL
{
    public interface IDataLayer
    {
        int giveRecordCount();
    }
}

DataLayer Class: (DataLayer.cs)

namespace MVC_DI_BL
{
    public class DataLayer : IDataLayer
    {
        private const int recCount = 10;

        public int giveRecordCount()
        {
            return recCount;
        }
    }
}

Now lets wires this bad boy up to our MVC Website!  Sadly this is where the fun really begins for nerds like me.  Open the UnityConfig.cs file under the “App_Start” folder and look for the RegisterTypes method.

UnityConfig.cs – > public static void RegisterTypes (IUnityContainer container)

We want to add this line at the bottom of this method.

container.RegisterType<IDataLayer, DataLayer>();

Super Duper Important Note About the Code Above!
This is the most important part of this; we are essentially adding an instance of our DataLayer class which is aligned to our IDataLayer interface directly to our Unity Container.  Everytime Unity is asked to fulfill the dependency of IDataLayer, it will reach into this container and give that instance the DataLayer class which it instantiates on app start.  This is the black magic of dependency injection!

Lets test our implementation and make sure it works.  We have 2 super easy ways to test it.  We can perform property injection or constructor injection.  I will quickly show you how to do both.

Property Injection:
1. Create a property:   public IDataLayer dl { get; set; }
2. Add the [Dependency] attribute to the property.

The unity framework will automatically bind your DataLayer : IDataLayer instance from the Unity Container to this property.  Easy right?

Alternatively you can use Constructor Injection which typically makes building your test cases easier.  I personally prefer this because I am a little lazy and like to reduce the number of lines of code in my test cases.

Constructor Injection:
1.  Create a property: public IDataLayer dl { get; set; }
–We don’t need to add the [Dependency] attribute to this for constructor injection
2. Create a new Constructor with a parameter and update our property here.
public HomeController(IDataLayer _dl) { dl = _dl; }
3. Add the [InjectionConstructor] attribute to our new constructor.

I have added my code for the HomeController and Index view below for you to test this out.  The example uses both Property and Constructor Injection; to test each individually you will just need to comment out the appropriate decoration/attribute.

using Microsoft.Practices.Unity;
using MVC_DI_BL;
using System;
using System.Web.Mvc;

namespace MVC_DI.Controllers
{
    public class HomeController : Controller
    {
        //Property + Property Injection
        [Dependency]
        public IDataLayer dl { get; set; }

        #region Constructors and Disposal of objects
        //Modified the constructor for Unit Testing... Constructor Injection will 
        //populate this value in real-time.
        public HomeController() { }

        [InjectionConstructor]
        public HomeController(IDataLayer _dl)
        {
            dl = _dl;
        }
        //Clean up
        protected override void Dispose(bool disposing)
        {
            if (dl is IDisposable)
            {
                ((IDisposable)dl).Dispose();
            }
            base.Dispose(disposing);
        }
        #endregion

        public ActionResult Index()
        {
            return View(dl.giveRecordCount());
        }
    }
}
@model int
@{
    ViewBag.Title = "Home Page";
}

<div class="jumbotron">
    <h1>Record Count - @Model </h1>
</div>

Below is what your output should look like once you run your project.

If you get the same output then you have successfully implemented dependency injection into your MVC project.  Now we need to stay course and follow up with our test project.  We do not need to use dependency injection on our tests because we can bind our data manually; we don’t need any of the black magic that Unity performs in the background.

The first thing we need to do is create our Test Project Data Source; I have created a new class called TestDataLayer which inherits IDataLayer.  I then implemented the interface and had it return the number 9 instead of 10.  This way I can guarantee that I have bound my interface to our test data source.  Ideally your test data source should not be wired up to any external dependency so you can automatically test/build your projects offline.

Test DataLayer Code

using MVC_DI_BL;

namespace MCV_DI.Tests
{
    public class TestDataLayer : IDataLayer
    {
        private const int recCount = 9;

        public int giveRecordCount()
        {
            return recCount;
        }
    }
}

Test Class

using System.Web.Mvc;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MVC_DI.Controllers;
using MVC_DI_BL;
using MCV_DI.Tests;

namespace MVC_DI.Tests.Controllers
{
    [TestClass]
    public class HomeControllerTest
    {
        [TestMethod]
        public void Index()
        {

            //Setup our test datalayer that we can easily create fake data that can be accessed offline, etc.
            IDataLayer dl = new TestDataLayer();

            // Arrange
            HomeController controller = new HomeController(dl);

            // Act - Does it still work with our custom datalayer?
            ViewResult result = controller.Index() as ViewResult;

            // Assert that our page still works
            Assert.IsNotNull(result);

            //Make sure we are using the test data layer and getting back the exact value we want.
            Assert.AreEqual(dl.giveRecordCount(), 9);  //the value 10 is returned from the datalayer we are using on our web project
        }

    }
}

As you can see all I have to do is call our HomeController with the constructor that takes our parameter and “poof” we have passed in our test datalayer.  Now all of our tests will automagically work.

Test – > Run – All Tests

Adding dependency injection may feel like yet another step to over architect your projects but after doing this a few times when developing an end to end solution you will quickly see how much of a requirement this is in order to build real-world solutions.  Unity is probably the easiest solution I have found for .NET MVC and it works great!  I hope this helps out someone who is newer to this concept; I know when I first was introduced to this that I was completely lost.  We all will have to go through this milestone on our way to becoming professional developers!  Good Luck!

Java and Real-time Raspberry Pi Sensors

I am a fan of Java even when it is not the best language for the job. The Java language is by far one of the most popular and widely used languages out there.  Unfortunately one language cannot do everything perfectly and in fact when working with the Raspberry Pi I have ran into a serious fundamental issue.  Java is not a real-time language; the sensors run their processes faster than Java can read the responses.

In this blog I will show you how to EASILY use Java and still use real-time sensors such as the temperature sensor.  If you are like me and do not want to abandon Java as your platform then here is the high level strategy for bridging this small gap.  We are going to build a small C++ script to basically make the call and return the data to our Java application then do the rest of the work in Java.

Look I know this sounds spotty and it is to a degree but there are so many advantages to retaining Java so your platform especially if you are truly building a device that talks to web services and external entities.  There is so so so so much great support, libraries and tutorials on how to do virtually anything and everything in Java.  You CANNOT compare the support and functionality of Java to C++, Python, etc.  (My Java rant is now done… sorry if you disagree, on some levels your opinion may be correct)

Lets get started!  Here is a basic Java application which we will use to obtain the Temperature and Humidity of the environment as well as the range of an object in front of our range finder sensor.

public class TestClass {
    public static void main(String[] args) {
        System.out.println("This is my console app");
        System.out.println("Reading from my sensor:" + giveWeatherData());
    }
	 
    public static String giveWeatherData() {
        //Here is where we will call our sensor and return data
        return "";
    }
}

Now lets take a break from Java and build our C++ app that makes the actual call to our sensor.  I would recommend compiling this on your Raspberry Pi to ensure all of your dependencies are already there; its super easy to do and can be done via a quick SSH session.

Create a basic text file and drop the code below into it; you will want to name this file testweather.c  then paste the code below into it.

#include <wiringPi.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#define MAXTIMINGS	85
#define DHTPIN		7
int dht11_dat[5] = { 0, 0, 0, 0, 0 };

//Compile
//gcc -o testweather testweather.c -lwiringPi -lwiringPiDev
 
int read_dht11_dat()
{
	uint8_t laststate	= HIGH;
	uint8_t counter		= 0;
	uint8_t j		= 0, i;
	float	f; 
	int ret = 0;
 
	dht11_dat[0] = dht11_dat[1] = dht11_dat[2] = dht11_dat[3] = dht11_dat[4] = 0;
 
	pinMode( DHTPIN, OUTPUT );
	digitalWrite( DHTPIN, LOW );
	delay( 18 );
	digitalWrite( DHTPIN, HIGH );
	delayMicroseconds( 40 );
	pinMode( DHTPIN, INPUT );
 
	for ( i = 0; i < MAXTIMINGS; i++ )
	{
		counter = 0;
		while ( digitalRead( DHTPIN ) == laststate )
		{
			counter++;
			delayMicroseconds( 1 );
			if ( counter == 255 )
			{
				break;
			}
		}
		laststate = digitalRead( DHTPIN );
 
		if ( counter == 255 )
			break;
 
		if ( (i >= 4) && (i % 2 == 0) )
		{
			dht11_dat[j / 8] <<= 1;
			if ( counter > 16 )
				dht11_dat[j / 8] |= 1;
			j++;
		}
	}
 
	if ( (j >= 40) &&
	     (dht11_dat[4] == ( (dht11_dat[0] + dht11_dat[1] + dht11_dat[2] + dht11_dat[3]) & 0xFF) ) )
	{
		f = dht11_dat[2] * 9. / 5. + 32;
		printf( "Hum:%.0d%% Temp:%.0fF\n",
			dht11_dat[0], f );
	ret = 1;
	}
	return ret;
}
 
int main( void )
{ 
	if ( wiringPiSetup() == -1 )
		exit( 1 );
 
	int getRes = 0;
	while ( getRes == 0 )
	{
		
		getRes = read_dht11_dat();
		delay( 1000 ); 
	}
 
	return(0);
}

We need to compile and run this on our Raspberry Pi so if you created it locally then you will want to transfer it to your Pi.  On your Raspberry Pi you will want to run the following command to compile this code in a console window.  I have put this code at the top of the code block above in a comment; if you are anything like me then you will not remember the full command later on.

gcc -o testweather testweather.c -lwiringPi -lwiringPiDev

Now that this is compiled, we just need to test it real quick; just log onto your Pi and run the command below from a command prompt. (Make sure your sensor is hooked up)

./testweather

You should get this output if you have your sensors hooked up to the right pins

So we have proven that our C++ app can successfully call the sensor and receive feedback from it.  We now need to call this app from Java and read that output.  This part is relatively simple because we are basically going to have Java create a command prompt in memory, run the application and parse the output that you would normally see if you executed it manually.  I created a function called giveWeatherData that does just that!

  public static String giveWeatherData() {
	 //Here is where we will call our sensor and return data
	String ret = "";
    	
	Runtime rt = Runtime.getRuntime();
	String[] commands = {"/home/pi/pew/testweather","-get t"};
	Process proc = null;
	try {
		proc = rt.exec(commands);
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

	BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
	BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

	// read the output from the command
	String s = null;
	try {
		while ((s = stdInput.readLine()) != null) {
			ret = s;
		    System.out.println(s);
		}
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

	// read any errors from the attempted command
	try {
		while ((s = stdError.readLine()) != null) {
		    System.out.println(s);
		}
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
	return ret;
 }

That is pretty much all of the major moving pieces for this blog; all that is left to do is put it all together.  Here is the Java code with everything that you need!

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class TestClass {
	
public static void main(String[] args) {
    System.out.println("This is my console app");
    System.out.println("Reading from my sensor:" + giveWeatherData());
}
	 
 public static String giveWeatherData() {
	 //Here is where we will call our sensor and return data
	String ret = "";
    	
	Runtime rt = Runtime.getRuntime();
	String[] commands = {"/home/pi/pew/testweather","-get t"};
	Process proc = null;
	try {
		proc = rt.exec(commands);
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

	BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
	BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

	// read the output from the command
	String s = null;
	try {
		while ((s = stdInput.readLine()) != null) {
			ret = s;
		    System.out.println(s);
		}
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

	// read any errors from the attempted command
	try {
		while ((s = stdError.readLine()) != null) {
		    System.out.println(s);
		}
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
	return ret;
 }

}

Let run our Java Application and see it all in action.  Make sure that the C++ application is in the same directory as the Java App; if so then you should be good to go.

Now you can continue to use Java and leverage its strong points with a fairly simple way to bridge a weakness in this language.

Tomcat and Docker, Why and how?

My rant about Docker and why it is great!

I am a huge fan of Docker and what it can do you for; especially in an industrial or entrepreneurial environment where scaling, stability, changes and frequent code releases are the norm.  The bullet points below are in my opinion the biggest advantages committing to containerizing your code/deployments.

  • Stability – You are developing your code for a controlled environment; once it works in your Docker container then you are set!  It does not matter where you host it or how each host is configured.  Your code will behave the same in dev as it does in uat and in your production environment.
  • Automated Scaling –  You will be hosting your docker container in a controller framework such as Kubernetes which boasts great features such as auto scaling, auto deployments, etc.  This is huge in regards to saving on resources; your instances will scale up and down with demand so you are not paying for servers that are not being used.  More importantly your product will not go down due to spiking demand (within reason of course).
  • Self Healing – Hosting vendors such as Google have built in self healing mechanisms directly into their platforms,  Lets say you wrote some code that slowly consumes disk space over time; eventually this will bring your Tomcat instance down.  Well if you have this containerized, the platform will immediately bring up a new “healthy” instance in its place to ensure constant up-time. (Just an FYI, I have never written bad code so this is only a hypothetical for me)
  • Managing Change – Change is a part of life so you better be ready for it.  Docker is quickly becoming a constant in the world of hosting so this naturally makes changing hosting companies a piece of cake.  I can confidently move my docker instances to virtually any Docker hosting company with 100% certainty that it will behave exactly the same as the prior host the first time.  Its almost the same concept of turning off a server, shipping to a new location and starting it up again; its just going to work with no additional effort.

The biggest disadvantage is really the easy of just creating something and pushing it out to a host; setting up your product on a hosting platform will take a little work especially if it is your first run at this.  This is by no means a reason to not at least give this a whirl; having this skill at your fingertips can easily give you a serious competitive advantage in the development and hosting industry.

Creating a Docker Instance with Tomcat (on a mac)

Lets go over how to create a docker instance that uses Tomcat and push a compiled Tomcat site to it.

The first thing we NEED to do is install the Docker tool on your machine; this will basically be the mechanism that we use to build and run our docker instances.  Without this we are nothing more than a boat without water.  Installing Docker is super easy; all you need to do is go to the docker website and download/run the latest stable version of “Docker Community Edition”.
Docker Download Link

After you download and setup Docker we will open a command prompt/terminal to test it out. When you open the command prompt, simply type “docker-machine ls” which shows you all docker virtual machines you have setup on your machine.  If you run this and you have no machines listed then you can simply run this following command to create a default instance/vm.

docker-machine create --driver virtualbox default

Now that we have Docker installed, we will need a quick website to run on it using Tomcat.  I will not go into how to build a quick Java site, instead I have a war file that you can download and use in your example. (I Love Apples Website – WAR File)  – Download and un-compress this file.

Next we will create our Docker file which is nothing more than a flat text file with instructions for the Docker application to use.  We will basically be telling docker about the instance we want it to create.

Go ahead and create a blank text file and add the following to it:

FROM tomcat:9-jre8

# Remove unneeded apps
RUN rm -rf /usr/local/tomcat/webapps/* 

# Add our app
ADD ILoveApples.war /usr/local/tomcat/webapps/

# Expose port 80
EXPOSE 80

CMD ["catalina.sh", "run"]

Well now we have created our Docker file and we have a website packaged into a “War” file; we are ready to start putting all of the pieces together and run this web server inside of a docker instance.  Now in this demo we will be running our docker instance inside of a virtual machine which should already be created if you follow the instructions on this blog.

Lets make sure our Docker machine is running.

docker-machine ls

Example output
NAME       ACTIVE   DRIVER       STATE     URL                         SWARM   DOCKER        ERRORS
default    -        virtualbox   Running   tcp://192.168.99.100:2376           v1.12.5       

The 2 things we need to pay attention to here is the “NAME” and “STATE” columns.  If the state is not running then lets start our docker machine by typing the following command.  The name “default” is the name of the vm instance that will be used in our commands for the remainder of this blog.

docker-machine start default

Example output
Starting "default"...
(default) Check network to re-create if needed...
(default) Waiting for an IP...
Machine "default" was started.
Waiting for SSH to be available...
Detecting the provisioner...

This may take a few minutes to start if you are lacking the horse power in your computer; typically its pretty quick though. Now lets connect to our docker instance so that we can build and run our docker file.  This is key to do it this way because this is architecturally how it will be done at any hosting company you use for your website.

Here is how to connect to your docker instance.

docker-machine ssh default

Ok now even though you are technically on a virtual machine, you still have access to your files.  Lets assume that you put the War file and the Docker file we downloaded/created earlier into a folder called “Docker” in your Documents folder.  All we have to do is navigate to that folder and build your docker instance.

docker@default:~$ cd /Users/postalguy/Documents/Docker/

docker@default:/Users/postalguy/Documents/Docker$ docker build -f docker.txt --tag iloveapplesimage .
Sending build context to Docker daemon 10.75 kB
Step 1 : FROM tomcat:9-jre8
 ---> 6b4e3caa8fee
Step 2 : RUN rm -rf /usr/local/tomcat/webapps/*
 ---> 20acb70ce5b8
Step 3 : ADD ILoveApples.war /usr/local/tomcat/webapps/
 ---> a3b723cb8e70
Step 4 : EXPOSE 80
 ---> 89df30a414c3
Step 5 : EXPOSE 8080
 ---> 8b9395bb41b4
Step 6 : CMD catalina.sh run
 ---> d5f62504c882
Successfully built d5f62504c882

The docker build command is fairly easy; -f define the file we created, –tag is giving our docker instance a name we can use identify/control this instance.   The final “.” at this end says to look in this directory for everything we need.

If we run the following command we will see our docker image registered with this docker instance.

docker images
REPOSITORY                              TAG                 IMAGE ID            CREATED             SIZE
iloveapplesimage                        latest              d5f62504c882        2 days ago          366.6 MB

We are almost done now!  We just need to start our docker image inside of our docker virtual machine.  This is super duper easy!  We will use the docker run command; forwarding the outside 8080 port internally to our tomcat server on port 8080.  If you use the -d command in addition to this then it will run your instance in the background, releasing your console to run another command.  For testing purposes I like to keep it running on the same thread so I can see the output of my tomcat server.

docker run -p 8080:8080  iloveapplesimage

We are almost done now!  (I think I have said this before).  Lets open another fresh console; we just need to get the ip address of our docker machine that we started our docker image in.  Here is how we do this.

docker-machine ls
NAME       ACTIVE   DRIVER       STATE     URL                         SWARM   DOCKER        ERRORS
default    -        virtualbox   Running   tcp://192.168.99.100:2376           v1.12.5

So now we know our docker IP address, all we need to do is fire up a web browser and put the following URL in it!  (Substitute the IP from the URL  column above into your URL)

http://192.168.99.100:8080/ILoveApples/index.jsp

Well that is it!  Now every time you update your WAR file, just copy it into your docker folder and rebuild/rerun your docker instance.  Honestly it is a bit more work for deploying website BUT this is by far a sophisticated way to engineer your product for scalability/stability/predictability without having to over engineer your code and web server.  This will save you so many hours of heart ache, coding and engineering if you have a big project with a lot of demand and expectation to be ready for anything.  I personally love docker and have used it in professional environment; I have been able to scale up my servers globally/regionally, automatically fix bad instances and reduce overall cost…. All while I was sleeping!  Its all automated by your hosting company from here on out!

Real World Docker File Example

Now this was a super simple sample of a docker file.  I would like to leave you with one of my personal docker files that I have used on the google web platforms (which uses Kubernetes).

FROM tomcat:7-jre7
MAINTAINER ****@****.com

# Remove unneeded apps
RUN rm -rf /usr/local/tomcat/webapps/* 
RUN rm /usr/local/tomcat/conf/context.xml && rm /usr/local/tomcat/conf/server.xml

ADD tomcat-users.xml /usr/local/tomcat/conf/
ADD server.xml /usr/local/tomcat/conf/
ADD context.xml /usr/local/tomcat/conf/
ADD ****-8d3c9346814d.p12 /usr/local/tomcat/conf/
ADD ***.war /usr/local/tomcat/webapps/
ADD finalkey.jks /usr/local/tomcat/conf/
ADD cacerts /usr/local/tomcat/conf/

ENV DATASTORE_PRIVATE_KEY_FILE /usr/local/tomcat/conf/****-8d3c9346814d.p12
ENV DATASTORE_SERVICE_ACCOUNT 834******63-kb05f2sj2**********h246lh@developer.gserviceaccount.com
ENV JAVA_OPTS "-Djavax.net.ssl.keyStore=/usr/local/tomcat/conf/finalkey.jks -Djavax.net.ssl.keyStorePassword=***** -Djavax.net.ssl.trustStore=/usr/local/tomcat/conf/cacerts -Djavax.net.ssl.trustStorePassword=*****"
ENV CATALINA_OPTS "-Duser.timezone=UTC"
EXPOSE 80
EXPOSE 8080
EXPOSE 443

CMD ["catalina.sh", "run"]



This example above shows you how to import your own SSL keys, key store for connecting to external database server, exposing SSL and adding your own custom tomcat configuration files.

 

Native Android MVC Application

In this blog we will be reviewing an Android template that I created to help developers who are new to native android development quickly get their projects up and running with minimal effort. This project serves as 2 things: 1. A learning template 2. An application template that you can use for your own project.

It was designed in such a way that you can go in and view how the sample pages work, each page containing only the code require to perform that specific example so as to reduce the amount of fluff you need to read through. Once you are comfortable with this then you can move onto turning this into your own project. (Instructions: makingThisYourOwn.txt) Within minutes you can start coding your own business logic into this app, skipping the hours/days it takes to set everything up that you will need.

Lets talk about developing Android apps

Developing android apps can be simple, in fact that is what we are trying to prove today. Like most things in technology, Android development is like Othello.  Easy to learn, lifetime to master.

The basics: All we need is to ensure that Android Studio is setup properly on our machines; this development environment will fill in all of the details for us such as our android emulator, git, etc.
Download Android Studio

Getting down to Business
  • We want to teach you how to start programming Android apps as quick as possible; in order to do that we will be using a custom framework that will help you create a clean app in no time.
  • In order to do this we need to ensure that we have the following elements installed properly on your computers
    • Android Studio – This is the development platform that we use to make android applications with.
    • Git – Used to pull and push code from other Git repositories such as GitHub
Get the Code

We will be using Android Studio to get a copy of our code from GitHub. Create your free GitHub account before we get started if you don’t have an account already. GitHub.com

  1. Open Android Studio
  2. Select “Check out project from Version Control”
    1. Submenu selection of “GitHub”
  3. Enter the following information into the “Clone” window
    1. Git Repository URL:
      https://github.com/postalguy03/android-starter-mvc-template.git
    2. Parent Directory: Select a directory on your computer where you want this project to be downloaded to.  (Folder must exist)
    3. Directory Name: Enter a name for your main project folder
  4. You may be prompted for a “Gradle” location.
    1. Gradle is the program which will automatically download any/all dependencies required to run this project.
Review the Project & Code
  • Java is the primary language used when programming android applications using Android Studio.
  • Lets review our project structure:
    • App – This is the folder that contains all of our application files
      • Manifests – This folder contains our application definition file, this is the point of engagement when the android operating system launches the application
      • Java – This contains… yes you guessed it… Java. Lots and lots of Java classes
      • Res – Short for resources, this contains our views(layout), images (drawable), animations (anim), strings/styles (values), etc.
    • Gradle Scripts – This is the folder that manages all of our project dependencies
  • If your application has red squiggilie lines like the one on this squiggilie word then run the ”Clean Project” command.
    • Build Menu -> Clean Project
Lets Run the Code
  • You have 2 different ways you can run an android application from Android Studio
    • Run it directly on your phone.  You must enable development mode on your phone and then enable USB Debugging.  Enabling developer mode is easy to do.
    • Create a “Virtual Android Device” which is basically a phone running on your computer.
      • Select the Tools Menu -> Android -> AVD Manager
        • Start an existing/prebuilt AVD
          OR
        • Create a new AVD
      • Select your desired Android Virtual Device and under the Actions Column click the green arrow (green play button)
        • You android device could take a few minutes to start.. It is anything but fast.
  • Next lets login to either our physical or virtual android phone.
  • Go back to Android Studio and find the Green Icon that looks like a Bug.
    • Click it and the application will then be pushed and automatically started on your android phone
Lets review how to use this app as a learning tool

This application is structured so you can see and understand the basic concepts of android programming.  We will quickly go over how you perform the following actions:

  • Inner Application Broadcasts – Primarily used for communicating with code that is running on different threads
  • JSON Call Examples – Used to make calls to obtain external content
  • Database Example – Used to store data into a local database
  • Imaging Example – Shows you how to scale and turn square images into circles
  • App Settings Example – Show you how to save data into a the android system preferences
  • Loading Images Example – Shows you how to load images from external resources.

We just need to learn how to use and read this application so that we can understand these examples.

How this works

We will start by running the application to view an example.  Next we will explore how to see the code behind the example.

You should be able to break down each example into its most bare form and just focus on the code that makes it work.

This is really setup so you can basically browse for the functionality that you want to use in your own code and just pull out the parts you need.

 

Make this application your own!
  • You can turn this project which was designed to teach you into your own application in 10 minutes!
    • Close the project, we need to rename our folders and name space
      • Navigate to the location the project resides and navigate to the following path:
        • {folder}/app/src/main/java/  & {folder}/app/src/androidTest/java/
          • Currently our name space is cct.github.droid.android_mvc_sample, in order to change that we just simply rename the next 3 tiers of folders, each folder tier is relative to a dot in the “cct.github.droid.andoird_mvc_sample” name.  If I just renamed the cct folder to dogs then the android_mvc_sample folder to dogs_app and now my namespace would be dogs.github.droid.dogs_app
        • Reopen the Android Application and open your project.  It should now be broken… red squigiligies everywhere!  Don’t worry.
          • Select the following menu item:
            • Edit -> Find -> Replace in Path…
              • Text to find: “cct.github.droid”
              • Replace with: “dogs.github.droid”
            • Update our project configuration by selecting the following menu item
              • File -> Project Structure…
              • One the new window opens up select the “app” selection under “modules”
                • Select the “Flavors” tab and update the following field
                  • Application ID: dogs.github.droid.dogs_app
Modify your home page!
  • Lets create our new “Home Page” for our application.
    In order to do this we need to create 2 elements:

    • Layout Page
      • Open the layout folder
        • Right Click Layout Folder -> New Layout Resource File -> Change Root Elements to Relative Layout -> Give it a name fragment_{name}
      • Controller (Fragment)
        • Open viewController folder
          • Right Click viewController Folder -> New Java Class -> Name it fragment_{name}
          • Now we just need to turn this new class into something that can read and work with our layout file.  In Java we can just “extend” on the Fragment class to do this.  On the next slide is the basic code we need to set this up.
  • Extend the Fragment class
    • Public class fragment_{name} extends Fragment {
      • (click on the red squigilie.. “alt + enter” to import v4.app.Fragment
    • Add out Android Lifecycle methods
      • (Added to the embedded text file)
    • Add your Listener for EventBus (inner application broadcasting)
      • (Added to the embedded text file)
  • If we copied the content from the next slide, be sure to link your new layout file.
    • Current Line:
      • View view = inflater.inflate(R.layout.fragment_home, container, false);
    • New Line:
      • View view = inflater.inflate(R.layout.fragment_{name}, container, false);
Basic Android Fragment Code & Life Cycle Events
public class fragment_temp extends Fragment {

    public fragment_temp() {
    }

    //----------------------------------------
    //------ Android Life Cycle events -------
    //----------------------------------------
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            //Fragment started with arguements.. lets do someting with them!
        }
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);

        return view;
    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }
    @Override
    public void onStart() {
        super.onStart();
    }
    @Override
    public void onResume() {
        super.onResume();
        EventBus.getDefault().register(this); // EventBus
    }
    @Override
    public void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this); // EventBus
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }


    //----------------------------------------
    //--------- Listener(EventBus) -----------
    //----------------------------------------
    //EventBus method for recieving events from other threads/fragments -- used in place of broadcast recievers/intents/listeners
    // ultimately this helps with creating cleaner code quicker
    public void onEventMainThread(EventModel event) {
        if (event.getEventType() == EventModel.EventType.EVENT_BUS_MESSAGE_TEST) {
            Toast.makeText(this.getActivity(), getResources().getString(R.string._txt_EventBus_Sample_Message), Toast.LENGTH_SHORT).show();
        }
    }
    
}
Register your new pages with the App and Run!
  • FragmentRouter
    • Register a new Router Reference
      • Add a new element to the public enum Tag. (Comma separated values)
  • MainApplication
    • Add a new line to register your new fragment
  • MainActivity
    • Update your starting fragment
  • Current line:
    • FragmentRouter.replace(getSupportFragmentManager(), R.id.container, FragmentRouter.Tag.HOME_FRAGMENT, null, FragmentRouter.Animation.NON, false);
  • New Line:
    • FragmentRouter.replace(getSupportFragmentManager(), R.id.container, FragmentRouter.Tag.{new value from first step}, null, FragmentRouter.Animation.NON, false);
Update our Sliding Menu
  • Managing our menu is easy; we only have to update 2 regions.
    • Menu Definition: Strings.xml
      • Open Strings.xml in the Values folder.  Locate and add/update the elements under the “mnu_items” String-Array node/element
    • Menu Click Events: MainActivity
      • Now that we have new values, we just need to handle the events when the are clicked.  We do that in the MainActivity.
        • There is just a repeating “if – else if” statement which we need to modify and add our new menu item element.
Adding basic objects to your new page
  • Open your new fragement_{filename} Layout file
    • Drag a button onto you layout
    • Give it an ID in the properties window
  • Open you Fragment_{filename}
    • Add the following code in your “onCreateView” method
    • //Sample Broadcast -- not binding to button, just setting onclick listener
      view.findViewById(R.id.{id of the new button”).setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) { btnClickMyButton(v); }
      });
  • Add the following method to your file/class
    • public void btnClickMyButton(v(View v) {
          AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
          dlgAlert.setMessage(" I'm really good at stuff until people watch me do that stuff ");
          dlgAlert.setTitle(“About Me");
          dlgAlert.setPositiveButton("OK", null);
          dlgAlert.setCancelable(true);
          dlgAlert.create().show();
      }
  • Run your project!

Basics of the Raspberry Pi – Turning a light on and off

Basics of the Raspberry Pi – Part 3
Part 1 – Basic Setup
Part 2 – How it all works 

Turning a light on and off – Part 3


In this blog we will make a small Java application that turns our light on and off. We will need a few things before we get started.

  1. Eclipse
  2. sFTP Client (Filezilla is a great on that is free)
  3. SSH Client/Terminal
    • If you are on windows that I would recommend downloading PUTTY

The first thing that we will do is Open Eclipse and create a new Java Project.  We will need to add one dependency to this project; the easiest way to do that is to convert your Java Project to a Maven Project.  This only takes a second, you simply right click your project, go to the configuration option and then click “Convert to Maven Project”.

After you convert your project to a Maven Project you will notice a pom.xml file is automatically added to your project. All you have left to do is add the following element to this pom.xml file under the Project element.

<dependencies>
  <dependency>
     <groupId>com.pi4j</groupId>
     <artifactId>pi4j-core</artifactId>
     <version>1.1</version>
  </dependency>
</dependencies>

Now right click your project, go to the Maven menu and then click “Update Project”. Now you have the PI4J dependency in your project.  Now lets write some code!

Lets start by adding our Java class.  Right click your “src” folder and select “new” then select “class”.  We will name this new class “main”.

So the goal of this application will be to build a small console application that will turn the light on, wait 5 seconds and then turn the light off.

Now lets setup our Java app to run as a console application.  All we need to do is add this basic code.

public class main {
	  public static void main(String[] args) throws InterruptedException {
	        System.out.println("This is my console app");
	  }
}

Lets add our dependency to the application.

import com.pi4j.io.gpio.*;

Lets just jump in and add all of our code; I will explain what it all does below.

  public static void main(String[] args) throws InterruptedException {

        // intializing our gpio controller
        final GpioController gpio = GpioFactory.getInstance();

        //Turn the LED on
        System.out.println("Turning the LED ON.");
        // Wire up our GPIO 25 pin to a variable in our code
        // We are also turning on the LED with the PinState.HIGH parameter
        final GpioPinDigitalOutput pin = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_25, "LED-25", PinState.HIGH);

        // Lets leave the LED on for 5 seconds
        System.out.println("Waiting for 5 seconds before turning the LED off");
        Thread.sleep(5000);

        // turn off gpio pin #
        System.out.println("Turning the LED off");
        pin.low();
        
        // clean up tasks before we exit thie application
        gpio.shutdown();

        System.out.println("goodbye :)");
  }

We only have about 4 lines that do anything significant in the code above.

1.  final GpioController gpio = GpioFactory.getInstance();
This simply initialized our GPIO library so we can start interacting with the 40 pin connector on the Raspberry Pi

2.  final GpioPinDigitalOutput pin = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_25, “LED-25”, PinState.HIGH);
This is probably the most important thing to not only get right but understand what is going on.  What we are doing is simple; we are binding the “pin” to one of the 40 pins on the board.  This is key on how to understand which pin you are binding to.  Here is a “cheat sheet” that I found on the pi4j website; note that the GPIO number you need to use is labeled next to the value you actually see on the GPIO Extension Board. GPIO Cheat Sheet I would recommend printing this off for future projects

3.  pin.low();
We are turning the light off by essentially breaking the circuit.

4.  gpio.shutdown();
We need to clean up our resources and let go of any control we have acquired over the board so other processes can control this circuit.

We are done writing our code; now we just need to compile our application, transfer it to our Raspberry Pi and run it.


Lets compile our code!
We want to basically export our code into an executable JAR file.  Lets right click our project and select the “Export” option.
You will want to ensure that you are exporting this as a “Runnable Jar File” as show in the image below

When we click next we just want to select a run configuration and location to output our JAR file.  If you don’t have a configuration to select, the easiest was to create one is to just run the application in debug mode once.  Eclipse will automatically create one for you.

Now just click the “Finish” button and Eclipse will create your Jar file!


Lets transfer our application/JAR file!
Transferring the Jar file should be fairly basic as long as you enabled ssh on part 1 of this blog.  The first thing you need to do is figure out the IP Address of your Raspberry Pi, assuming it is on your network.  The easiest way to do this is to open a terminal and type “ifconfig”; you should be able to easily see the IP of your Pi from there.

Now that we have the IP Address of the Pi, on the device that has the Jar file, you need to transfer the file using sftp/ssh.  There are tons of tools for this; I personally prefer to use FileZilla.  When you launch FileZilla you can perform a “Quick Connect” and enter the following information.

Host:  {the IP you found from the instructions above}
Username: pi
Password: raspberry
Port: 22


Lets run our application!
Now that the Jar file is on the Raspberry Pi, lets hop back onto the Pi (or ssh in).  Open a new terminal and navigate to the directory that you transfered the Jar file to.  Now type the following command

sudo java -jar myjarfile.jar

You should now see your LED turn on and off!  The ONLY reason we had to run this with high level permission (sudo) is because the GPIO library requires that to interact with the hardware.

I hope this blog helped you understand the entire process better!  Honestly once you understand the basics taking it to the next level is a piece of cake/pi. (sorry for the incredibly dumb play on words).  My next Raspberry Pi will show you how to use sensors and the camera (Night vision/IR Camera).  In regards to code it is not much more and the concepts are almost identical to what we went over here.

Basics of the Raspberry Pi – Part 3
Part 1 – Basic Setup
Part 2 – How it all works 

Basics of the Raspberry Pi – How it all Works

Basics of the Raspberry Pi – Part 2
Part 1 – Basic Setup
Part 3 – Turning a light on and off 

How it all works – Part 2


Lets figure out how all of this comes together!  I promise once you do this once then everything will click and you will be off to bigger and better projects with the Raspberry Pi.  For now lets talk about a simple project; below is our 1,000 foot view of what we want to accomplish.  (All of these components where referenced in Part 1 of this blog)

This all seems fairly simple until you get to the breadboard and how/where too plug in your wires and components.   I can tell you that this is a fairly dummy proof process; I have plugged components into the wrong places and have yet to break anything.  I know I did something wrong when the Raspberry Pi immediately resets/reboots.  Just please be sure to understand your voltages and when to use resistors otherwise the components that you use could easily break/pop/die.

Ok, so to recap we have now performed the following steps and are ready to start interacting with the breadboard.

  1. Plugged our 40 Pin Cable into our Raspberry Pi
  2. Plugged the other end of the 40 Pin Cable into our GPIO Extension Board
  3. Seeded our GPIO Extension Board into our BreadBoard

Before we start plugging wires into the breadboard we need to understand how the GPIO Extension Board.  The Breadboard itself is really a super simplistic device; I have outlined how it works below.

This is a device designed to assist in the creation of completing circuits.  Basically every red line that is overlaying the breadboard represents a metal connection that ensures that all pin holes are inter-connected.

When you plug the GPIO Board into this, you really want to plug it in so that one half of the pins are on the right side and the second half are on the left side as shown in the picture below.

You can now start creating full circuits that connect different Pins on the GPIO Extension Board;  which is essentially the same thing as creating circuits directly on the 40 Pins on the Raspberry Pi device.  This is just the safe and easy way to do it.

The only thing left to do is build a complete circuit on the BreadBoard!  To Create a Complete Circuit we will perform the following steps:

  1. Plug one end of your resistor into the breadboard line that the GPIO 25 connector from the GPIO Extension Board aligns to; plug the other end of the resistor into a line on the breadboard that is free.
  2. On the same line the resistor connects to, plug in one end of your LED light
  3. Plug in the second end of the LED light into a line that aligns to a Ground pin “GRND” on the GPIO Extension Board.

When you are done then your breadboard should be similar to the image below.  There are infinite ways to create this circuit, just be sure to get that resistor into the circuit so you do not damage up your LED light.

Below is the same implementation as above.

We are ready to turn on our Raspberry Pi and start creating some code to control our circuit.  We will be using Java in this demo to control our LED light.  I am choosing Java not because it is the more suitable language for interacting with the Raspberry Pi but because it is the most popular language being used with this device.

Part 3 – Turning a light on and off (using Java)

Side note about using Java with the Raspberry Pi: I can tell you that I have already ran into instances that exposes the Java flaws with the Raspberry Pi but don’t fret too much; all shortcomings have easy work arounds.  I plan on creating a blog focused solely on this topic.

Basics of the Raspberry Pi – Part 2
Part 1 – Basic Setup
Part 3 – Turning a light on and off 

Basics of the Raspberry Pi – Setup

Basics of the Raspberry Pi – Part 1
Part 2 – How it all works 
Part 3 – Turning a light on and off 

Part 1: Raspberry Pi – Prototyping, Simple Lights and some Java


I kept hearing about the Raspberry Pi and all of the wonderful things you can do with it. It was time for me to roll up my sleeves and dig in with my first real project.  I can honestly say that I seriously struggled to find all of the information and documentation out there that I needed put together in a way that I could easily take it and run with it.  Well after many hours of tinkering I decided to write my own guide in words that makes sense to how my mind works.

In this blog I will go over everything you need to know about the Raspberry Pi from what to buy down to running some basic java code to turn on an led.

Here is what you need and more importantly; why you need it!  The total cost of all of this should not exceed $65 unless you cannot find #9 at a good price.

  1. Raspberry Pi – This is basically your computer
  2. Micro SD Card  – This is your hard drive that you will install your Operating System on
  3. 40 Pin Cable – This is used to connect to the Breakout Board (#4)
  4. GPIO Extension Board (Breakout Board) – This is placed on the BreadBoard and basically allows you to create controllable circuits with the Raspberry Pi
  5. BreadBoard – This is nothing more than a bunch of metal wires and pin holes for you to create circuits on using Jumper Cables that connect pins from the Breakout Board (I will explain in detail later)
  6. Resistor – This is here to reduce the voltage that will run through your LED; if not it may melt or pop!
  7. LED – This is your LED that basically will tell us if the circuit that we created is active or not.
  8. Ambition

Lets get started!  The first thing that we need to do is setup our Raspberry Pi.  This is probably the easiest part of the entire thing.  If your Raspberry Pi came with an SD card then it probably already has the OS installer setup.  You will need to download and install NOOBS onto your SD Card. NOOBS is an easy operating system installer which contains Raspbian which will be the Operating System that you interface with when running your code.

Once you download this file; simply unzip it onto your SD Card.  Now lets pop the SD Card in your Raspberry Pi and fire it up.  Your goal is to see a screen like this one. 

The next part is quiet easy; all you have to do is click the CheckBox for Raspbian and click install.  This process takes about 10-15 minutes or so.  
Once the install is finished the system will reboot and load up your brand new Raspbian GUI.

This base install is all loaded up with some of the tools you will need to start programming.  Most notably it already has Java SDK, VNC Server, SSH Server, and other countless developer tools.  Some of which you will need to enable through the rasp-config tool.  The easiest way to enable some of these tools is to open a new Terminal and type “sudo raspi-config”.  Once this menu appears, navigate to “Advanced Options”, this is where you can drill down into SSH and/or VNC and enable/disable these services.

Now that we have a working Raspberry Pi we can start adding all of the other components to it.   In part 2 of this Blog we will go over all of the components and how it all comes together.

Basics of the Raspberry Pi – Part 1
Part 2 – How it all works 
Part 3 – Turning a light on and off