Tag: guide

Staying Productive

Staying Productive

Background

I wrote a post a long while back about how I started to use Google Keep to get myself organized. Google Keep has been a go-to app for me on my phone for a long time now. I love using it to make lists of things, and I find it much more convenient than a paper notebook.

Don’t get me wrong–I think a paper notebook still has plenty of uses! I love my notebook for long running meetings with open-ended discussions or brain storming sessions. It’s great to be able to take a pen/pencil and doodle down any idea that comes to mind. When I’m having a free-form conversation, I need a free-form way to take notes.

However, my phone is something I almost always have with me–and my paper notebook isn’t. My phone allows me to take my Google Keep notes and email them to myself. It allows me to have a reminder right on my homescreen every time I unlock my phone. It’s just more convenient.

But something happened since the last time I wrote about using Google Keep. I use it more and more, and at some point I felt like I was getting less and less done. This is less about in the office and more about how productive I feel at home. So how can I be getting less done (or at least feeling that way) if I’m taking my own advice and using Google Keep to hack my TODO list?

I have tons of lists and no actions.

I think that’s the big take away. I list all the things I’m thinking about, and I keep making more lists. There’s no time frame around actioning things with the lists I’m making! So, in the spirit of continuous improvement, I set out to make some changes.

Inspiration

I know I wanted to make some changes with this part of my life because it was starting to weigh down on me; I didn’t feel productive. But I knew this wasn’t going to be something I’d answer over night. I kept my eyes and ears open for ideas for a little while before I thought up some tweaks.

The first thing I came across while living my alter ego was an Instagram post by Big J. Big J is this guy that’s incredibly big and incredibly strong. He’s lived the bodybuilding life and has a lot to show for it… And because being successful in the bodybuilding and strength world means being extremely motivated and hardworking, it’s no surprise I picked up this little bit from Big J:

Simple idea, right? Put some time into planning your schedule for the upcoming days. It almost seems to obvious to not be doing. I mean, don’t I do this already? I have meeting invites and stuff in my calendar for work… But, that’s right! I don’t have anything in my calendar for my own personal things that I like to do outside of work. Hmmm…

The next little tip to push me along was after a conversation with a teammate of mine at work. Our conversation was mostly about work-life balance, but my colleague was telling me about something he was trying out around forming habits. Essentially, over a period of time he’s been recording his success at keeping on top of good habits and identifying reasons why he’s sometimes missing them. Definitely right up the continuous improvement alley! Another great point he brought up was that good habits need to be introduced one at a time and only once you’ve been consistent with your other habits. By adding too much at once, you can derail the whole good habit process.

The “Staying Productive” Hack

This is the hack I’ve been implementing for a bit over a week now, and it’s helped tremendously with feeling productive!

Every night when I’m laying in bed, I spend about 5-15 minutes with my phone and I schedule personal activities in my calendar for the following day.

There it is. It’s not rocket science or something Earth shattering, but it’s definitely helping. Taking a page out of Big J’s book and a tip from my colleague, I’ve modified my schedule to introduce a very brief planning period every day. And it’s just one change that I think is helping introduce a good habit into my life.

This has helped me:

  • Stay on top of prepping food (which is a big part of the lifestyle I try to live)
  • Schedule time to relax (yes, I even schedule time for things like video games!)
  • Schedule time to blog (I run three blogs, and sometimes finding time to write feels like a chore)
  • Work on personal projects
  • … Feel like I’m being productive.

And no, I didn’t drop Google Keep–It actually helps feed into my scheduling! It’s great to look over my lists of things and try to create actions for them.

Next Steps

This simple hack is not only nothing particularly fancy, it’s also not bullet proof! But that’s okay when you’re always trying to continuously improve. Some snags I’ve run into or things I’ve thought about are:

  • How do I adjust my planned schedule when unexpected things come up? If someone drops in for a visit out of nowhere, or my car breaks down, or my dog decides to tear up the furniture, how do I make sure I can continue on with my planned schedule? Right now some things drop off the schedule or I push other things off to compensate. This hasn’t been too big of a problem so far, but sometimes this has a bit of a landslide effect and it makes the rest of the day feel unproductive. A little bit of dirt in the cogs seems to throw the whole thing off for me! This is something I’ll be thinking about as I encounter it and I’ll try to thing of some easy solutions.
  • How can I be more like Big J?! Aside from being bigger and stronger, how can I plan for more days? Big J plans every Sunday but I plan every night for the next day. Is there a happy medium? Planning every Sunday would potentially amplify the landslide effect I previously mentioned, but it would be a convenient single planning session for the whole week. Perhaps I’ll continue with the advice of my colleague and modify one part of my new habit at a time and look at planning for an extra day at a time and see how that goes!

If you’ve been making checklists and find that you’re unable to action items, try this approach! It takes only a few minutes every day, and so far I’ve been having great success in feeling productive. It’s not difficult, so it’s worth a try!


IronPython: A Quick WinForms Introduction

IronPython: A Quick WinForms Introduction

Background

A few months ago I wrote up an article on using PyTools, Visual Studio, and Python all together. I received some much appreciated positive feedback for it, but really for me it was about exploring. I had dabbled with Python a few years back and hadn’t really touched it much since. I spend the bulk of my programming time in Visual Studio, so it was a great opportunity to try and bridge that gap.

I had an individual contact me via the Dev Leader Facebook group that had come across my original article. However, he wanted a little bit more out of it. Since I had my initial exploring out of the way, I figured it was probably worth trying to come up with a semi-useful example. I could get two birds with one stone here–Help out at least one person, and get another blog post written up!

The request was really around taking the output from a Python script and being able to display it in a WinForm application. I took it one step further and created an application that either lets you choose a Python script from your file system or let you type in a basic script directly on the form. There isn’t any fancy editor tools on the form, but someone could easily take this application and extend it into a little Python editor if they wanted to.

Leveraging IronPython

In my original PyTools article, I mention how to get IronPython installed into your Visual Studio project. In Visual Studio 2012 (and likely a very similar approach for other versions of Visual Studio), the following steps should get you setup with IronPython in your project:

  • Open an existing project or start a new one.
  • Make sure your project is set to be at least .NET 4.0
    • Right click on the project within your solution explorer and select “Properties”
    • Switch to the “Application” tab.
    • Under “Target framework”, select  “.NET Framework 4.0”.
  • Right click on the project within your solution explorer and select “Manage NuGet Packages…”.
  • In the “Search Online” text field on the top right, search for “IronPython”.
  • Select “IronPython” from within the search results and press the “Install” button.
  • Follow the instructions, and you should be good to go!

Now that we have IronPython in a project, we’ll need to actually look at some code that gets us up and running with executing Python code from within C#. If you followed my original post, you’ll know that it’s pretty simple:


var py = Python.CreateEngine();
py.Execute("your python code here");

And there you have it. If it seems easy, that’s because it is. But what about the part about getting the output from Python? What if I wanted to print something to the console in Python and see what it spits out? After all, that’s the goal I was setting out to accomplish with this article. If you try the following code, you’ll notice you see a whole lot of nothing:


var py = Python.CreateEngine();
py.Execute("print('I wish I could see this in the console...')");

What gives? How are we supposed to see the output from IronPython? Well, it all has to do with setting the output Stream of the IronPython engine. It has a nice little method for letting you specify what stream to output to:


var py = Python.CreateEngine();
py.Runtime.IO.SetOutput(yourStreamInstanceHere);

In this example, I wanted to output the stream directly into my own TextBox. To accomplish this, I wrote up my own little stream wrapper that takes in a TextBox and appends the stream contents directly to the Text property of the TextBox. Here’s what my stream implementation looks like:


private class ScriptOutputStream : Stream
{
  #region Fields
  private readonly TextBox _control;
  #endregion

  #region Constructors
  public ScriptOutputStream(TextBox control)
  {
    _control = control;
  }
  #endregion

  #region Properties
  public override bool CanRead
  {
    get { return false; }
  }

  public override bool CanSeek
  {
    get { return false; }
  }

  public override bool CanWrite
  {
    get { return true; }
  }

  public override long Length
  {
    get { throw new NotImplementedException(); }
  }

  public override long Position
  {
    get { throw new NotImplementedException(); }
    set { throw new NotImplementedException(); }
  }
  #endregion

  #region Exposed Members
  public override void Flush()
  {
  }

  public override int Read(byte[] buffer, int offset, int count)
  {
    throw new NotImplementedException();
  }

  public override long Seek(long offset, SeekOrigin origin)
  {
    throw new NotImplementedException();
  }

  public override void SetLength(long value)
  {
    throw new NotImplementedException();
  }

  public override void Write(byte[] buffer, int offset, int count)
  {
    _control.Text += Encoding.GetEncoding(1252).GetString(buffer, offset, count);
  }
  #endregion
}

Now while this isn’t pretty, it serves one purpose: Use the stream API to allow binary data to be appended to a TextBox. The magic is happening inside of the Write() method where I take the binary data that IronPython will be providing to us, convert it to a string via code page 1252 encoding, and then append that directly to the control’s Text property. In order to use this, we just need to set it up on our IronPython engine:


var py = Python.CreateEngine();
py.Runtime.IO.SetOutput(new ScriptOutputStream(txtYourTextBoxInstance), Encoding.GetEncoding(1252));

Now, any time you output to the console in IronPython you’ll get your console output directly in your TextBox! The ScriptOutputStream implementation and calling SetOutput() are really the key points in getting output from IronPython.

The Application at a Glance

I wanted to take this example a little bit further than the initial request. I didn’t just want to show that I could take the IronPython output and put it in a form control, I wanted to demonstrate being able to pick the Python code to run too!

Firstly, you’re able to browse for Python scripts using the default radio button. Just type in the path to your script or use the browse button:

IronPython - Run script from file

Enter a path or browse for your script. Press “Run Script” to see the output of your script in the bottom TextBox.

Next, press “Run Script”, and you’re off! This simply uses a StreamReader to get the contents of the file and then once in the contents are stored in a string, they are passed into the IronPython engine’s Execute() method. As you might have guessed, my “helloworld.py” script just contains a single line that prints out “Hello, World!”. Nothing too fancy in there!

Let’s try running a script that we type into the input TextBox instead. There’s some basic error handling so if your script doesn’t execute, I’ll print out the exception and the stack trace to go along with it. In this case, I tried executing a Python script that was just “asd”. Clearly, this is invalid and shouldn’t run:

python_error_asd

Python interpreted the input we provided but, as expected, could not find a definition for “asd”.

That should be along the lines of what we expected–The script isn’t valid, and IronPython tells us why. What other errors can we see? Well, the IronPython engine will also let you know if you have bad syntax:

python_error_bad_syntax

Python interpreted the script, but found a syntax error in our silly input.

Finally, if we want to see some working Python we can do some console printing. Let’s try a little HelloWorld-esque script:

python_pass_hello_world

Python interpreted our simple Hello World script.

Summary

This sample was pretty short but that just demonstrates how easy it is! Passing in a script from C# into the IronPython is straight forward, but getting the output from IronPython is a bit trickier. If you’re not familiar with the different parts of the IronPython engine, it can be difficult to find the things you need to get this working. With a simple custom stream implementation we’re able to get the output from IronPython easily. All we had to do was create our own stream implementation and pass it into the SetOutput() method that’s available via the IronPython engine class. Now we can easily hook the output of our Python scripts!

As always, all of the source for you to try this out is available online:

Some next steps might include:

  • Creating your own Python IDE. Figure out some nice text-editing features and you can run Python scripts right from your application.
  • Creating a test script dashboard. Do you write test scripts for other applications in Python? Why not have a dashboard that can report on the results of these scripts?
  • Add in some game scripting! Sure, you could have done this with IronPython alone, but maybe now you can skip the WinForms part of this and just make your own stream wrapper for getting script output. Cook up some simple scripts in a scripting engine and voila! You can easily pass information into Python and get the results back out.

Let me know in the comments if you come up with some other cool ideas for how you can leverage this!


Fragments: Creating a Tabbed Android User Interface

Fragments: Creating a Tabbed Android User Interface

Fragments: A Little Background

Update: The actual application is available on the Google Play store.

Once upon a time, Android developers used only two things called activities and views in order to create their user interfaces. If you’re like me and you come from a desktop programming environment, an Activity is sort of like a form or a window. Except it’s more like a controller for one of these classes. With that analogy in place, a view is then similar to a control. It’s the visual part you’re interacting with as a user. I remember the learning curve being pretty steep for me being so stuck in my desktop (C# and WPF) development, but once I came up with these analogies on my own, it seemed pretty obvious. So to make an Android application, one would simply put some views together and chain some activities to show these views. Pretty simple.

Something changed along the way though. It was apparent that the Activity/View paradigm was a bit lacking so something new was added to the mix: The Fragment. Fragments were introduced in Android 3.0 (which is API level 11). Fragments added the flexibility to be able to swap out parts of an activity without having to completely redefine the whole view. This means that having an application on a mobile phone with a small screen can appear differently than when it’s on a large tablet, and as a developer you don’t have to redesign the whole bloody thing. Awesome stuff!

So, to clarify, a fragment is just a part of the activity. By breaking up activities into fragments, you get the modular flexibility of being able to swap in and out components at will. If you’re like me and you took a break from Android when fragments were introduced, then you may have another little learning curve. The goal of this article is to create a tabbed Android user interface using fragments.

For what it’s worth, when I first tried putting together a tabbed UI with fragments, it was a complete mess. I was surfing the net for examples, but I couldn’t find anything that really hit it home for me. Once I had it working, I decided I should redo it and document the process. That’s how this article came to be! Another side note… I’m a C# developer by trade and I haven’t developed with Android/Java within a team. If you don’t like my coding conventions then please try to look past that to get the meat of the article!

As per usual, you can follow along by downloading all of the code ahead of time. Please check out the section at the end of the article and pick whichever option you’d like to get the source!

Setting Up: Getting Your Project Together

I’m going to make a few assumptions here. You should have Eclipse installed with the latest Android Development Tools. There are plenty of examples out there for how to get your environment put together, but I’m not going to cover that here.

You’re going to want to start by making a new Android Application in eclipse. By going to the “File” menu, then the “New” sub menu, then the “Other” sub menu, you should get a dialog letting you pick Android application. You’ll get a wizard that looks like the following (where I’ve filled in the information with what I’ll be using for this entire example):

Tab Fragment Tutorial - New Android Application

The first part of the wizard is setting up your Android project.

The wizard gives you some options for what you want to have it generate for you. In this case, I opted out of having a custom icon (since that’s not really important for this tutorial) and I chose to have it create an activity for me.

Tab Fragment Tutorial - Create Activity

The second step in the wizard lets you choose what to create. I wanted just the activity made.

Our activity is actually going to be pretty light-weight. The bulk of what we’re going to be doing is going to be inside of our fragments. Because of this, we should be totally fine just making our main activity a simple blank activity.

Tab Fragment Tutorial - Create Blank Activity

We won’t have much code in our main activity. Let’s just opt for the blank activity.

The final step in the wizard just wants you to confirm the naming for your generated code.

Tab Fragment Tutorial - Activity Naming

Let’s create our “MainActivity” activity with a layout called “activity_main”. Pretty straight forward.

At this point, we actually have an Android application that we can deploy to a phone or a virtual device. If you’re new to Android programming, I suggest you try it out. It’s pretty exciting to get your first little application running.

The Layouts

The layout XML files in Android provide the hierarchies of views that will get shown in the UI. If you haven’t modified the one that was created by default, it will probably look like this:

Tab Fragment Tutorial - Initial Main Activity Layout XML

The default Main Activity XML will look like this. It’s really just a text view that says “Hello World”.

What does that give us? Well, we get a RelativeLayout view that acts as a container for a TextView. The TextView says “Hello World”. Amazing, right?

Let’s switch up our main activity’s layout a bit. Instead of a RelativeLayout, let’s drop in a linear layout that has a vertical orientation. We’ll blow away the TextView too, and drop in a Fragment. Our fragment will need to point to our custom fragment class (which we haven’t created yet). For now, make the class “com.devleader.tab_fragment_tutorial.TabsFragment”. Later in the example, we’ll create the TabsFragment class and put it within this package. When the application runs, it will load up our custom fragment (specified by the full class name) and place it within our LinearLayout.

The layout XML for the main activity looks like the following:


<LinearLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent">

 <fragment
 class="com.devleader.tab_fragment_tutorial.TabsFragment"
 android:id="@+id/tabs_fragment"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent" />
</LinearLayout>

We’re going to need a layout for our tabs fragment. This is going to be the view portion of the UI that gets dropped in to our main activity. It’s going to be responsible for showing the tabs at the top of the UI and then providing container views for the contents that each tab will want to show.

In order to create this layout, right click on your “layout” folder nested within the “res” folder in the Eclipse IDE. Go to “new”, and then click on the “Other” child menu. Pick “Android XML Layout File” from your list of options. Select “TabHost” as the layout’s root element. Let’s call this file “fragment_tabs.xml”.

The top level component in this layout will be a TabHost. We’ll put our TabWidget in next, which is going to contain the actual tab views, and then a FrameLayout with two nested FrameLayouts inside of it for holding the contents that we want to show for each tab. To clarify, the user will be clicking on views within the TabWidget to pick the tab, and the contents within the tab1 and tab2 FrameLayouts will show the corresponding user interface for each tab.

The layout XML for the tabs fragment looks like the following:


<TabHost
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@android:id/tabhost"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:background="#EFEFEF">

 <LinearLayout
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent">

 <TabWidget
 android:id="@android:id/tabs"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content" />

 <FrameLayout
 android:id="@android:id/tabcontent"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent">

 <FrameLayout
 android:id="@+id/tab1"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:background="#FFFF00" />

 <FrameLayout
 android:id="@+id/tab2"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:background="#FF00FF" />

 </FrameLayout>
 </LinearLayout>
</TabHost>

You may have noticed I used some pretty aggressive hard-coded colors in the layout file. I highly advise you switch these to be whatever you want for your application, but when I’m debugging UI layouts I like to use really high contrasting colors. This helps me know exactly where things are (as opposed to having 10 views all with the same background). Maybe I’m a bit crazy, but I find it really helpful.

Now that we have the main activity done and the tab fragment all set up, the last thing we need is to create some sort of layout for our individual tab views. This will be the view that is placed inside of the TabWidget on our tabs fragment layout. These views will have the title of the tab and they’ll be what the user actually interacts with in order to switch tabs.

The layout XML for our simple tab view looks like the following:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:orientation="vertical" >

<TextView
 android:id="@+id/tabTitle"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

And that’s it for layouts! Just these three simple files. Now, we need to fill out our classes!

The Classes

If we start from the beginning with the classes, the first (and only) class that gets generated for you is the MainActivity class. If you left it untouched (hopefully you did since there was no indication to change it yet!) then you should have a class that looks like:

Tab Fragment Tutorial - Initial Main Activity Class

The default MainActivity class that gets generated after we complete the steps in the wizard.

In order to make this example work, we barely even need to modify this class at all. You’ll notice our MainActivity extends the Activity class. Because we’re going to be using fragments in our application, we need to modify this class to extend the FragmentActivity. In this entire example, I opted to use the Android v4 Support Library. Thus, in order to make this example work, please ensure you’re using FragmentActivity from the package “android.support.v4.app.FragmentActivity“.

Once you’ve made this replacement (“Activity” for “FragmentActivity”) we’re all done in this class. Great stuff, right? Let’s move on.

We’re going to want to make a class that defines what a tab is. In order to make some nice re-usable code that you can extend, I decided to make a base class that defines minimum tab functionality (at least in my opinion). Feel free to extend upon this class later should your needs exceed what I’m offering in this tutorial.

The base TabDefinition class will:

  • Take in the ID of the view where the tab’s content will be put. In our example, this will be the ID for tab1 or tab2’s FrameLayout.
  • Provide a unique identifier to look up the tab.
  • Be required to provide the Fragment instance that will be used when the tab is activated.
  • Be required to create the tab view that the user will interact with in order to activate the tab.

Let’s add a new class called “TabDefinition” to the package “com.devleader.tab_fragment_tutorial”, just like where our MainActivity class is. The code for the TabDefinition class is as follows:


package com.devleader.tab_fragment_tutorial;

import java.util.UUID;

import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * A class that defines a UI tab.
 */
public abstract class TabDefinition {
 //
 // Fields
 //
 private final int _tabContentViewId;
 private final String _tabUuid;

 //
 // Constructors
 //
 /**
 * The constructor for {@link TabDefinition}.
 * @param tabContentViewId The layout ID of the contents to use when the tab is active.
 */
 public TabDefinition(int tabContentViewId) {
   _tabContentViewId = tabContentViewId;
   _tabUuid = UUID.randomUUID().toString();
 }

 //
 // Exposed Members
 //
 /**
 * Gets the ID of the tab's content {@link View}.
 * @return The ID of the tab's content {@link View}.
 */
 public int getTabContentViewId() {
   return _tabContentViewId;
 }

 /**
 * Gets the unique identifier for the tab.
 * @return The unique identifier for the tab.
 */
 public String getId() {
   return _tabUuid;
 }

 /**
 * Gets the {@link Fragment} to use for the tab.
 * @return The {@link Fragment} to use for the tab.
 */
 public abstract Fragment getFragment();

 /**
 * Called when creating the {@link View} for the tab control.
 * @param inflater The {@link LayoutInflater} used to create {@link View}s.
 * @param tabsView The {@link View} that holds the tab {@link View}s.
 * @return The tab {@link View} that will be placed into the tabs {@link ViewGroup}.
 */
 public abstract View createTabView(LayoutInflater inflater, ViewGroup tabsView);
}

Now that we have the bare-minimum definition of what a tab in our UI looks like, let’s make it even easier to work with. In my example, I just want to have my tabs have a TextView to display a title–They’re really simple. I figured I’d make a child class of TabDefinition called SimpleTabDefinition. The goal of SimpleTabDefinition is really just to provide a class that takes the minimum amount of information to get a title put onto a custom view.

Please keep in mind that there are many ways to accomplish what I’m trying to illustrate here, but I personally felt having a base class with a more specific child class would help illustrate my point. You could even put in a second type of child class that would make a graphical tab that shows a graphical resource instead of a string resource. Tons of options!

Let’s add another new class called “SimpleTabDefinition” to the package “com.devleader.tab_fragment_tutorial”. The code for SimpleTabDefinition is as follows:


package com.devleader.tab_fragment_tutorial;

import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;

/**
 * A class that defines a simple tab.
 */
public class SimpleTabDefinition extends TabDefinition {
  //
  // Fields
  //
  private final int _tabTitleResourceId;
  private final int _tabTitleViewId;
  private final int _tabLayoutId;
  private final Fragment _fragment;

  //
  // Constructors
  //
  /**
  * The constructor for {@link SimpleTabDefinition}.
  * @param tabContentViewId The layout ID of the contents to use when the tab is active.
  * @param tabLayoutId The ID of the layout to use when inflating the tab {@link View}.
  * @param tabTitleResourceId The string resource ID for the title of the tab.
  * @param tabTitleViewId The layout ID for the title of the tab.
  * @param fragment The {@link Fragment} used when the tab is active.
  */
  public SimpleTabDefinition(int tabContentViewId, int tabLayoutId, int tabTitleResourceId, int tabTitleViewId, Fragment fragment) {
    super(tabContentViewId);

    _tabLayoutId = tabLayoutId;
    _tabTitleResourceId = tabTitleResourceId;
    _tabTitleViewId = tabTitleViewId;
    _fragment = fragment;
  }

  //
  // Exposed Members
  //
  @Override
  public Fragment getFragment() {
    return _fragment;
  }

  @Override
  public View createTabView(LayoutInflater inflater, ViewGroup tabsView) {
    // we need to inflate the view based on the layout id specified when
    // this instance was created.
    View indicator = inflater.inflate(
      _tabLayoutId,
      tabsView,
      false);

    // set up the title of the tab. this will populate the text with the
    // string defined by the resource passed in when this instance was
    // created. the text will also be centered within the title control.
    TextView titleView = (TextView)indicator.findViewById(_tabTitleViewId);
    titleView.setText(_tabTitleResourceId);
    titleView.setGravity(Gravity.CENTER);

    // ensure the control we're inflating is layed out properly. this will
    // cause our tab titles to be placed evenly weighted across the top.
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
      LayoutParams.WRAP_CONTENT,
      LayoutParams.WRAP_CONTENT);
    layoutParams.weight = 1;
    indicator.setLayoutParams(layoutParams);

    return indicator;
  }
}

Awesome stuff. Now we can define tabs easily in our application. We just have one more class left, I promise! In the following section, I’ll re-iterate over everything, so if you’re feeling a bit lost… Just hang in there.

The one part we’re actually missing is the fragment that will manage all of our tabs. We created the layout for it already, which has a TabHost, a TabWidget (to contain the clickable tab views), and some FrameLayouts (that contain the content we show when we press a tab). Now we just need to actually attach some code to it!

The TabsFragment class that we’re going to want to add to the package “com.devleader.tab_fragment_tutorial” is responsible for a few things. First, we’re going to be defining our tabs in here. This class will be responsible for taking those tab definitions and creating tabs that get activated via the TabHost. As a result, this fragment class is going to have to implement the OnTabChangedListener interface. This will add a method where we handle switching the fragment shown to match the fragment for the contents of the tab that was pressed.

The code for our TabsFragment class looks like the following:

package com.devleader.tab_fragment_tutorial;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;

/**
 * A {@link Fragment} used to switch between tabs.
 */
public class TabsFragment extends Fragment implements OnTabChangeListener {
  //
  // Constants
  //
  private final TabDefinition[] TAB_DEFINITIONS = new TabDefinition[] {
    new SimpleTabDefinition(R.id.tab1, R.layout.simple_tab, R.string.tab_title_1, R.id.tabTitle, new Fragment()),
    new SimpleTabDefinition(R.id.tab2, R.layout.simple_tab, R.string.tab_title_2, R.id.tabTitle, new Fragment()),
   };

  //
  // Fields
  //
  private View _viewRoot;
  private TabHost _tabHost;

  //
  // Exposed Members
  //
  @Override
  public void onTabChanged(String tabId) {
    for (TabDefinition tab : TAB_DEFINITIONS) {
      if (tabId != tab.getId()) {
        continue;
      }

      updateTab(tabId, tab.getFragment(), tab.getTabContentViewId());
      return;
    }

    throw new IllegalArgumentException("The specified tab id '" + tabId + "' does not exist.");
  }

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    _viewRoot = inflater.inflate(R.layout.fragment_tabs, null);

    _tabHost = (TabHost)_viewRoot.findViewById(android.R.id.tabhost);
    _tabHost.setup();

    for (TabDefinition tab : TAB_DEFINITIONS) {
      _tabHost.addTab(createTab(inflater, _tabHost, _viewRoot, tab));
    }

    return _viewRoot;
  }

  @Override
  public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    setRetainInstance(true);

    _tabHost.setOnTabChangedListener(this);

    if (TAB_DEFINITIONS.length > 0) {
      onTabChanged(TAB_DEFINITIONS[0].getId());
    }
  }

  //
  // Internal Members
  //
  /**
  * Creates a {@link TabSpec} based on the specified parameters.
  * @param inflater The {@link LayoutInflater} responsible for creating {@link View}s.
  * @param tabHost The {@link TabHost} used to create new {@link TabSpec}s.
  * @param root The root {@link View} for the {@link Fragment}.
  * @param tabDefinition The {@link TabDefinition} that defines what the tab will look and act like.
  * @return A new {@link TabSpec} instance.
  */
  private TabSpec createTab(LayoutInflater inflater, TabHost tabHost, View root, TabDefinition tabDefinition) {
    ViewGroup tabsView = (ViewGroup)root.findViewById(android.R.id.tabs);
    View tabView = tabDefinition.createTabView(inflater, tabsView);

    TabSpec tabSpec = tabHost.newTabSpec(tabDefinition.getId());
    tabSpec.setIndicator(tabView);
    tabSpec.setContent(tabDefinition.getTabContentViewId());
    return tabSpec;
  }

  /**
  * Called when switching between tabs.
  * @param tabId The unique identifier for the tab.
  * @param fragment The {@link Fragment} to swap in for the tab.
  * @param containerId The layout ID for the {@link View} that houses the tab's content.
  */
  private void updateTab(String tabId, Fragment fragment, int containerId) {
    final FragmentManager manager = getFragmentManager();
    if (manager.findFragmentByTag(tabId) == null) {
      manager.beginTransaction()
        .replace(containerId, fragment, tabId)
        .commit();
    }
  }
}

And that’s it! Just four classes in total, and one of them (MainActivity) was almost a freebee!

Putting It All Together

Let’s recap on all of the various pieces that we’ve seen in this example. First, we started with the various layouts that we’d need. Our one and only activity is pretty bare bones. It’s going to contain our tabs fragment view. The tabs fragment view is responsible for containing the individual tabs a user clicks on as well as the content that gets displayed for each tab. We also added a layout for really simplistic tab views that only really contain a TextView that shows the tab’s title.

From there, we were able to look at the classes that would back up the views. To use our fragment implementation, we only had to modify our parent class of our only activity. I opted to create some classes that define tab functionality to make extending the UI a bit easier, and adding additional child classes that fit in this pattern is simple. The TabsFragment class was the most complicated part of our implementation, and truth be told, that’s where most of the logic resides. This class was responsible for defining the tabs we wanted to show, and what fragments we would swap in when each tab was clicked.

In order to extend this even more, the things you’ll want to consider are:

  • Defining your own type of tab definition classes. Maybe you want to look at graphical tabs, or something more complicated than just a title.
  • Implementing your own fragment classes that you display when your tabs are clicked. In the example, the contents of the tabs are empty! This is definitely something you’ll want to extend upon.
  • Adding more tabs! Maybe you need three or four tabs instead of two.

Summary

Fragments in Android really aren’t all that complicated. As a new Android developer or transitioning from the pre-API level 11 days, they might seem a bit odd. Hopefully after you try out this example they’re a lot more clear. Hopefully by following along with this tutorial you found that you were easily able to set up a tabbed user interface in Android and get a basic understanding for how fragments work.

Source and Downloads

I like being able to provide the source in as many formats as possible… so here we go:

Update: The actual application is available on the Google Play store.


Code Smells – Issue Number 2

Code Smells (Image from http://www.sxc.hu/)

Code Smells

Welcome to the second edition of Code Smells! Periodically I’ll be posting about how to detect code smells and what they mean in terms of the big picture of your code. The previous installment can be found right here.

What’s a code smell? Wikipedia says it perfectly:

In computer programming, code smell is any symptom in the source code of a program that possibly indicates a deeper problem. Code smells are usually not bugs—they are not technically incorrect and don’t currently prevent the program from functioning. Instead, they indicate weaknesses in design that may be slowing down development or increasing the risk of bugs or failures in the future.

Onto the code smells!

The Stink List

Code Smell #4: (Thanks to reddit user fkaginstrom) You have an large number of parameters being passed in to your function call. Functions that take in a ton of parameters stink for a few reasons. How many is too many though? This is a topic that people have debated all over The Internet. This Stack Overflow answer even quotes an author saying to never have more than three parameters in a function. In my opinion? There’s no fixed number. It’s going to vary from situation to situation, project to project, class to class, and method to method. Putting a fixed number on it is sort of setting up a rule to be broken.

What can you do to avoid this kind of smell? This C#-based Stack Overflow thread has a bunch of great ideas. One simple solution is just to bundle things into logical groupings of data. An example (although, it’s potentially a poor example since it’s only two parameters) is x and y coordinates. You can bundle these into a custom point type and pass this into functions. Now a function that may have taken four pairs of coordinates is reduced from eight parameters down to four. This approach also introduces the dependency on your custom type for your function, but I’m just offering it up as an option. If you’re always passing around the same group of X pieces of data around, it may make sense to bundle them into a single container type.

A side effect of reducing the number of parameters your functions require is readability. It might seem minimal, but having functions with only a handful of parameters keeps them from becoming unwieldy and much easier to understand when scanning through code. Readability is sometimes overlooked by developers, but when you’re in a team (and most developers work in teams), it goes a long way.

Code Smell #5: (Thanks to reddit user fkaginstrom) Your class has a large number of methods. If we keep the Single Responsibility Principle in mind (which states that a class should have one reason to change), it’s a warning sign that we might be creeping in on violating it. How? If more and more methods keep getting added, more responsibilities/capabilities can sneak in. This MSDN blog article also highlights some examples of the Single Responsibility Principle. Essentially, as the methods within your class grow in numbers, your class becomes responsible for more types of things. If you later on want to use  just one of those things in a different context, you’re now required to use one big heavy-weight type. Of course, this heavy-weight type comes with it’s own bundle of dependencies, setup requirements, and so on.

How do you avoid this? You can start by refactoring your monstrous type into multiple types. If your type has 12 methods that it defines, and they fall under three general categories of functionality, consider making three interfaces to group the functionality. Then you might consider adding three classes that stay true to these interfaces. The MSDN article I mentioned before does a good job of explaining  how this kind o approach works.

Code Smell #6: Your single method has grown to hundreds of lines. This is one code smell I find that newer programmers introduce more frequently than experienced programmers. However, when you’re working on an enormous code-base, sometimes this type of thing sneaks right up on you. So what’s the problem with having one method do a ton of things? It’s a convenience, isn’t it? let’s say someone only has to call one method that can launch a rocket, play golf, and invest in the stock market while filming a block-buster movie. That’s power and ease of use, no?

This related to Code Smell #5, in my opinion. The convenience of being able to call a method that does all sorts of fancy things at once is the exact inverse of the problem you face when you want to test the method. If I just want to test that I can successfully start the burners in the rocket, I have no choice but to call the method that does everything. What makes this problem even worse is that once your code has been structured this way, breaking down big methods into smaller methods can prove to be a challenge. When you see how dependencies are passed down the call hierarchy, or where certain classes have knowledge of others, things become scary.

I’ll give one real life example of something I saw recently in a particular code base. A test had to be written to cover a problematic area of code that had been refactored. There needed to be some sort of verification in code that proved this section was behaving as expected under particular conditions. Great stuff. Except the section of code existed inside of a method that did the following:

  • UI interaction
  • Database read
  • Data processing
  • File read
  • Data processing 2
  • Database write
  • External disk operation* (This one was pretty specific to the project I’m describing, but it wasn’t just a simple file read/write)
  • File write
  • UI interaction

Where the highlighted “Data processing 2” is the section of the method that needed testing. How’s that for fun? In order to test this one section properly it required refactoring of all of the encompassing code so that we could test it as a unit.

Have your own code smells? Share them in the comments. Follow Dev Leader on social media outlets to see code smell updates as they come out!

Nick Cosentino – LinkedIn
Nick Cosentino – Twitter
Dev Leader – Facebook
Dev Leader – Google+


Code Smells – Issue Number 1

Code Smells (Image from http://www.sxc.hu/)

Background

I thought this might be kind of fun (fun can also be read as “upsetting”), so I’m giving it a shot. It’s pretty frequent as programmers we go back and revisit some code and find ourselves shaking our heads at what we see. These code smells often don’t show their faces when they’re being created, so don’t beat yourself (or anyone else) up just yet. Common signs you’ve stumbled upon a code smell are when you find yourself saying:

How could that co-op have possibly coded this?! Blast those interns!

Or

What the heck was John thinking when he put this together?! Does he not have a brain?!

Or

No wonder we find so many bugs in this part of code! Look what Jane did!

But it never truly hits home until you get one of these:

What is this crap?! This is by far the worst code I have ever seen. How cou–Oh. Wait. I did that.

Code is always a work in progress. If it’s not, it’s because you’re writing a one off script or your code doesn’t do much of anything. Our skills as programmers are always transforming as are our perspectives. You’re guaranteed to have one of these moments if you’re programming long enough and look back on your code that was once The Pinnacle of Awesome.

With that said, I’m hoping to share some code smells that come up as I see them in my own projects or when talking with friends/colleagues. You might be about to type up one of these code smells, so pay attention! I don’t know how frequently I’ll put one of these posts together, but I might as well start now. Every time I get a handful of code smells I’ll try to push something out to The Interwebz.

The Stink List

Code Smell #1: Your variable is named or prefixed with “temp”, “tmp”, or some variation of “temporary”. This is unnecessary. If you have a variable, by definition it’s something that’s temporary. Nothing in code lasts for forever. You’re just lengthening a variable name or not putting enough thought into a good name.

Code Smell #2: Your variable is one character long. The exception to this is probably for simple loops. You almost always see code that is iterating over a counting variable “i”. Maybe that’s not so bad. If you nest three loops and you have for i, j, and k, things can get messy. If you find you’re using single character names outside of loops… STOP. Just name your variable something that won’t be a puzzle for someone one day from now.

Code Smell #3: You prefix things as “New”, “First”, “Last”, or some other definitive/completely ambiguous position. If you have something that’s “Newest” now and then tomorrow a new one is made, you now have to go change all of your code that used “Newest”, because it’s not the newest now. Same with something like “old” or “new”. It’s the “old” one now, but what happens when your “new” one becomes old because of a third generation? Now you have two olds and a new. What the heck are you going to do? Pick a good name from the start.

Have your own code smells? Share them in the comments. Follow Dev Leader on social media outlets to see code smell updates as they come out!

Nick Cosentino – LinkedIn
Nick Cosentino – Twitter
Dev Leader – Facebook
Dev Leader – Google+


Python, Visual Studio, and C#… So. Sweet.

Python, Visual Studio, and C#

Python & C# – Background

Let’s clear the air. Using Python and C# together isn’t anything new. If you’ve used one of these languages and at least heard of the other, then you’ve probably heard of IronPython. IronPython lets you use both C# and Python together. Pretty legit. If you haven’t tried it out yet, hopefully your brain is starting to whir and fizzle thinking about the possibilities.

My development experiences is primarily in C# and before that it was VB .NET (So I’m pretty attached to the whole .NET framework… We’re basically best friends at this point). However, pretty early in my career (my first co-op at Engenuity Corporation, really) I was introduced to Python. I had never really used a dynamic or implicitly typed language, so it was quite an adventure and learning experience.

Unfortunately, aside from my time at EngCorp, I hadn’t really had a use to continue on with Python development. Lately, I’ve had a spark of curiosity. I’m comfortable with C#, sure, but is that enough? There’s lots of great programming languages out there! It’s hard for me to break out of my comfort zone though. I’m used to C# and the awesomeness of Visual Studio, so how could I ever break free from these two things?

Well… I don’t have to yet.

Python Tools for Visual Studio

This was a nice little treasure to stumble upon:

But I didn’t really know what it was all about. I had heard of IronPython, and I knew I could use Python with C# together, so what exactly is “Python Tools“?

After I watched the video that the Visual Studio team tweeted out, I was captivated. Did this mean I could revisit python without having to leave the comfort of my favourite IDE? You bet. First thing I did after watching this video (and yes, I somehow managed to hold back the excitement and wait until the video was done) was fire up Visual Studio. I run with Visual Studio 2012 (the dark theme too) so in my screenshots that’s what you’ll be seeing. Once Visual Studio has loaded:

  • Go to the “Tools” menu at the top of the IDE.
  • Select the “Extensions and Updates…” menu item.
  • You should see the “Extensions and Updates” dialog window now.

You’re going to want to search for “Python Tools” after you’ve selected the “Online” option on the left side of the dialog. It should look something like this:

Python Tools - Visual Studio Extensions and Updates

Installing Python Tools for Visual Studio is pretty easy. Make sure you’re searching online and search for “Python Tools”.

After you’ve followed all of the installation instructions, it’s time to make sure the installation worked. Simple enough!

  • Go to the “File” menu at the top of the IDE.
  • Go to the “New” menu item.
  • Select the “Project…” menu item.
  • You should now see the “New Project” dialog

To ensure Python is now available, try seeing if you have Python project templates available:

Verify Python in Visual Studio

To verify that Python is now available in Visual Studio, check under the installed templates. It should be under “Other Languages”.

Hopefully it’s there. If not, or if you have any other install questions, I highly recommend you refer to the official site and follow along there. This is what got me up and running with my current machine, but if your setup is slightly different you should definitely follow their instructions. That’s it! You have Python Tools! But what else would make your C#, Python, and Visual Studio experience EVEN BETTER? The answer to that question is of course IronPython. Head on over to this page and get yourself setup with the latest cut of IronPython. Once that’s setup, you should have all the fancy tools you need!

Print to Console – Your First C#/Python Application

I’m sure you feel the excitement building. I’ll start by saying the code is all available online, so even though I’ll have snippets and pictures here, you can download all of the source and follow along that way if you want. Otherwise, I’ll do my best to walk you through how I set things up! This application is going to be pretty simple. It’s a tiny bit bigger than a “Hello World” application, with the difference being that you tell Python what you want to print to the console. Easy-peasy, right?

First up, let’s make a new C# console project.

  • From Visual Studio, go to the “File” menu at the top of the IDE.
  • Select the “New” menu item.
  • Select the “Project” menu item.
  • You should see the “New Project” dialog.
  • Select the “Visual C#” template on the left of the dialog.
  • Select “Console Application”.
  • In the framework dropdown at the top of the dialog, select .NET 4.5
  • Fill in the details for where you want to save your project.
  • Press “OK”! And we’re off!

Now that you have a console application you’re going to want to add in all the dependencies we need. If you look at the project in your solution explorer, you’re going to want to add the following dependencies:

IronPython Dependencies in Visual Studio

Add the IronPython and Microsoft.Scripting dependencies through the solution explorer in Visual Studio.

If you’re having trouble getting the dependencies set up, remember you can always download the source projects I’ve put together. Now that you have all the necessary dependencies, here’s the source for our little application:

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;

using IronPython.Hosting;

namespace PrintToConsole
{
    internal class Program
    {
        private static void Main()
        {
            Console.WriteLine("What would you like to print from python?");
            var input = Console.ReadLine();

            var py = Python.CreateEngine();
            try
            {
                py.Execute("print('From Python: " + input + "')");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Oops! We couldn't print your message because of an exception: " + ex.Message);
            }

            Console.WriteLine("Press enter to exit...");
            Console.ReadLine();
        }
    }
}

Let’s walk through what this code is doing:

  • First we’re getting input from the user. This is some pretty basic C# stuff, but we’re simply printing a message to the console and taking in the text the user enters before they press enter.
  • Next, we create a Python engine instance. This is the class that’s going to be responsible for executing python for us!
  • The code that exists within the try block tells our engine instance to execute some python code.
    • The print() method that you see being passed to the engine is the syntax since Python 3.0.
    • The parameter that we’re passing into the print() method is a python string… but we’re sticking our user input inside of it as well!
    • It’s also important to note that we’re building up a C# string that contains all of the Python code that will be executed and passing that to the engine.
  • I have a catch block here to catch any unexpected problems. Can you think of any?
    • What happens if your user input some text with a single quote?
  • The last part of the application just asks the user to press enter when they are all done.

Simple! There’s your first C# + Python application! You can see the source for the whole thing over here.

Run External Script

So this is great: you can now run some python code from within C#. Totally awesome. But what about all those python scripts you have written up already? Do you need to start copying and pasting them into C# code files and start to try and format them nicely? The answer is no, thankfully! Let’s start by following the exact same steps as outlined in the first example. You should be able to set up a new .NET 4.5 C# console project and add in all the same dependencies. Once you have that put together, you can use the following source code:

using System;
using System.Collections.Generic;
using System.Text;

using IronPython.Hosting;

namespace RunExternalScript
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Console.WriteLine("Press enter to execute the python script!");
            Console.ReadLine();

            var py = Python.CreateEngine();
            try
            {
                py.ExecuteFile("script.py");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Oops! We couldn't execute the script because of an exception: " + ex.Message);
            }

            Console.WriteLine("Press enter to exit...");
            Console.ReadLine();
        }
    }
}

This script looks similar, right? Before I explain what it does, let’s add in the Python script that you’ll be executing from this console application.

  • Right click on your project in the solution explorer.
  • Select the “Add” menu item from the context menu.
  • Select the “New Item…” menu item.
  • You should see the “Add New Item” dialog.
  • You’ll want to add a new text file called “script.py”.

It should look a little something like this:

Add new Python script in Visual Studio

In the “Add New Item” dialog, select “Text File” and rename it to “script.py”.

The next really important step is to ensure that this script gets copied to the output directory. To do this, select your newly added script file in the solution explorer and change the “Copy to Output Directory” setting to “Copy Always”. Now when you build your project, you should see your script.py file get copied to the build directory. Woo! You can put any python code you want inside of the script file, but I started with something simple:

print('Look at this python code go!')

Okay, so back to the C# code now. This example looks much like the first example.

  • Wait for the user to press enter before executing the Python script. Just to make sure they’re ready!
  • Create our engine instance, just like in the first example.
  • In the try block, we tell the engine to execute our script file. Because we had the file copy to the output directory, we can just use a relative path to the file here.
  • Again, we’ve wrapped the whole thing inside of a try/catch to ensure any mistakes you have in your python script get caught.
    • Try putting some erroneous Python code in the script file and running. What happens?
  • Finally, make sure the user is content with the output and wait for them to press Enter before exiting.

Look how easy that was! Now you can choose to execute Python code generated in C# OR execute external Python scripts!

Summary

It’s awesome to see that you expressed an interest in trying to marry these two languages together inside of a powerful IDE. We’re only breaking through the surface here, and admittedly I’m still quite new to integrating Python and C# together. I need to re-familiarize myself with Python, but I can already see there is a ton of potential for writing some really cool applications this way.

In the near future, I’ll be discussing how the dynamic keyword in C# can actually allow you to create classes in Python and use them right inside of C#… Dynamically!

Both of these pages were helpful in getting me up and running with C# and Python together:

Source code for these projects is available at the following locations:


Raspberry Pi + WordPress => PiPress

Raspberry Pi

Background

In the past, I’ve dabbled a bit with hosting my own server on a spare outdated box that likely should have been thrown out. My least favourite thing to do is sit down and tinker with trying to get services and such configured so that they all work together… But once it’s working, it’s glorious. Enter the Raspberry Pi.

Earlier this year I decided I wanted to get a Pi. Why? I wasn’t too sure… But they’re cheap and nothing bad could come of it 🙂 Once I got the thing up and running I was reading about how people were using them. Hosting a WordPress site was definitely one of the uses, so I figured I’d try my hand at that. There are other guides on The Internet about how to do this, but this is what got me up and running.

Disclaimer: A *lot* of this is taken from IQ Jar where there’s been an absolutely amazing outline posted. Although I am repeating a lot of the same steps here, I wanted to post what I felt was a complete install guide. I found myself going back and forth between a few resources, so hopefully this will reduce that issue for you. I do very highly recommend you have a look at IQ Jar though.

Raspberry Pi: What & Where To Buy?

This part is pretty open ended. Let’s start with the “what” portion of things.

The Raspberry Pi is just the board. If you’re totally content with buying a board without a case that you can’t even power up, then you’re all set. Although, if that’s the case, you probably don’t need to read anymore of this! It’s common to pick up the following to get your Raspberry Pi working:

  • Raspberry Pi
  • Case
  • Power Adapter
  • SD Card

But once you’ve got those things, you still can’t do too much with your Raspberry Pi aside from powering it up. Some other things you’ll likely want:

  • USB Wireless Adapter
  • USB Keyboard
  • HDMI Cable

NOTE: Pay special attention to what wireless adapters and SD cards can be used with a Pi out of the box. You’ll want to save yourself the headache if others have confirmed the parts you’re looking at purchasing are compatible.

So now that you have an idea what things you’ll need to pickup, where do you get them? If you search The Googles for where to buy any of this stuff, you’ll probably get a ton of hits. Maybe that’s not totally useful for you. I’d suggest the following sites:

  • Amazon: I got everything I needed off of Amazon in one fell swoop. You can even find some combo deals that include the Raspberry Pi and a case. Heck, some even come with the SD card too!
  • ModMyPi: A great resource… There’s tons of options on this site and it’s specifically for the Pi. Probably can’t go wrong by looking here.
  • Ebay: Ol’ Faithful. Lots of options here too, just like Amazon. Bound to find something that fits the bill.
  • Newark: There are a great deal of product offerings and resources on Newark. Check them out for full packages, accessories, and additional guides/walk-throughs.

The Walkthrough

First thing: there are a million ways to do this. I’m not going to explore all the options here because I’m not an expert and because I want to provide you with my own steps that worked for me. As soon as I deviate from that… Things will get messy and complicated 🙂

  1. Download a Raspbian “Wheezy” image from the Raspberry Pi website. This is the image of the operating system your Pi will use.
  2. Download Win32 Disk Imager. You’ll need this to get the image of the operating system onto your SD card.
  3. Once both downloads have completed, run Win32 Disk Imager and use it to write the image to your SD card. You’ll need a card reader/writer in your computer, but this is pretty standard these days.
  4. Take your card out of your computer and pop it into your Pi. You should have your Pi all setup now with power, USB keyboard, USB WIFI adapter, and an HDMI cable plugged into your TV/monitor.
  5. When you power up your Pi, you should be taken to an initialization/configuration menu. If it ain’t working, there are a million and one trouble shooting guides.
  6. Some things I suggest you get going while you’re here:
    • Reduce graphics memory to the minimum (16). Should help with performance.
    • Give yourself a modest overclock. Not sure what’s deemed safe, but I went somewhere in the middle.
    • Enable SSH. Later on you’ll never even need to be near your Pi. I can actually control my Pi from my phone with this sweet app.
  7. Once you’ve got things how you want, expand the file system and reboot your Pi.
  8. When the Raspberry Pi is back up and running, you need to login to your credentials and then type “startx” and press enter. This will get you into the GUI portion of things.

Anyone well versed in *nix may not need or want to do this, but I found it easiest this way. At this point, get your wifi and everything setup. Your blog won’t be very useful if your Pi isn’t on the internet. Having the GUI portion of Raspbian will also let you quickly search the net and pull up articles if you’re running into any oddities with the components you bought. Anyway, now that your Raspberry Pi is working with all the parts you purchased, on with the rest of it:

  1. Open up a terminal. You’re going to need it for basically everything else in this guide. We’re going to start by turning your Raspberry Pi into a LAMP server.
  2. Type “sudo apt-get update” to update the various packages on your Pi.
  3. sudo apt-get install apache2” to download and install the Apache web server. You’ll want to say yes when it asks for confirmation (and same whenever this happens for the other packages we need to install).
  4. sudo nano /etc/apache2/apache2.conf” to open up the apache configuration. You’ll want to stick “ServerName localhost” at the very end of this file and then save and exit the editor. This will get rid of warnings about determining the server’s domain name.
  5. Restart apache by using “sudo service apache2 restart“. Amazing. You now have a web server.
  6. You’ll need to take care of any port forwarding to make sure your router does it’s job to get to your Pi.
  7. Next is installing PHP: “sudo apt-get install php5
  8. Type “ls /usr/lib/php5/” and take not of the entry that looks like “20100525+lfs“. Yours might be slightly different.
  9. sudo nano /etc/php5/apache2/php.ini” to open up the PHP configuration. Find the line that starts with “extension_dir” and change it so it looks like: extension_dir = “/usr/lib/php5/20100525+lfs/” (except with the name of the entry you have if it was different!)
  10. sudo nano /etc/apache2/apache2.conf” to open up the apache configuration. You want to verify you have this line in there: Include conf.d/*.conf
  11. Next up, you’re going to need to make a config file for Apache. This can be done by typing: “sudo nano /etc/apache2/conf.d/php.conf” and then putting the following text inside of the file:
    # PHP is an HTML-embedded scripting language which attempts to make
    # it easy for developers to write dynamically generated webpages.
    LoadModule php5_module modules/libphp5.so
    #
    # Cause the PHP interpreter to handle files with a .php extension.
    AddHandler php5-script .php
    AddType text/html .php
    #
    # Add index.php to the list of files that will be served as
    # directory indexes.
    DirectoryIndex index.phpSave and close nano when you’ve finished.
  12. To improve the performance of PHP, install APC by typing “sudo apt-get install php-apc
  13. Now that you’ve finished that, restart Apache: sudo service apache2 restart

Next we need to get MySQL up and running. This is going to serve as the backend for your WordPress installation.

  1. sudo apt-get install mysql-server mysql-client
  2. Follow up with the MySQL plugin for PHP: “sudo apt-get install php5-mysql
  3. Now that you’ve finished that, restart Apache: sudo service apache2 restart

Next we’re actually going to install wordpress!

  1. In your terminal: “sudo wget http://wordpress.org/latest.tar.gz
  2. Then extract the whole thing: “sudo tar -zxvf latest.tar.gz
  3. From here, you can either follow along with the official WordPress Setup instructions, or just do what I did. If you want to do what I did, just keep following here!
  4. We need to make a user in MySQL:
    1. In the terminal: “mysql -u <YOUR_ADMIN_USERNAME> -p” and hit enter.
    2. (Obviously where it says <YOUR_ADMIN_USERNAME> you should replace with the database admin username you picked)
    3. Enter your password as the prompt suggests and press enter.
    4. Next up: “CREATE DATABASE wordpress” to make the database named wordpress.
    5. And now we set privileges: “GRANT ALL PRIVILEGES ON wordpress.* TO “wordpress”@”localhost” IDENTIFIED BY “<YOUR_PASSWORD>”;” and press enter.
    6. (Again, it’s hopefully obvious to replace <YOUR_PASSWORD> with your password)
    7. FLUSH PRIVILEGES
    8. And then finally “EXIT
  5. For my install, I put WordPress right at the root of my website. To do this, we need to copy the contents of the wordpress directory to your /var/www/ directory, but we’re *NOT* copying the wordpress directory itself there: “cp -a wordpress/. /var/www/
  6. And now, we run the install script! Since we installed WordPress to the root of the website, we go to http://127.0.0.1/wp-admin/install.php in a browser. Follow the few simple steps there and you should be up and running!
  7. Remember to check the troubleshooting section on the WordPress site if something seemed to go wrong!

That’s it! You should be up and running.

What’s Next?

You might find your site is a little slow. That’s somewhat expected on your little Rapsberry Pi. Don’t fret. There are lot’s of methods for optimizing your site.

  • Check out WP Super Cache, or specifically, the guide over at IQ Jar for more information on tweaking this (it’s near the bottom of the post).
  • There’s minifying plugins for javascript and CSS files. This can do a nice job compressing the files and reducing how much data has to be transferred.
  • You can look at something like Smush.it to help with compressing your images that you serve. Again, smaller means faster.
  • Finally, you might want to test your site on GTmetrix to see if it can recommend any other optimizations to you.

Summary

To wrap up, I hope you found this guide informative. I thought a Raspberry Pi was a great way to start a little DIY project at home and it was fun to get a blog up and running on it.

References

I’m sure I consulted a million and one guides on the Internet, but the following that stick out to me (and I highly recommend you look into them):

  • IQ Jar: Crucial for getting me up and running. Specifically, these two guides here and here.
  • WordPress.com: The detailed guide here for installing WordPress once you have all the prerequisites was definitely necessary.
  • GTmetrix:  Serving content was relatively new to me. Once I was analyzing my page with this site, I was lead down a rabbit hole of different things to try and optimize. I highly recommend it!

  • Nick Cosentino

    Nick Cosentino

    I work as a team lead of software engineering at Magnet Forensics (http://www.magnetforensics.com). I'm into powerlifting, bodybuilding, and blogging about leadership/development topics over at http://www.devleader.ca.

    Verified Services

    View Full Profile →

  • Copyright © 1996-2010 Dev Leader. All rights reserved.
    Jarrah theme by Templates Next | Powered by WordPress