Tag: development

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.


Dynamic Programming with Python and C#

Dynamic Coding with C# and Python

Dynamic Code: Background

Previously, I was expressing how excited I was when I discovered Python, C#, and Visual Studio integration. I wanted to save a couple examples regarding dynamic code for a follow up article… and here it is! (And yes… there is code you can copy and paste or download).

What does it mean to be dynamic? As with most things, wikipedia provides a great start. Essentially, much of the work done for type checking and signatures is performed at runtime for a dynamic language. This could mean that you can write code that calls a non-existent method and you wont get any compilation errors. However, once execution hits that line of code, you might get an exception thrown. This Stack Overflow post’s top answer does a great job of explaining it as well, so I’d recommend checking that out if you need a bit more clarification. So we have statically bound and dynamic languages. Great stuff!

So does that mean Python is dynamic? What about C#?

Well Python is certainly dynamic. The code is interpreted and functions and types are verified at run time. You won’t know about type exceptions or missing method exceptions until you go to execute the code. For what it’s worth, this isn’t to be confused with a loosely typed language. Ol’ faithful Stack Overflow has another great answer about this. The type of the variable is determined at runtime, but the variable type doesn’t magically change. If you set a variable to be an integer, it will be an integer. If you set it immediately after to be a string, it will be a string. (Dynamic, but strongly typed!)

As for C#, in C# 4 the dynamic keyword was introduced. By using the dynamic keyword, you can essentially get similar behaviour to Python. If you declare a variable of type dynamic, it will take on the type of whatever you assign to it. If I assign a string value to my dynamic variable, it will be a string. I can’t perform operations like pre/post increment (++) on the variable when it’s been assigned a string value without getting an exception. If I assign an integer value immediately after having assigned a string value, my variable will take on the integer type and my numeric operators become available.

Where does this get us with C# and Python working together then?

Example 1: A Simple Class

After trying to get some functions to execute between C# and Python, I thought I needed to take it to the next level. I know I can declare classes in Python, but how does that look when I want to access it from C#? Am I limited to only calling functions from Python with no concept of classes?

The answer to the last question is no. Most definitely not. You can do some pretty awesome things with IronPython. In this example, I wanted to show how I can instantiate an instance of a class defined within a Python script from C#. This script doesn’t have to be created in code (you can use an external file), so if you need more clarification on this check out my last Python/C# posting, but I chose to do it this way to have all the code in one spot. I figured it might be easier to show for an example.

We’ll be defining a class in Python called “MyClass” (I know, I’m not very creative, am I?). It’s going to have a single method on it called “go” that will take one input parameter and print it to the console. It’s also going to return the input string so that we can consume it in C# and use it to validate that things are actually going as planned. Here’s the code:

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Scripting.Hosting;

using IronPython.Hosting;

namespace DynamicScript
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Console.WriteLine("Enter the text you would like the script to print!");
            var input = Console.ReadLine();

            var script =
                "class MyClass:\r\n" +
                "    def __init__(self):\r\n" +
                "        pass\r\n" +
                "    def go(self, input):\r\n" +
                "        print('From dynamic python: ' + input)\r\n" +
                "        return input";

            try
            {
                var engine = Python.CreateEngine();
                var scope = engine.CreateScope();
                var ops = engine.Operations;

                engine.Execute(script, scope);
                var pythonType = scope.GetVariable("MyClass");
                dynamic instance = ops.CreateInstance(pythonType);
                var value = instance.go(input);

                if (!input.Equals(value))
                {
                    throw new InvalidOperationException("Odd... The return value wasn't the same as what we input!");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Oops! There was an exception while running the script: " + ex.Message);
            }

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

Not too bad, right? The first block of code just takes some user input. It’s what we’re going to have our Python script output to the console. The next chunk of code is our Python script declaration. As I said, this script can be loaded from an external file and doesn’t necessarily have to exist entirely within our C# code files.

Within our try block, we’re going to setup our Python engine and “execute” our script. From there, we can ask Python for the type definition of “MyClass” and then ask the engine to create a new instance of it. Here’s where the magic happens though! How can we declare our variable type in C# if Python actually has the variable declaration? Well, we don’t have to worry about it! If we make it the dynamic type, then our variable will take on whatever type is assigned to it. In this case, it will be of type “MyClass”.

Afterwards, I use the return value from calling “go” so that we can verify the variable we passed in is the same as what we got back out… and it definitely is! Our C# string was passed into a Python function on a custom Python class and spat back out to C# just as it went in. How cool is that?

Some food for thought:

  • What happens if we change the C# code to call “go1” instead of “go”? Do we expect it to work? If it’s not supposed to work, will it fail at compile time or runtime?
  • Notice how our Python method “go” doesn’t have any type parameters specified for the argument “input”? How and why does all of this work then?!

Example 2: Dynamically Adding Properties

I was pretty excited after getting the first example working. This meant I’d be able to create my own types in Python and then leverage them directly in C#. Pretty fancy stuff. I didn’t want to stop there though. The dynamic keyword is still new to me, and so is integrating Python and C#. What more could I do?

Well, I remembered something from my earlier Python days about dynamically modifying types at run-time. To give you an example, in C# if I declare a class with method X and property Y, instances of this class are always going to have method X and property Y. In Python, I have the ability to dynamically add a property to my class. This means that if I create a Python class that has method X but is missing property Y, at runtime I can go right ahead and add property Y. That’s some pretty powerful stuff right there. Now I don’t know of any situations off the top of my head where this would be really beneficial, but the fact that it’s doable had me really interested.

So if Python lets me modify methods and properties available to instances of my type at runtime, how does C# handle this? Does the dynamic keyword support this kind of stuff?

You bet. Here’s the code for my sample application:

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

using Microsoft.CSharp.RuntimeBinder;

using IronPython.Hosting;

namespace DynamicClass
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            Console.WriteLine("Press enter to read the value of 'MyProperty' from a Python object before we actually add the dynamic property.");
            Console.ReadLine();

            // this script was taken from this blog post:
            // http://znasibov.info/blog/html/2010/03/10/python-classes-dynamic-properties.html
            var script =
                "class Properties(object):\r\n" +
                "    def add_property(self, name, value):\r\n" +
                "        # create local fget and fset functions\r\n" +
                "        fget = lambda self: self._get_property(name)\r\n" +
                "        fset = lambda self, value: self._set_property(name, value)\r\n" +
                "\r\n" +
                "        # add property to self\r\n" +
                "        setattr(self.__class__, name, property(fget, fset))\r\n" +
                "        # add corresponding local variable\r\n" +
                "        setattr(self, '_' + name, value)\r\n" +
                "\r\n" +
                "    def _set_property(self, name, value):\r\n" +
                "        setattr(self, '_' + name, value)\r\n" +
                "\r\n" +
                "    def _get_property(self, name):\r\n" +
                "        return getattr(self, '_' + name)\r\n";

            try
            {
                var engine = Python.CreateEngine();
                var scope = engine.CreateScope();
                var ops = engine.Operations;

                engine.Execute(script, scope);
                var pythonType = scope.GetVariable("Properties");
                dynamic instance = ops.CreateInstance(pythonType);

                try
                {
                    Console.WriteLine(instance.MyProperty);
                    throw new InvalidOperationException("This class doesn't have the property we want, so this should be impossible!");
                }
                catch (RuntimeBinderException)
                {
                    Console.WriteLine("We got the exception as expected!");
                }

                Console.WriteLine();
                Console.WriteLine("Press enter to add the property 'MyProperty' to our Python object and then try to read the value.");
                Console.ReadLine();

                instance.add_property("MyProperty", "Expected value of MyProperty!");
                Console.WriteLine(instance.MyProperty);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Oops! There was an exception while running the script: " + ex.Message);
            }

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

Let’s start by comparing this to the first example, because some parts of the code are similar. We start off my telling  the user what’s going to happen and wait for them to press enter. Nothing special here. Next, we declare our Python script (again, you can have this as an external file) which I pulled form this blog. It was one of the first hits when searching for dynamically adding properties to classes in Python, and despite having limited Python knowledge, it worked exactly as I had hoped. So thank you, Zaur Nasibov.

Inside our try block, we have the Python engine creation just like our first example. We execute our script right after too and create an instance of our type defined in Python. Again, this is all just like the first example so far. At this point, we have a reference in C# to a type declared in Python called “Properties”. I then try to print to the console the value stored inside my instances property called “MyProperty”. If you were paying attention to what’s written in the code, you’ll notice we don’t have a property called “MyProperty”! Doh! Obviously that’s going to throw an exception, so I show that in the code as well.

So where does that leave us then? Well, let’s add the property “MyProperty” ourselves! Once we add it, we should be able to ask our C# instance for the value of “MyProperty”. And… voila!

Some food for thought:

  • When we added our property in Python, we never specified a type. What would happen if we tried to increment “MyProperty” after we added it? What would happen if we tried to assign an integer value of 4 to “MyProperty”?
  • When might it be useful to have types in C# dynamically get new methods or properties?

Summary

With this post, we’re still just scratching the surface of what’s doable when integrating Python and C#. Historically, these languages have been viewed as very different where C# is statically bound and Python is a dynamic language. However, it’s pretty clear with a bit of IronPython magic that we can quite easily marry the two languages together. Using the “dynamic” keyword within C# really lets us get away with a lot!

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


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:


Innovation: Weekly Article Dump

Innovation: Weekly Article Dump (Image by http://www.sxc.hu/)

Innovation and You

There’s no denying innovation is important. You often see startups oozing with innovation completely disrupt a market and consequently, there are tons of people out there with dreams to do the same thing. How do you jack up the innovation level in your company? Why is it that startups seem to be so much better at innovating even though multi-million dollar companies have the people and financial resources to throw at R&D? Why do big companies suck at innovating?

The answer starts with your employees. Empowering your employees to innovate and embedding innovation in the work culture is key to ensuring your company continues to innovate. With big companies, the focus moves from innovation to profit maximization. Over time though, some small team of highly innovative individuals are going to find a way to do it differently or do it better, and the big players will take a hit.

Where does your company sit in the world of innovation? Does innovation come from a select few individuals?

Articles

  • Driving Innovation: This article is all about how to truly drive innovation in your company: It doesn’t come from one person, but rather many people. Arne Sorenson shares five tips for trying to drive innovation among his team members. Coincidentally, my colleague Tayfun actually wrote an innovation piece on a similar topic earlier this week.
  • Are Headphones the New Cubicle?: I thought this post by Richard Moran was pretty interesting and at least worst asking yourself the question (even if you don’t feel like reading the article). Open offices are seemingly the new way to go, but are the benefits of open offices reduced by everyone strapping headphones on? I’m personally a big fan of having an open concept office, but I do think that open communication factor is significantly hurt by having headphones on all day.
  • How to Spot a Great Leader in Four Easy Steps: James Caan says that great leaders are defined by four major things: confidence, intuition, decisiveness, and empathy. I have to agree. People need a leader they can get behind and trust to make good decisions. That leader needs to show confidence when they are making their decisions to really show that they aren’t blindly leading people down path X. However, the empathy part goes really far. After all, you’re dealing with real live people, not machines.
  • Intrapreneurship – Guest Blog by Tayfun Uzun: I’ve already briefly mentioned it here in this post, but my colleague Tayfun from Magnet Forensics wrote his perspective on intrapreneurship and how it drives innovation. It’s all about empowering each individual in the company to be innovative in their own right, and in return, the company itself experiences a boost in innovation. Check it out!
  • University of Waterloo Grad’s Journey To Becoming A Software Engineer: Here’s the part where I toot my own horn a bit. A friend of mine, Meghan Greaves, did a mini-interview with me for a TalentEgg article. It’s about how and when I knew what I wanted to do when I “grew up”, what university in Waterloo was like for me, and my transition into a development leadership role at Magnet Forensics. It was really flattering to have Meghan put this together, so please check it out and give her a shout out on twitter!
  • New Generation of Business: Connecting Employee Loyalty with Customer Loyalty: In this post by Colin Shaw, he dives into the concept of employee ambassadors and how you can build a better business by marrying employee and customer loyalty. Keeping employees engaged through your employee ambassadors will help keep the rest of your employees engaged and believing in the company’s mission.
  • Just Do it – Right from the Start!: Michael Skok provides a high-level walkthrough for startup success. The first thing? The right people. A successful company absolutely requires the right people and that’s where it starts. Keeping a solid workplace culture and empowering your employees are two fundamental things to do as you bring the right people on board. Great article!
  • Look for Advisors Who Can Teach, Not Tell: Hunter Walk shares some advice that certainly makes sense for advisory boards, but I wouldn’t limit it to just that. The idea of being able to teach and not just tell is a parallel to great leadership. Telling people what to do is not as effective as telling people what the goal is and empowering them to get there. It’s much easier to learn and grow if you’re given guidelines but you get to hold the reins.
  • Using Humor in Business: Some Practical AdviceColin Shaw is up again this week with an article on humour in business. I think it’s pretty common that when people think of big corporations they have this vision of straight-faced people in suits carrying brief cases… but is that always the reality? Should it be the reality? Colin talks about how you can leverage humour in the workplace for things such as improving relationships or making ideas more memorable. There’s certainly a balance, but I think Colin doe sa great job explaining it.
  • The # 1 Job of a Leader Is …: If you have grammar OCD then skip to the next link right now. Fair warning! Tom Hood says that to be a true leader, you need to be doing “more better”. What does it mean? It’s simple… do better, only more! Okay, maybe it still sounds kind of strange, but the idea still applies. In order to be a real leader in your domain, you have to keep doing better. You need to innovate, push boundaries, and keep doing things better. Do better than your competitors, and do better than you did in the past.
  • 5 Lessons On How to Build High Impact Teams: Jake Wood talks about what it takes to make a high impact team. What are some of the ingredients? First, you need to know your role and how you fit in with your team. You need to embrace innovation and change. And of course, one of my favourites, “Passion trumps talent, but culture is king”.
  • Why Your Software Development Process Is Broken: In this article by Joe Emison, discusses where control in software products lies and how shifting it between developers and high-level managers can have different effects. On one hand, developers with too much control start to stick in all the fancy new technology because developers love new shiny things, and on the other hand high-level managers create a one-way flow of direction down to developers. His solution is to have a benevolent dictator that lies somewhere in the middle.

Empower your team to innovate and watch your company’s innovation as a whole increase. Remember to follow Dev Leader on social media outlets to get these updates through the week!

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

You can also check out Dev Leader on FlipBoard.


  • 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