Ryan Harrison My blog, portfolio and technology related ramblings

Android - Stocks app

I’ve written and Android app that can be used to view stocks and shares information from a wide variety of different businesses. The user maintains their own stocks portfolio so they only see the latest figures and information for the tickers that they are interested in - be it technology businesses such as Google or Microsoft, or perhaps just the popular financial indicator such as the FTSE or Dow Jones. The portfolio can be added to or removed from at the users convenience.

The full source code for this app is available on my GitHub account.

Also download the .apk file to install it on your own devices (Froyo and above).

Rather than presenting the information in a big long table, this app aims to give you the basic information about each ticker in a more graphical way. I’ve used colour coded tiles instead of a table which displays red for a ticker that has gone down in price in the current day of trading, or green if it has risen. Other pieces of the most important information is also present in each of the tiles. This includes the market the stock trades in, the current price, the price change, the price change percentage and the market capitalisation value.

Here is the main app display which shows the ticker tiles for each of the stocks currently in the users’ portfolio. As more stocks are added, tiles are added to the bottom. The figures themselves can be updated by tapping the icon in the top rightmost corner. In a way this almost replicates ‘live tiles’ in Windows 8.

Stocks Main

As I said before the tickers that are monitored on this screen can easily be added to through the use of the ‘+’ icon in the top right hand corner. This brings up the ‘Add ticker’ screen that allows you to search for a given company. In this example I search for ‘Google’ which brings up a list of possible stocks to add to the monitored portfolio. Here I choose the main Google ticker ‘GOOG’. It immediately gets added as another tile on the main screen with the most recent price information. To remove a ticker from the portfolio, hold your finger on the appropriate tile and select ‘ok’ in the confirmation menu that appears. The tile will be immediately removed from the main screen and the figures for the stock will no longer be downloaded unless the ticker is added again through the ‘Add Ticker’ view.

Stocks Add

Stocks Added

To view more detailed information and figures about a particular ticker in your portfolio, simply tap the appropriate tile that contains the relevant ticker. This brings up a new screen containing further financial figures about the stock along with a news feed with items relating to the stock. The news feed is updated constantly with the tickers to present the newest articles. Tapping a news article opens up the article in your web browser. For example here is the display for Yahoo Inc which was accessed by simply touching the Yahoo tile on the main display. As you can see the news feed is presented at the bottom and more detailed figures are at the top including the Day Highs and Low, Years High and Low and Volume figures.

Stocks Info

When inside the detailed information view for a particular stock, you can also view various charts for the stock which illustrate the price changes over a certain timeframe. Access this by tapping the ‘View Chart’ button. By default a 3 month chart will be shown however you can change the charts timespan by selecting an option from the top of the page. Here is an example showing the 1 month chart for Yahoo -

Stocks Chart

Each view in the app is fully compatible with a wide range of screen resolutions in both portrait and landscape. For example when flipped to landscape, the detailed information view for a stock is changed to present the information in a more user friendly manner -

Stocks Info Landscape

All data in the app is downloaded from the API’s by Yahoo! Finance (free for personal use). The app is also compatible with devices running Android Froyo (version 8) and above. I may do further posts on the internal infrastructure of the app which relies heavily on parsing retrieved XML and JSON data.

Get the full source code from my GitHub account.

Download the .apk file to install the app on your own devices (Froyo and above).

Read More

C# - The basis of a unit testing framework

Cut out all the sugar from pretty much any unit testing framework and you have yourself the situation where the users have marked their test classes to signify that they contain test methods and have marked the test methods themselves to tell the framework to actually run them.

So really on the base level (cutting out assertions and such) you need to somehow figure out which methods in which classes should be run by your tester. In managed languages this becomes a lot simpler through the use of reflection. We can simply ‘reflect’ on each of the classes/methods and decide if they should be run or not.

Here is some short C# code that demonstrates this idea through attributes and reflection. Classes which contain test methods are marked with the TestClass attribute and the test methods themselves which will be run later on are marked with the TestMethod attribute. The code uses LINQ to first get all the types in the currently executing assembly which include the TestClass attribute. Then all the methods are found in each of those classes which are marked with the TestMethod attribute. Finally each of those test methods are invoked using a new instance of the test class itself. The code is all commented so it should all be self-explanatory.

This simple idea can then be added onto in a load of different ways. For example some methods are expected to throw certain exceptions. The TestMethod attribute could therefore be modified to allow that exception through. The unit tester itself could then be adapted to catch that exception and still pass.

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Reflection;

namespace UnitTester  
    // Attribute to mark that a class contains tests that should be run  
    internal class TestClassAttribute : Attribute  

    // Attribute to mark that a method is a test and so should be run  
    internal class TestMethodAttribute : Attribute  

    // Class does not have TestClassAttribute so will ignored  
    internal class TestSuiteOne  
        // Method has TestMethod attribute but resides in a class without TestClass so will be ignored  
        public void DoTestOne()  
            Console.WriteLine("Doing test one in TestSuiteOne");  

    // Class does have TestClassAttribute so will not be ignored  
    internal class TestSuiteTwo  
        // Helper method does not have TestMethod attribute so will be ignored by the tester  
        // However will be run once indirectly through DoTestOne()  
        private void Helper()  
            Console.WriteLine("Helping to run the tests in TestSuiteTwo");  

        // Method has TestMethod attribute so will be run by the tester  
        public void DoTestOne()  
            Console.WriteLine("Doing test one in TestSuiteTwo");  

        // Method has TestMethod attribute so will be run by the tester  
        public void DoTestTwo()  
            Console.WriteLine("Doing test two in TestSuiteTwo");  

    internal class Program  
        public static void Main()  
            // Get access to all the types in the executing assembly  
            Assembly assembly = Assembly.GetExecutingAssembly();

            // Get all the types whose custom attributes includes TestClassAttribute  
            IEnumerable<Type> testClasses =  
            assembly.GetTypes().Where(t => t.GetCustomAttributes(false).Any(a => a is TestClassAttribute));

            foreach (Type testClass in testClasses)  
                Console.WriteLine("Running tests in TestClass: " + testClass.Name);

                // Get all the methods from the testclass whose custom attributes includes TestMethodAttribute  
                IEnumerable<MethodInfo> testMethods =  
                testClass.GetMethods().Where(m => m.GetCustomAttributes(false).Any(a => a is TestMethodAttribute));

                // Create an instance of the test class so we can run the test methods from it  
                object testClassInstance = Activator.CreateInstance(testClass);  
                foreach (MethodInfo testMethod in testMethods)  
                    // Run each of the test methods using the instance of the testclass  
                    testMethod.Invoke(testClassInstance, null);  
Read More

Java - Write code indirectly using reflection

In a recent post I showed how it is possible to write all your C# code indirectly through reflection. Here is the same example in Java. The process itself is very much the same - retrieve meta information about the classes/methods we are interested in and then invoke them passing in the object it would normally be called from. The classes themselves are all very similar through C# to Java. Type becomes Class, MethodInfo becomes Method etc.

A more interesting difference is how the Java version uses variable length parameters in the .invoke calls on Method objects as a way of passing parameters to the particular method. In the C# version you have to explicitly pass a Type or object array. I think the Java version is slightly more user friendly in that quite small regard even though the actual parameter itself is an array in both circumstances.

Its also interesting to see just how many exceptions the Java version can throw in the process. Because they are all checked you are forced to deal with them whereas C# does not have this feature. Its probably likely then that you would have to catch a more generic exception in the C# version.

Here is the code for the Java version. The result is the same as the C# version.

import java.lang.reflect.InvocationTargetException;  
import java.lang.reflect.Method;

public class Reflector {

    public static void main(String[] args) throws InstantiationException, IllegalAccessException, SecurityException,  
        NoSuchMethodException, IllegalArgumentException, InvocationTargetException {

        // Normal method  
        System.out.println("Normal method:\n");  
        Foo foo = new Foo();  

        System.out.println("\nUsing reflection:\n");  
        Class<?> fooClass = Foo.class;

        Foo fooInstance = (Foo) fooClass.newInstance();  
        Method setFirstMethod = fooClass.getMethod("setFirst", int.class);  
        Method setSecondMethod = fooClass.getMethod("setSecond", int.class);  
        setFirstMethod.invoke(fooInstance, 36);  
        setSecondMethod.invoke(fooInstance, 83);

        Method toString = fooClass.getMethod("toString", null);  
        String result = (String) toString.invoke(fooInstance, null);

        Method println = System.out.getClass().getMethod("println", String.class);  
        println.invoke(System.out, result);

class Foo {

    private int first;  
    private int second;

    public void setFirst(int newFirst) {  
        this.first = newFirst;  

    public void setSecond(int newSecond) {  
        this.second = newSecond;  

    public String toString() {  
        return "First = " + first + ", Second = " + second;  


Normal method:

First = 36, Second = 83

Using reflection:

First = 36, Second = 83  

Here is the C# version.

Read More

Java - Snippet Manager

The source code for my Java swing Snippet Manager application is now on GitHub.

Download the JAR file

Main Features -

  • A centralised repository of all your small code snippets and memos
  • Create, edit and origanise a selection of code, or plain text, snippets with syntax highlighting
  • Supported languages include C#, Java, PHP and Pascal
  • Assign keywords and descriptions to each snippet and use the search field to filter out your current set of snippets accordingly
  • Save your snippet collection to an XML file for use on any computer. Have separate files for different snippet sets
  • Easy and to use intuitive interface with automatic line numberings, syntax highlighting and find/replace dialog

Snippet Manager Screenshot

Full source code

Download an exectuable JAR file

Read More

C# - Write code indirectly using reflection

You can use the reflection features in C# to write your normal code in an indirect manner. No idea why you would want to do something like this, but it gives an idea of the control you get when using reflection.

In this example we have a small class wrapping two integers inside their own properties. First of all an object is created, the properties set, and the .ToString() method result passed into a Console.WriteLine using the conventional way. The exact same thing happens again but now indirectly through the use of reflection. As you can see it takes up nearly three times more code to to the exact same thing using reflection but you at least get the same result.

class Program  
    static void Main()
        Console.WriteLine("Using normal method:\n");

        // Normal method of instantiation and calling methods  
        Foo obj = new Foo();  
        obj.First = 36;  
        obj.Second = 83;  

        Console.WriteLine("\nUsing reflection:\n");  
        Type fooType = typeof (Foo);

        // Get an instance of the class  
        Foo fooInstance = (Foo) Activator.CreateInstance(fooType);

        // Get and set values of the two int properties  
        PropertyInfo firstPropInfo = fooType.GetProperty("First", typeof(int));  
        PropertyInfo secondPropInfo = fooType.GetProperty("Second", typeof(int));

        firstPropInfo.SetValue(fooInstance, 36, null);  
        secondPropInfo.SetValue(fooInstance, 83, null);

        // Run the ToString method on the object  
        MethodInfo toStringInfo = fooType.GetMethod("ToString");  
        string toStringResult = (string) toStringInfo.Invoke(fooInstance, null);

        // Run Console.WriteLine using the ToString result  
        MethodInfo writeLineInfo = typeof (Console).GetMethod("WriteLine", new[] {typeof(string)});  
        writeLineInfo.Invoke(null, new[] {toStringResult });  

class Foo  
    public int First { get; set; }  
    public int Second { get; set; }

    public override string ToString()  
        return "First = " + First + ", Second = " + Second;  


Using normal method:

First = 36, Second = 83

Using reflection:

First = 36, Second = 83  

Here is a Java version of the same example

Read More