Archive for 2010
One of the standard Android buttons that is required to be on every phone is the “menu” button. This brings up a little options menu on the bottom of the screen with icons and text labels that perform some action. For instance, on the main screen of the official Twitter app, you’ll get an options menu with two buttons: “Settings” and “Sign out”.
It’s easy to add an options menu with MonoDroid.
In the activity class, just override two methods: OnCreateOptionsMenu and OnOptionsItemSelected. The first one will construct a menu when the user hits the menu button. The second will respond to the action they clicked. Here’s how my code looks right now:
OnCreateOptionsMenu
The “Add” method overload on the IMenu that I’m using takes arguments: groupId, itemId, order, title, respectively. GroupId and ItemId almost seem arbitrary to me at this point. Order is the numeric order of how the options will be displayed, and title is the text that will appear with the icon.
Note that there is no Add overload with a parameter to specify the icon. I added a refresh icon to the project (since MonoDroid doesn’t seem to have Android.R.Drawable.IcMenuRefresh yet for some reason) named “ic_menu_refresh.png”, so once I get the option added, I turn right around and give it an icon with the SetIcon method.
OnOptionsItemSelected
I’m switching on the title of the option selected, which may or may not be good practice, but it works fine. You could also switch on the ItemId (see above) if you want. Note that the “ToS” is just an extension method that I wrote because I was tired of getting jerked around by the weird Java string/ToString stuff. The “Refresh” option only calls the Refresh method that I’m using elsewhere. Finally, while the default case might never happen, notice that this method returns a “bool”, so it’s a good catch-all that leaves the rest of the work to the super class.
That’s option menus in a quick nutshell. An easy way to add common functionality without junking up your layout. Feel free to take a look at the complete code at my MonodroidStockPortfolio project on GitHub.
After the recent Gawker issues, I decided that I need to take a better approach to password management. I saw someone tweet about LastPass (“the last password you’ll ever need”), so I decided to give it a shot. It’s an online “vault” for all your passwords, coupled with plugins for every major browser (including an extension that is available for the new Opera 11 and its new extension framework). Most browsers have password managers built in, but this one crosses over each browser, and indeed, each computer where you have LastPass plugins installed. So if I happen to be using Chrome on my desktop to create a new account somewhere, then LastPass will save that username and password to an organized vault. Then later, if I happened to be using Opera on my laptop, LastPass will pull that login information for me.
Additionally, LastPass will optionally generate very strong random passwords for you. And if you need to retrieve your password at any point, you can view your entire vault through the browser plugins, or login to their site.
Give it a try. If you use the same password everywhere, or are constantly forgetting your passwords (like me), then LastPass may be just the thing you need. Just make sure your LastPass password is very strong, and not used anywhere else.
One of my concerns about my MonoDroid app is that the more features I add, the messier the code is getting. I’m not using an IoC container, for instance, so all my dependencies are hard-wired. I couldn’t figure out a way to hook up one of the great IoC containers out there already (StructureMap, Ninject, etc) without resorting to the service-locator pattern, which really doesn’t get my code less messy (though it does prevent hard dependencies).
With that in mind, I looked to figure out a way to get ‘hooks’ into my app somehow to provide a central place to wire up my dependencies and inject them where necessary. My first thought was to use PostSharp. While this approach may or may not ultimately be the best one, PostSharp is such a terribly useful tool, that I’m bound to want to use it for something else anyway. A quick glance at PostSharp docs indicated that it might be Mono compatible, but what about MonoDroid?
I fiddled with it for a while, posted on both the MonoDroid mailing list and the SharpDevelop forums, fiddled some more, and with some help from Gael, got it working rather easily.
Step 1: Download and install PostSharp.
Step 2: Add a reference to PostSharp.SL.dll to your MonoDroid project. Yes, you read that right, the Silverlight PostSharp library.
Step 3: Add a file PostSharp.Custom.targets to your MonoDroid project with the following contents:
Step 4: Compile. At this point, you shouldn’t be getting a build error, and you should probably get a ‘warning’ message from PostSharp in your VS output window saying that you don’t have any aspects yet, dummy!
Step 5: Create an aspect. Here’s a (pretty useless) sample aspect that I used to test with:
Step 6: Use the aspect. In my case, it was simple as decorating an arbitrary method with the aspect attribute that I just created.
Step 7: Done! You can now use all the PostSharp AOP goodness in your MonoDroid app that you want to. Below is a logcat screenshot of my aspect in action.
Note that this scenario (PostSharp on MonoDroid) is not supported officially by SharpCrafters, so if you run into any problems, you’re more or less on you’re own. Gael was kind enough to push me in the right direction, and he might help you too, but don’t count on it.
It came to my attention recently that while the WordPress migration went generally well, it wasn’t properly handling a lot of the embedded Youtube videos. So, I wrote a little app to go through and do all the corrections (mostly just removing large swaths of whitespace). I have the old data backed up, so if you see anything that looks like it might have been mangled, let me know.
In the meantime, enjoy the fruits of my labors: my back catalog of old “Tuesday Tube” posts!
This has been a busy year, and I’m just going to use this post as a chance to reflect on what I’ve accomplished this year. I will then probably have a 2011 goals post later (probably right after Codemash).
I started this year still working for Quick Solutions. I had a great time at Codemash 2010, and learned quite a lot. Around this time I started meeting with a mentor at Quick and laying out some plans. I generally believe that plans are for fools, but I managed to accomplish most of my plans, in spirit at least, if not to the letter.
I had a goal to read a couple dev books each quarter. I didn’t read all the books that were on my list, but I did read roughly my targeted amount. Additionally, I captained a dev book club for a few months, which was a lot of fun, and was more fulfilling than just reading a book by myself.
I did take and pass the PMP exam, which seems like such a distant memory now. I’m not a project manager or a manager of any sort yet, but I’m confident that I will get there when I need to.
I have only contributed to OSS projects in minor, minor ways this year. This is definitely a failed goal. However, in terms of community involvement, I am quite active, and was just recently elected as an officer to the CONDG user group, and I also volunteered at Stir Trek to carry pizza boxes and stuff swag bags. So I’ve not just been sitting on my duff either.
I did not write a mobile development white paper. Instead, I’ve been participating in the MonoDroid private beta program, and I will be “co-presenting” with Bill Sempf at CodeMash on MonoDroid (and possible other conferences). I am currently working on a MonoDroid app, and I hope to release that to the marketplace soon.
I had a goal to give at least 3 presentations in the local dev community. Well, take out the word “local” and I accomplished that easily with presentations in Maryland, Virginia, and Grand Rapids, as well as a couple minor sessions at local events too. It also goes without saying that I attended plenty of conferences, local and otherwise.
I’ve been recently slacking on my Project Euler, but I have solved 65 problems, for an average of about 1.25 problems solved per week, which is actually must better than the goal I set for myself initially.
I also managed to take a new job with Telligent, and transition to being a remote worker.
All of this, and one other minor thing: my second child (Emma Groves) was born this year.
So, all in all, I’d say it’s a pretty darn successful year, and I have a lot to be proud of. I couldn’t have done it alone, of course. My wife Ali has been a constant support, especially through all the travel, late nights, studying, etc. Both of the companies I worked for this year have a ton of great people that I’ve leaned on for knowledge, support, and guidance. This includes Jayme Davis, Craig McKeachie, Jim Holmes, Chris Farrell, Craig Stuntz, all my Twitter friends, the team of guys at the AG, my current product team, anyone who still reads this blog, and many many others. A cast of thousands, if you will. Thank you, everyone.
Well, it’s been a long journey, but I’ve finally arrived at WordPress. In case you haven’t been here since the beginning, here’s a brief history of mgroves.com:
I first bought the domain/hosting through easycgi.com. I really didn’t have a clear reason why, but I put some stuff up there like my resume, some music reviews, and some other random junk. All static. I was employed with OSU, but not as a web developer.
Blogs and RSS were really starting to take off (not that they were brand new, but they were really getting popular) in late 2005. I decided that blogging might be fun, so I slapped together a home-made blog engine with PHP (which I was just starting to learn). I had a layout and structure similar to slashdot, and I borrowed the slashdot “image-representing-a-category” motif too. I had a table-based layout. Unlike slashdot, my site was really ugly.
A few months later, I moved to the web development group at OSU, which had a fantastic designer. He saw my site and practically hung himself. I convinced him to live, and also to make a nice new design for me. I also took that opportunity to improve my blog-engine a little bit as well.
Soon, I was posting like a madman, up to 3 times a day. Not particularly rich content, but certainly there was plenty of it. During this period, I reached the front page of Digg twice, once for a post I did about hidden stuff in logos, and once indirectly about AJAX (which was also becoming a big deal at the time). The traffic blew up my site (the fabled Digg effect), so I once again adjusted my blog engine to give it caching. Hotlinking was also sucking up a lot of bandwidth, so I adjusted my software to watermark every image. At some point, I switched hosting to Dreamhost to save some money (though I lost the ability to use ASP/ASP.NET, which I still kinda regret).
And that’s where I was for a long while. I got another redesign, and made minor tweaks here and there. I got a couple checks from Google AdSense, Commission Junction, etc. Not much, but it easily covered hosting. My blogging frequency dropped off when I was getting my MBA at night, and then dropped even further when my son was born.
Early last year, I decided that my blog engine was becoming too painful to use. I was married, had a kid, and didn’t have time for fooling around with my weak homegrown engine when there are so many free, feature-rich engines out there already. The Habari guys had visited the Columbus PHP Group, so I decided to give them a go. The migration from my database schema to their’s wasn’t too bad at all.
However, as much as I liked the Habari guys, and their ideas about blogging/CMS, Habari had some flaws, missing features, and wasn’t getting updated very much (one or two updates in a year). Sure, it’s open source and I could contribute, but that’s really at odds with my purpose for getting a blogging engine in the first place. In the interim, I had used WordPress for a couple of projects and sites here and there and really got to like it.
So, here I am. Static -> Custom blog engine -> More custom blog engine -> Habari -> WordPress.
Based on comments that an angry mob of EF users left, I decided that I needed to take another look at EF4.
First off: you can use POCOs in EF4 without the CTP. It can be done. Now please stop throwing bricks through my windows!
I did another spike branch using the above linked tutorial. Compared to the CTP code-first approach, it’s a tiny bit clunky, but compared to the standard inherit-from-EntityObject approach, it’s much much better. I think that you can use T4 to generate your POCOs from the class designer even, so that’s an option too.
Some other notes:
The repository implementation was exactly the same as before. Craig Stuntz, who has been extremely and selflessly helpful has suggested that I modify the repository slightly to use GetObjectStateEntry instead of checking if the id is 0. That is an idea that makes sense, but I just haven’t done it yet, as I still need to figure out the whole attached/detached thing and other implementation details of EF. But if I were you, I’d take his advice.
Let me withdraw my blanket “F” grade of EF. There are a lot of facets to EF, some of them get an “A” (code-first POCO) and some of them still get an “F” (EntityObject). Overall, EF4 gets a “passing” grade (hows that for diplomatic?).
Coming into these comparisons, NHibernate is the OR/M I’ve used the most, and the one I’m biased towards (although code-first POCOs in EF have really impressed me).
A brief overview of NHibernate if you’ve not used it before: It’s an OR/M just like EF, based on the Hibernate library from Java. Each class maps to a database object via an XML configuration file. An NHibernate “session” is opened to interact with the database (similar to an EF “context”). The biggest complaint about NHibernate is usually the messy XML files that needed to be created. Fluent NHibernate aims to solve that by moving these XML mapping files into C# mapping classes, so you get intellisense, compile time checking, etc, and as a bonus you get a fluent configuration API too. Another complaint about NH, is that for querying, NHibernate uses HQL, the Hibernate Query Language, and not Linq. I don’t really like the HQL API, so that’s why I like to use the NHiberate.Linq library as much as possible, which brings native Linq support to NHibernate. (If all these extra libraries seem intimidating, well, that’s what NuGet is for
Some more notes about Fluent NH:
While NHibernate allows us to use POCOs for our entity objects, one annoying thing is that the entity properties have to be marked as virtual. Other than that, they stay the same. While the ‘virtual’ thing isn’t a big deal, I think EF POCOs get the leg up here, as they require zero change to the actual entities.
I wrote a ProductMap class to do the object-relational mapping. However, there is also a convention-based approach that doesn’t require using explicit mapping classes. However, I’ve found that this can be more trouble than it’s worth for all but the very simplest domains.
There was some weirdness with NHibernate.Linq when I tried to select and order all distinct categories (see NavController here). The NHibernate.Linq library 1.0 release was late last year, and I think there is more work needed on it to get the Linq support up to snuff, but I think it’s 90% of the way there.
I used a session-per-request pattern via StructureMap and the EndRequest event in Global.asax.cs. This means that the repository doesn’t have to worry about opening/closing/disposing the NH session, and gives a basic unit-of-work pattern to each web server request. This can be implemented in other ways (HttpModule, for instance). I didn’t do this yet with EF, because doing it with NH has become a part of my normal NH ritual, I guess. I’ll definitely talk about this pattern in a separate post.
I had some trouble with the Image upload, and it’s because Fluent-NH doesn’t really know how to handle varbinary(max) by default (though regular NH appears to handle it fine). See this commit on Github to see how I got it to work. The image-stored-in-the-database thing has been a sticking point for both EF and NH, just in different ways. I usually prefer to store images in the file system, and if you do too, then this is pretty much a non-issue.
I’ve been throwing around this term: POCO this and POCO that. POCO stands for “Plain Old CLR Object”, and it just means that you can use a class with an OR/M without that class inheriting from some base class that the OR/M provides. Many OR/M users (including myself) prefer OR/Ms that support POCOs because it means that the OR/M technology can be confined to hide behind an interface, and the rest of the application doesn’t care which OR/M is being used.
As I showed in the last post, standard EF does not use POCOs and thus its tendrils snake throughout your application (though apparently there is a way to accomplish this without the CTP, I just haven’t figured it out yet). But never fear lovers of closed-sourced Microsoft sanctioned tools: EF will soon allow the use of POCOs. This “code first” method is the most appealing to me, because it reminds me the most of Fluent-NH (let me disclose that bias so you know where I’m coming from). Write a bunch of entity classes, then write a subclass of DbContext which contains DbSets of those classes. Use this DbContext subclass to interact with the database (the same API as the above two methods). Specify a standard SQL connection string (there’s a convention in place so that’s optional), and when the application first fires up that DbContext object, the SQL database/object will all be generated out on the db server. Nice.
Some more notes on code-first EF4:
This was a much, much easier implementation, obviously, since I could use my existing entities, no problem. I updated my StructureMap config to use the new implementation, and that was it. Again, I did not do a unit-of-work implementation yet for EF, so I still have to go back and do that.
A standard SQL connection string works fine.
While I found this implementation very easy, there are a lot of factors to consider when the tables are generated, hosed, and regenerated during development. If your testing involves some sort of data baseline, then it would be a good idea to run that baseline whenever the model changes during development (the generation/hosing/regeneration can be configured in the Application_Start event in the Global.asax.cs). If you are using a shared database, you should also be mindful when regenerating (or checking in changes that will cause regenerating), as this will hose all the data.
The code-first EF4 stuff is not part of the current EF4 release. It is CTP (community tech preview) 4, and thus the features & API are not set in stone. Check out ScottGu’s blog post for details and a download link.
I’ve never used EF before, and to be honest, I have pretty strong biases against it for a number of reasons. However, it deserves a fair shake, so here goes.

The standard EF approach is similar to Linq-to-SQL. You first create database objects (tables, views, SPs). Then you add a new “Entity Data Model” to the project, select the DB objects you want to model via a wizard, and EF will generate all the objects/SQL/etc that you need to interact with the database. (There is a “model first” approach where you define classes first and the SQL objects/scripts get generated. It’s essentially the same approach in reverse).
With standard EF4, POCOs can’t be used, so I basically had to rip out all references to my existing entities and replace them with EF4′s entities. This was painful just for this tiny app with one entity. Going back the other way would be equally painful. If I built the app to use EF objects in the first place, this part wouldn’t have been painful. However, as one of my goals is to keep the implementation behind an interface, using EF in the standard way simply doesn’t work.
Some more notes:
EF4 generates a wacky SQL connection string when creating the Data Model. Compared to the above offense of not using POCOs, this ranks pretty low as a problem.
Other than gutting my existing entities, implementing the repository interface was easy enough, but it took me a couple of commits to get it right, since I’ve never used EF4 before (have I mentioned?) I didn’t put a unit-of-work pattern into place, so I might still need to do that (and as I write this, that comment was just made to the previous blog post
.
One wacky thing to mention is the code to read an uploaded image via an input stream: it didn’t work if I used the entity’s property as a buffer directly, I had to switch to an intermediate buffer byte array.
Since the entity classes are generated, I had to put all the DataAnnotations metadata into their own “buddy” classes (see this commit). Opinions on buddy classes can vary widely. I’m not a big fan of the repeated bits of code, but I don’t think it’s necessarily a total dealbreaker.
My grade for standard EF is pretty much an “F”. Since POCOs aren’t used, EF gets its hooks in a large part of your code. This is the EF that I heard so many complaints and formed my biases about, and I now I can safely say it’s deserving. It might be a good solution for small, simple apps, and it makes a good demo, but that’s about all I can say positive about it.
HOWEVER, there is an EF4 POCO solution, and while it’s only a CTP right now, it’s very encouraging, and very interesting, and I’ll cover it in the next post.


