Droid-Fu Android Library

by Marcus King 12. April 2011 01:49

I recently stumbled across Droid-Fu (say it like Kung-Fu not like Droid F. U. as you would when Android pisses you off) when looking to see if there were any good android helper libraries that helped with some of the monotony of android development.  I’m pleased by what I find so far some of the code doesn’t make a lot of sense to me such as BetterService.java but I guess because they recommend you create a custom DroidFuApplication rather than the standard Application they can have hooks into other special features.  But that kind of goes into one of my big complaints about the framework, that it requires recommends you to create a class that extends DroidFuApplication and register it in your application manifest.

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android" ...>  
  3.     <application android:name="MyDroidFuApplication" ...>  
  4.         ...   
  5.     </application>  
  6.     ...   
  7. </manifest>  

That by itself isn’t bad but it seems that every useful android tool/library requires you to override the base Application class with something of their own such as RoboGuicean IoC framework for Android based off of Google’s Guice.  As we all know you can’t have multiple inheritance or extension in Java.  So now you’ve got to sacrifice something.  In my case I keep the IoC but am still able to leverage some of the Droid-Fu goodness such as their WebImageView widget which asynchronously retrieves and displays a remote image and has built in caching so duplicate HTTP requests aren’t made.  It even allows you to set a “loading” image to display while the remote image is retrieved.  However it doesn’t do anything to safeguard against pulling in an image that is too large and causes an OutOfMemoryException (one of those Droid F.U. moments I was talking about).  Really I think the WebImageView should be part of the android framework itself or at least the ImageView widget needs to be improved to handle external URL’s.  Using the WebImageView is super simple, you just download Droid-Fu JAR file and add a reference to it in the Java Build Path.  Then in layout XML of your Activity you add something like:

  1. <com.github.droidfu.widgets.WebImageView android:id="@+id/user_profileImage"  
  2.                 android:layout_width="55dip"  
  3.                 android:layout_height="55dip"           
  4.                 android:layout_marginRight="10dip" />  

In your Activity code you simply retrieve the WebImageView, set it’s image URL, and load the image.

  1. import com.github.droidfu.widgets.WebImageView;   
  2.   
  3. public class UserProfileActivity extends Activity {   
  4.   
  5.     private WebImageView userProfileImage;   
  6.     private User currentUser;   
  7.        
  8.     /** Called when the activity is first created. */  
  9.     @Override  
  10.     public void onCreate(Bundle savedInstanceState) {   
  11.         super.onCreate(savedInstanceState);   
  12.         setContentView(R.layout.user_profile);   
  13.            
  14.         userProfileImage = (WebImageView)findViewById(R.id.user_profileImage);   
  15.            
  16.         userProfileImage.setImageUrl(currentUser.getPhotoUrl());   
  17.         userProfileImage.loadImage();   
  18.     }   
  19. }  

Tags: , ,

Java | Android | Mobile

Parallel Programming is Hard

by Marcus King 2. March 2011 06:17

I’m sure you’ve read the countless posts on how we’re going to be forced into writing more multi-threaded applications due to the fact that it’s now the standard to have multi-core machines.  Pretty soon we’re going to get into double digit numbers of cores and traditional single threaded program execution is an abysmal waste of system resources.  Uggghhh but parallel programming is really hard!  Luckily Microsoft is releaving some of our stress by introducing things like the Task Parallel Library as well as PLINQ with .NET 4, plus functional languages like F#, Haskell, Erlang, Scheme, and others are becoming popular which also aleviate many of the headaches with parallel programming (mainly around maintaining state).  But there are scenarios where I’m working on a project that I can’t use .NET 4 or heaven forbid be more adventurous and use a functional language. 

Luckily Steven Toub, one of the guys behind Task Parallel Library released a white paper Patterns of Parallel Programmingthat is just phenomenal. Easily one of the best whitepaper’s I’ve ever read, it’s not a light read however coming in at 118 pages.  In this not only does he break down common patterns in parallel programming but he gives you an inside peak to some of the patterns that are used in the actual TPL; e.g. Parallel.ForEach().  It’s remarkably simple in this example but I know the real implementation in .NET 4 is quite a bit more complicated because it optimizes the number of threads dispatched depending on system load and batches groups of work for individual threads.

Here’s my derivative of the examples in the whitepaper that I’ve used successfully in a few .NET 3.5 applications.

  1. public static class Parallel   
  2. {   
  3.     public static void ParallelFor(int inclusiveLowerBound, int exclusiveUpperBound, Action<int> body)   
  4.     {   
  5.         ParallelFor(inclusiveLowerBound, exclusiveUpperBound, body, Environment.ProcessorCount);       
  6.     }   
  7.   
  8.     public static void ParallelFor(int inclusiveLowerBound, int exclusiveUpperBound, Action<int> body, int numberOfThreads)   
  9.     {   
  10.         // Initialize the number of remaining threads, and set the starting point for the iteration.   
  11.         int remainingWorkItems = numberOfThreads;   
  12.         int nextIteration = inclusiveLowerBound;   
  13.         const int batchSize = 3;   
  14.         using (ManualResetEvent mre = new ManualResetEvent(false))   
  15.         {   
  16.             // Create each of the work items.   
  17.             for (int p = 0; p < numberOfThreads; p++)   
  18.             {   
  19.                 //ThreadPool is the easiest to use but isn't very reliable if a thread fails   
  20.                 //I've had some instances where a spot in the threadpool doesn't get released if an error occurs   
  21.                 ThreadPool.QueueUserWorkItem(delegate   
  22.                 {   
  23.                     int index;   
  24.                     //Let each thread handle a batch of work items instead of one action per thread   
  25.                     //to prevent excessive context switching   
  26.                     while ((index = Interlocked.Add(ref nextIteration, batchSize) - batchSize) < exclusiveUpperBound)   
  27.                     {   
  28.                         int end = index + batchSize;   
  29.                         if (end >= exclusiveUpperBound)   
  30.                             end = exclusiveUpperBound;   
  31.                         for (int i = index; i < end; i++)   
  32.                             body(i);   
  33.                     }   
  34.                     //This will signal that we are out of items to be worked (in a thread-safe manner)   
  35.                     if (Interlocked.Decrement(ref remainingWorkItems) == 0)   
  36.                         mre.Set();   
  37.                 });   
  38.             }   
  39.             // Wait for all threads to complete   
  40.             mre.WaitOne();   
  41.         }   
  42.     }   
  43.   
  44.     public static void ParallelForEach<T>(IEnumerable<T> source, Action<T> body)   
  45.     {   
  46.         ParallelForEach(source, body, Environment.ProcessorCount);   
  47.     }   
  48.   
  49.     public static void ParallelForEach<T>(IEnumerable<T> source, Action<T> body, int numberOfThreads)   
  50.     {   
  51.         //If it's a list we can use the ParallelFor with batching   
  52.         IList<T> sourceList = source as IList<T>;   
  53.         if (sourceList != null)   
  54.         {   
  55.             // This assumes the IList<T> implementation’s indexer is safe   
  56.             // for concurrent get access.   
  57.             ParallelFor(0, sourceList.Count, i => body(sourceList[i]));   
  58.         }   
  59.         else  
  60.         {   
  61.             int remainingWorkItems = numberOfThreads;   
  62.             using (var enumerator = source.GetEnumerator())   
  63.             {   
  64.                 using (ManualResetEvent mre = new ManualResetEvent(false))   
  65.                 {   
  66.                     // Create each of the work items.   
  67.                     for (int p = 0; p < numberOfThreads; p++)   
  68.                     {   
  69.                         ThreadPool.QueueUserWorkItem(delegate   
  70.                         {   
  71.                             // Iterate until there's no more work.   
  72.                             while (true)   
  73.                             {   
  74.                                 // Get the next item under a lock,   
  75.                                 // then process that item.   
  76.                                 T nextItem;   
  77.                                 lock (enumerator)   
  78.                                 {   
  79.                                     if (!enumerator.MoveNext()) break;   
  80.                                     nextItem = enumerator.Current;   
  81.                                 }   
  82.                                 body(nextItem);   
  83.                             }   
  84.                             //This will signal that we are out of items to be worked (in a thread-safe manner)   
  85.                             if (Interlocked.Decrement(ref remainingWorkItems) == 0)   
  86.                                 mre.Set();   
  87.                         });   
  88.                     }   
  89.                     // Wait for all threads to complete.   
  90.                     mre.WaitOne();   
  91.                 }   
  92.             }   
  93.         }   
  94.     }   
  95. }  

Tags: , , , , , ,

.NET | C# | Parllel | Functional

Command Line Arguments are a PAIN in .NET

by Marcus King 1. March 2011 05:46

So I was recently tasked with creating a console application that could be executed ad hoc and would attempt to “sync” data between two systems.  Simple enough.  But then as I got into the application I realized that there were a lot of variables that determined the flow and behavior of the execution of the program.  At first I thought of just creating an app.config file that would have an <appsettings/> section with all the variables I would need to read to run the code, I guess because of my web background.  As I thought about it more it didn’t seem right to do things this way.  I mean after all someone would have to make a copy of the exe and all necessary dll’s into a new folder, go in change the config settings, and run the application anytime they needed a variation of the settings.  We’ll luckily people thought about this long before I was programming, a little thing called Command Line Arguments.  Okay now I know how to solve the problem and hey in my Main method I have an array of strings called args so it should be simple to extract the flags/settings form the CLI right?  WRONG.

static void Main(string[] args)
{
} 

For some reason Microsoft doesn’t have a built in way, or even a utility, and worse yet limited documentation on parsing CLI arguments.  But I’m sure someone has solved this problem before so I’m off to Google looking for an answer and to my surprise there are a lot of utilities and libraries available but there really isn’t a de facto standard.

I evaluated a few and the best one I’ve seen so far is the Command Line Parser Libraryover at CodePlex.  You simply add a reference to CommandLine.dll to your project and add a class (private inner is recommended) to your Program.cs file that has your properties to hold the data you extract as well as attributes on those properties that define how they map to the command line arguments

class Options
{
    [Option("i", "input", Required = true, HelpText = "Input file to read.")]
    public string InputFile = null;

    [Option(null, "lenght", HelpText = "The maximum number of bytes to process.")]
    public int MaximumLenght = -1;

    [Option("v", null, HelpText = "Print details during execution.")]
    public bool Verbose = false;

    [HelpOption(HelpText = "Dispaly this help screen.")]
    public string GetUsage()
    {
        var usage = new StringBuilder();
        usage.AppendLine("Quickstart Application 1.0");
        usage.AppendLine("Read user manual for usage instructions...");
        return usage.ToString();
    }
}

As you can see you simply create an Option attribute with the first parameter being the switch name to use in the CLI, the long name of the switch, whether it’s required or not, and help text if someone were to use the /? syntax at the end of your executable.  Help Text!  that’s pretty cool. It’s also really good at being generous with various whitespace characters around your parameters and even converting input into the appropriate type (notice int, string, and bool above). 

Now that we have the structure set up for using the CommandLine library to parse the arguments we need to capture the input from the Main method and hand the arguments over to the new Options class we created above.

var options = new Options();
ICommandLineParser parser = new CommandLineParser();
if (parser.ParseArguments(args, options))
{
    // consume Options type fields
    if (options.Verbose)
    {
        Console.WriteLine(options.InputFile);
        Console.WriteLine(options.MaximumLenght);
    }
    else
        Console.WriteLine("working ...");
}

Easy as pie.

Tags:

PostSharp - AOP for .NET

by Marcus King 10. January 2011 12:55

Aspect Oriented Programming (AOP) is one of those things I heard mumblings about for sometime and viewed it as some esoteric fringe CS concept that solved a very limited problem set and couldn't help me in my applications.  Then when I started reading more about it my preconceptions were strengthened.  Much of the documentation I saw was extremely confusing and didn't describe the real value of AOP.  Then I saw PostSharp and while it's still the same in theory, the very direct documentation showed me practical examples of how AOP helps us to take our code a step further than OOP and allows us to create more modularized and reusable code.  My reaction was, what have I been missing all this time.  How many hours have I wasted writing the same code I've written hundreds of times before not only in different applications but how many times have I repeated the exact same code in the same application.

Luckily in most cases there are good native features built into the language or third party frameworks that are available to reduce the tedious chore of writing basic code yet again.  However, there are a lot of times when OOP doesn’t provide us with a good way to solve a recurring problem.  I’m guessing since you’ve made it this far in you see that this is the point where AOP steps in and fills the gap left by OOP.  I recently did a video tutorial on improving exception handing  using AOP via PostSharp.  Traditionally in applications we need to catch when certain exceptions are thrown and do something with the exception by either logging it, calling another workflow, wrapping the exception inside of another one, or simply swallowing the exception, or some combination of all.  Let’s say for example we have a class we use to call a remote web service to retrieve data for our application.

 

  1. public class StockService   
  2. {   
  3.     public StockDetails GetStockDetails(string symbol)   
  4.     {   
  5.         try  
  6.         {   
  7.             //.... call to service    
  8.         }   
  9.         catch (SoapException ex) { throw new StockServiceException("Error Getting Details", ex); }   
  10.     }   
  11.     public decimal GetHistoricalPrice(string symbol)   
  12.     {   
  13.         try  
  14.         {   
  15.             //.... call to service    
  16.         }   
  17.         catch (SoapException ex) { throw new StockServiceException("Error Getting Historical Price", ex); }   
  18.     }   
  19.     public void AddToPortfolio(string symbol, int shares)   
  20.     {   
  21.         try  
  22.         {   
  23.             //.... call to service    
  24.         }   
  25.         catch (SoapException ex) { throw new StockServiceException("Error Adding to portfolio", ex); }   
  26.     }   
  27. }  


Look how often we are repeating the same basic pattern.  We’re making our service call and wrapping any Soap Exception that is thrown in a custom StockServiceException.  Using PostSharp we are able to modularize our code and make the business logic of the StockService class look so much cleaner.

 

 

  1. public class StockService   
  2. {   
  3.     [HandleException(SoapException, StockServiceException, "Error Getting Details")]   
  4.     public StockDetails GetStockDetails(string symbol)   
  5.     {           
  6.         //.... call to service      
  7.     }   
  8.     [HandleException(SoapException, StockServiceException, "Error Getting Historical Price")]   
  9.     public decimal GetHistoricalPrice(string symbol)   
  10.     {           
  11.         //.... call to service     
  12.     }   
  13.     [HandleException(SoapException, StockServiceException, "Error Adding To Portfolio")]   
  14.     public void AddToPortfolio(string symbol, int shares)   
  15.     {           
  16.         //.... call to service       
  17.     }   
  18. }  


All we need to do is create an attribute that derives from OnMethodBoundaryAspect that accepts three parameters in the constructor;  the type of exception to handle, the type of exception to wrap the caught exception in, and a message to give to the wrapped exception.

 

 

  1. [Serializable]   
  2. public class HandleExceptionAttribute : OnExceptionAspect   
  3. {   
  4.     private Type _expectedException;    
  5.     private Type _wrapInException;    
  6.     private string _message;   
  7.   
  8.     // Constructor that takes in variable parameters when the attribute is applied       
  9.     public HandleExceptionAttribute(Type expectedExeptionType, Type wrapInExceptionType, string message)   
  10.     {   
  11.         _expectedException = expectedExceptionType;   
  12.         _wrapInException = wrapInExceptionType; _message = message;   
  13.     }   
  14.   
  15.     // This method checks to see if the exception that was thrown from the method the       
  16.     // attribute was applied on matches the expected exception type we passed into the        
  17.     // constructor of the attribute      
  18.     public override Type GetExceptionType(MethodBase targetMethod)   
  19.     {   
  20.         return _expectedException;   
  21.     }   
  22.   
  23.     // This method is called when we have guaranteed the exception type thrown matches the       
  24.     // expected exception type passed in the constructor.  It wraps the thrown exception        
  25.     // into a new exception and adds the custom message that was passed into the constructor       
  26.     public override void OnException(MethodExecutionArgs args)   
  27.     {   
  28.         args.FlowBehavior = FlowBehavior.Continue;    
  29.         Exception newException = (Exception)Activator.CreateInstance(_wrapInException, new object[] { _message, _expectedException });    
  30.         throw newException;   
  31.     }   
  32. }  

Another common problem set I solve with PostSharp is caching expensive method calls. I find myself repeating the same basic pattern in projects when I need to implement caching. I’m sure you’re familiar with it.

 

 

  1. public Account GetAccount(int accountId)   
  2. {   
  3.     string cacheKey = string.Format("GetAccount_{0}", accountId);   
  4.     Account account = Cache.Get(cacheKey);   
  5.     if (account == null)   
  6.     {   
  7.         account = accountRepository.GetAccount(accountId);   
  8.         Cache.Add(cacheKey, account);   
  9.     }   
  10.     return account;   
  11. }  


We build our cache key and check to see if the item is present if the cache. If it is we return the value pulled from the cache, otherwise we do the necessary work to retrieve/build the item to return and save it in the cache with the cache key we built so that the next time this method is called we can successfully pull the item from the cache. I’ve repeated this pattern over and over again, typically in a business layer when I need to retrieve data from an expensive resource like a database or a web service call or when I do complex logic to construct the object that I need to return. Luckily PostSharp provides a way to centralize all of the caching logic for me so I can concentrate on the business logic. The same method now looks like this

 

 

  1. [Cache]   
  2. public Account GetAccount(int accountId)    
  3. {    
  4.     return accountRepository.GetAccount(accountId);    
  5. }  


Once again I simply adorn the method with an attribute and it handles a lot of the repitive code. Here is what the Cache Attribute/Aspect code looks like.

 

 

  1. public class CacheAttribute : OnMethodBoundaryAspect    
  2. {    
  3.     public override void OnEntry(MethodExecutionArgs args)    
  4.     {    
  5.         string key = args.Method.Name + "_" + Cache.GenerateKey(args.Arguments);    
  6.         object value = Cache.Get(key);    
  7.            
  8.         if (value == null)    
  9.         {    
  10.             args.MethodExecutionTag = key;    
  11.         }    
  12.         else    
  13.         {    
  14.             args.ReturnValue = value;    
  15.             args.FlowBehavior = FlowBehavior.Return;    
  16.         }    
  17.     }   
  18.        
  19.     public override void OnSuccess(MethodExecutionArgs args)    
  20.     {   
  21.         string key = args.MethodExecutionTag.ToString();    
  22.         Cache.Add(key, args.ReturnValue);    
  23.     }   
  24. }  


In the OnEntry method I’m building the cache key and checking to see if the item exists in the cache and if so I’m not letting the target method complete and I’m returning the value pulled from cache. If no item was found in the cache, the execution of the target method proceeds and when the target method successfully executes the OnSuccess override is fired and the item is stored in the cache.

 

There are a lot more interesting things to do with the two areas of caching and exception handling so I would encourage you to check out my screen casts to learn more.

Tags: , , , ,

.NET | AOP

RecentPosts

Powered by BlogEngine.NET 1.6.1.0 - Eco Theme by n3o Web Designers