Getting Started with Android Development

March 7, 2010 13:02

Android

I've taken the plunge into Android development.

Coming from the .NET world and having programmed Java a very long time ago (back in 1995, which as I recall was right about when the language first came out), I was anxious—and a bit apprehensive—about where Java stood as well as how far the tools had progressed in the fifteen or so years since I last attempted to write my first Java program.

I'm happy to say that everything is good now, though because I've programmed in Microsoft environments almost exclusively since leaving college there were still some small hurdles and adjustments to make in getting comfortable with the tooling.

Let's start with the basics: Android applications are written in Java. The IDE of choice is Eclipse. Even though I'm just starting I'm seeing enough similarities between Java and some of the .NET languages (C#, specifically) that I'm beginning to think .NET wouldn't be so great were it not for Java (or maybe it's vice versa). In any case, the fact that there are so many similarities is a great boon to developers trying to cross-over.

For the rest of this post I'd like to go over what it takes to get started writing Android applications. I'll try not to repeat what's already been documented but rather point you to those sources. I've only been through the initial environment setup once, so parts of this will be a bit of a refresher for me, and gives me the opportunity to document the information and links for reference purposes, if nothing else.

Let's get started.

Required Components

There are a number of downloads, including:

1. The Android SDK

This is the core of the Android development platform. At minimum, you'll need to download and install the SDK.

2. The Eclipse IDE

You can write Android applications without an IDE, but why would you want to? Eclipse "Ganymede" is the recommended version. I downloaded and installed the "Eclipse IDE for Java Developers", though I think you can get by with the "Classic" version as well (it looks like the former just has more "stuff" in it).

3. Android Development Tools (ADT) Plugin

A must-have if you're going to use Eclipse for development. The ADT Plugin brings up a single dialog for new project creation and creates the basic application folder structure and minimum file set you need for a basic app.

Download & Install the SDK and Tools

If you click-through on items 1 and 3 above and check out Installing the Android SDK, you'll get a nice step-by-step walkthrough on how to download, install, and configure each piece. Not much point in me going into detail as I think the instructions on the Android site are pretty good.

When you've got everything installed, read through the "Hello, World" tutorial as it goes into how to create your first Android application.

Here's a couple more sources of information to help get you started:

Common Tasks

Common tasks and how to do them in Android.

Troubleshooting

Some of the more common issues you might run into and how to solve them.

Android FAQs

Framework, open source licensing, and security FAQs.

Android Discussion Groups

The Android Open Source Project mailing lists.

Writing Your First Android Application

I'm going to go over step-by-step how to go from nothing to a "stock" Android app. There really isn't much to it, so let's do this thing.

1.) "New" up an Android application

Assuming you installed the items listed above correctly, once you fire up Eclipse you'll see an "Android Project" option under the "File | New" menu:

image

Selecting "Android Project" brings up a single dialog from which we'll fill-out to create the new project:

image

2.) Specify the Project name

This is the name of your project. Pretty self-explanatory.

You'll see that as you fill in each section Eclipse (or, rather, the ADT Plugin) tells you what's still missing:

image

3.) Create New Project or From Existing Source or From Existing Sample

You've got three options here:

a. Create New Project to create a project from scratch

image

b. Create Project From Existing Source

image

If you already have a project from another source (like one of the samples that comes with the SDK), then select the "from existing source" option and specify the project's location.

c. Create Project from Existing Sample

If you specify a location then choose this option the dropdown will be populated with whatever projects are in that location.

image

4.) Choose the Build Target

This is one of the most important selections to make because it determines which version of the Android SDK must be installed on the target device (phone) for your application to run. Specify the most minimum SDK version possible if you want your app to run on the widest selection of phones. As I write this, many phones are still running Android 1.5 or 1.6; version 2.1 is running only on the newest, most advanced phones (though many phones are getting or will get the latest update as time goes on).

For this project, I'll just select Android 1.5:

image

5.) Specify Project Properties

image

Pretty straightforward step, though the conventions can be a bit of a mystery at first.

"Application Name" is the name of your application as it will appear on the Android device.

"Package Name" is the Java .apk package name. The naming convention for this is:

The prefix of a unique package name is always written in all-lowercase ASCII letters and should be one of the top-level domain names, currently com, edu, gov, mil, net, org, or one of the English two-letter codes identifying countries as specified in ISO Standard 3166, 1981.

Examples include:

com.sun.eng

com.apple.quicktime.v2

edu.cmu.cs.bovik.cheese

"Activity" is the subclass derived from the Android Activity parent class. While an activity is not necessary, any apps containing UI will use one as their starting point.

"Min SDK Version" is filled in automatically based on the "Build Target" selected above.

6.) Click Finish

Click "Finish" to complete the setup process and create your new project.

You now have the beginnings of an Android application. The starting folder structure looks like:

image

Conclusion

I really just wanted to document the basics in this post. Hopefully as I continue to dive deeper into Android development I'll be able to post about more specific, advanced topics. At this point, I've gone through the documentation, subscribed to the mailing lists, regularly watch Stackoverflow for Android specific questions, studied some of the samples, and written just one Android application though I've got another in progress. I don't own an Android phone yet, though with AT&T already selling one and soon-to-sell more, I know I'll have one soon.

Resources

On the Web – Reference and Info

Android Developers

This is Google's home for all things Android development. It includes instructions and information on how to get started, how to publish in the Android Marketplace, and has all the documentation you should need for Android development.

Android Developer's Guide

Fundamentals on up to more advanced topics.

Android Developer's Reference

Android API reference.

Official Android Developer's Blog

New happenings and such from the guys who created Android.

Stackoverflow "Android SDK" Questions

I subscribe to the RSS and keep up on the latest questions being asked that way.

Android and Me

News and information about the latest devices and software.

Android Community

Message boards where the overreaching topic is… Android.

Phandroid: Android Phone Fans

News and information about the latest devices and software.

Android Guys

News and information about the latest devices and software.

Code Conventions for the Java Programming Language

It's dated 1999, but this stuff doesn't go out of style.

 

On the Web – Demo Apps & Code

Android Developers Sample Apps

apps-for-android

 

On Twitter

My Android Twitter List (my Twitter list filled with Android goodness)

@androidtalk

@AndroidFroyo

@whatsupandroid

@androidandme

@androinica

@droidninja

@droid_life

@phandroid

 

Podcasts

AndroidGuys

Android and Me

Phandroid

 

[ Get 2GB of free online storage from Dropbox ]

[ Follow me on Twitter ]


Adding ELMAH to your ASP.NET Web Site

January 29, 2010 09:59

There's already a lot of posts out there on how to set up ELMAH (see References below). Still, as I went through the process of adding ELMAH to my own site, I found myself pulling information from multiple posts and even ran into a couple of surprises during deployment. So, in an effort to consolidate the information I needed and post solutions to the issues I had, I give you this post on the unhandled exception and error handling utility that is ELMAH.

What is ELMAH?

From the Google Code ELMAH home page:

ELMAH (Error Logging Modules and Handlers) is an application-wide error logging facility that is completely pluggable. It can be dynamically added to a running ASP.NET web application, or even all ASP.NET web applications on a machine, without any need for re-compilation or re-deployment.

In short, ELMAH is a utility that reports unhandled errors and exceptions. Looked at another way, ELMAH will display problems with your site that you might not otherwise see.

Adding ELMAH to an ASP.NET Web Site

1.) Get ELMAH

The first step is to actually get ELMAH. You can download from the Google Code page. Once you've got it, copy the file "Elmah.dll" into your site's bin folder.

2.) Modifying your web.config

There are a couple of initial modifications you'll have to make to your web.config:

a.) Add the following to the <httpModules> section:

<add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah"/>

b.) Add the following to the <httpHandlers> section:

<add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" />

3.) Deployment and dealing with initial issues

For the most basic ELMAH setup, that's it. You should be able to access your site's ELMAH logs by accessing http://yoursite/elmah.axd.

However, once you've deployed you might run into this error:

You are attempting to access ELMAH from a remote machine whereas it is currently configured not to allow remote access.

image

Fortunately, getting around this is pretty easy.

a.) Like it says, add a new <sectionGroup>:

<sectionGroup name="elmah">
    <section name="security" type="Elmah.SecuritySectionHandler, Elmah" />
</sectionGroup>

b.) Also, add the <elmah> section. I added it right underneath my <configSection> closing tag.

<elmah>
    <security allowRemoteAccess="yes" />
</elmah>

Again, redeploy the web.config file and we're done.

Except that, now, everyone in the world can view your ELMAH logs. Not good.

Securing ELMAH against unwanted eyes

Allowing everyone to view your ELMAH logs is generally not a good thing because an astute hacker could easily glean information from those logs and potentially exploit your site. So, we'll add some basic security.

1.) Include the admin path

Include the admin path in the httpHandler "add" so it looks like:

<add verb="POST,GET,HEAD" path="/admin/elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" />

2.) Add a <location> section

This stands as it's own sub-section beneath the main <configuration> tag:

<location path="admin">
    <system.web>
        <authorization>
            <deny users="?"/>
        </authorization>
    </system.web>
</location>

Now, we're done. When you access http://yoursite/admin/elmah.axd, you should be prompted for your credentials (assuming you're using ASP.NET's built-in security; see Phil Haack's post for more info).

If you're using BlogEngine.NET, add ELMAH to your admin menu

This is just an ease-of-access thing. If you add ELMAH to your web.sitemap, BlogEngine.NET will automatically pick it up and display in your admin menu.

Just add this to your sitemap file:

<siteMapNode url="~/admin/elmah.axd" title="ELMAH" description="" roles="administrators"/>

Conclusion

This concludes our discussion on how to add ELMAH to an ASP.NET web site.

References

 

[ Get 2GB of free online storage from Dropbox ]


The IIS SEO Toolkit

December 27, 2009 16:09

Scott Guthrie recently gave a shout-out to the IIS SEO Toolkit on his blog. I don't know about you, but something about SEO always brings up thoughts of greasy salesmen and used cars. Best purge those preconceptions from your mind, though, cause SEO is important.

Even excepting SEO, the SEO Toolkit is a great way to find other issues with a web site. For example, large content files (such as images, which can probably be shrunk down), duplicate keywords, missing meta information, missing content, and other information will all be revealed once you run the Toolkit against your site.

Scott gives a nice overview of the tool; I'll let his discussion get you started and jump right into what the tool showed me.

SEO Toolkit Analysis

Upon running your first analysis you'll get something like this (I ran the analysis against my fiction site, scottmarlowe.com):

image

The statistic I'm most concerned with is the "Number of Violations". I've got over 37,000 of them!

Turns out it's not as bad as it may seem, or not as difficult to whittle that number down anyway. Here is the breakdown of violations:

image

Let's take a look at the big ones (the ones with the highest counts).

1. The page contains unnecessary redirects

Turns out most of these are of this variety:

image

The first link it is indicating is a permalink for a blog post that looks like this:

<a rel="bookmark" href="http://www.scottmarlowe.com/post.aspx? id=f3dc138a-e948-4613-b546-d805fb2703c5">Permalink</a>

This forum post suggests a quick fix for this:

For this particular URL I would consider adding a "nofollow" to the link…

I use BlogEngine.NET; the permalinks were created with "rel=bookmark" already. I couldn't find a whole lot more than this as far as what "bookmark" buys me:

 

Bookmark Refers to a bookmark. A bookmark is a link to a key entry point within an extended document. The title attribute may be used, for example, to label the bookmark. Note that several bookmarks may be defined in each document.

 

But just in case, I also learned that you can specify multiple "rel" tokens just by putting some whitespace between them:

<a rel="bookmark nofollow" href="http://www.scottmarlowe.com/post.aspx? id=f3dc138a-e948-4613-b546-d805fb2703c5">Permalink</a>

That should do it for that violation.

2. The title begins with a brand name

Here are the details:

Search engines often parse text so that words that appear earlier in a sentence are weighted higher than words that appear near the end of a sentence.  Page relevancy is calculated by the use of important keywords that describe the page content. A page about a specific topic should use a keyword related to that topic at the beginning of the <title> tag instead of using a site name or brand name ("scottmarlowe"), because those do not describe the contents on the page.

This one was easy to fix. I'd been using the format "scottmarlowe.com - <page name>" as the title of my document (web page), so based on the recommendation I simply flipped the title so it reads "<page name> – scottmarlowe.com".

3. The page contains multiple canonical formats

A good discussion of this particular violation can be found on the CarlosAg Blog in the post Canonical Formats and Query Strings - IIS SEO Toolkit. The details for one of the violations of this type from my Toolkit analysis reads:

The page with URL "http://www.scottmarlowe.com/category/Book-Reviews.aspx" can also be accessed by using URL "http://www.scottmarlowe.com/category/Book-Reviews.aspx?page=1".
Search engines identify unique pages by using URLs.  When a single page can be accessed by using any one of multiple URLs, a search engine assumes that there are multiple unique pages. Use a single URL to reference a page to prevent dilution of page relevance. You can prevent dilution by following a standard URL format.

I saw two ways of dealing with this violation:

a. Add a Disallow in robots.txt

Add the following to your robots.txt:

Disallow: /*?

This will prevent search bots from using other avenues to access a page they would have already indexed via the main url. This is the approach I took.

b. Add a <link> with rel="canonical"

Add the following for each link:

<link rel="canonical" href="http://www.my-site.com/my-canonical-url" />

Note that this is new and may not be supported by all search engines.

4. The request is disallowed by a Robots.txt rule

This one was informational, and, in fact, was a non-issue as the pages excluded from crawling by my robots.txt were not supposed to be crawled.

5. Large Content Files

The SEO Toolkit does a nice job of displaying your largest files:

image

In my case, I had a few image files that were part of different blog posts that were shrunk when displayed but were, in fact, quite large. A lot of bandwidth was being wasted downloading the oversized images before they were scaled down and rendered on the client machine. Identifying the pages where those images were being used was pretty easy. Just right-click on the image in question and select "View Pages Linking to this Page":

image

I realized I could live without the images on those particular posts so I simply deleted them from the pages where they were being used.

6. Duplicate Description

This turned out to be a programming problem where many pages were having the meta description set twice. I corrected the code and hope to not see the violation again the next time I run the analysis.

Some oddities

The SEO Toolkit does have some known problems. After running my fifth or so analysis I all of a sudden starting seeing the error "Invalid name character… The ':' character, hexadecimal value 0x3A, cannot be included in a name":

image

Turns out this is a known mishandling of meta information by the Toolkit and that there should be a fix released sometime soon. I'll update this post once they do.

Unfortunately this error prevented me from running any more analysis of my site, so I'll have to wait until the fix is released to verify if I've fixed the major violations.

Conclusion

SEO is an often mal-used term, but that doesn't change the fact that it is important if you want to make your site as search engine friendly as possible. The SEO Toolkit is a fast, easy way to help out with this.


Writing a (Completely Useless) Windows 7 Gadget using Silverlight

November 11, 2009 20:12

At its simplest form a Windows gadget is comprised of a .html file and a .xml file. Think of it as a mini-web site, with the .html file representing the site's visual components and the .xml file the gadget config or definition. Of course, as a web site, most gadgets are going to have the usual suspects: css, JavaScript, image files, and—best of all—Silverlight.

The purpose of this post is to allow me to do some research on what Windows gadgets are, how to write them, and, most importantly, how to leverage Silverlight to make gadget development easier and more fun.

What is a Windows Gadget?

When I ask this question, I mean what is a Windows gadget, really? I already know what they are, but what's inside the .gadget file? It's easy to see. Gadget files, which use the .gadget file extension, are just compressed .zip files (much like a .xap in Silverlight). If you change the .gadget extension to .zip, you can then view the files inside just like any other ZIP archive.

Conversely, when you install a .gadget file, its contents are uncompressed to the following location:

C:\Users\<username>\AppData\Local\Microsoft\Windows Sidebar\Gadgets

I'll take a quick look at The Weather Channel gadget (one of the best, IMO):

image

As you can see, it has all the basic components of a standard web site. There are multiple .html files because this gadget, like many others, has a variety of views, each one based on the different gadget states: docked, undocked, fly-out (floating).

The XML Definition File

When you get down to it, the XML definition/config file (not really sure what to call it) is the only thing new. The rest of the gadget is stuff we've seen before.

Here's the generic layout of the .xml definition file, stolen borrowed from Donavon West's Build Your Own Windows Vista Sidebar Gadget article on MSDN:

   1: <?xml version=”1.0encoding=”utf-8” ?>
   2: <gadget>
   3:   <name>Gadget Name Here</name>
   4:   <namespace>YourCompanyNameHere</namespace>
   5:   <version>1.0.0.0</version>
   6:   <author name=”Company Name Here>
   7:     <info url=”http://contoso.comtext=”Visit our Web site/>
   8:     <logo src=”logo.png/>
   9:   </author>
  10:   <copyright>&#0169; 2007</copyright>
  11:   <description>your gadget description</description>
  12:   <icons>
  13:     <icon width=”64height=”64src=”icon.png/>
  14:   </icons>
  15:   <hosts>
  16:     <host name=”sidebar>
  17:       <base type=”HTMLapiVersion=”1.0.0src=”gadget.html/>
  18:       <permissions>full</permissions>
  19:       <platform minPlatformVersion=”0.3/>
  20:     </host>
  21:   </hosts>
  22: </gadget>

Donavon says this about the XML content:

Most of the elements in the definition file are used for displaying the gadget in the gallery. The one truly functional element is the src attribute of the base element—this points to the HTML file that will kickstart the gadget. I make it a practice to name this file gadget.html, but any valid filename will do.

So it's the XML file that acts as a bridge between the gadget hosting app (still sidebar.exe in Windows 7) and the gadget itself.

Creating a Windows Gadget using Silverlight

Creating a gadget that uses Silverlight is surprisingly easy.

1.) Start with a basic Silverlight Application project:

image

I'll call mine SilverlightGadget.

I'll host the control in an ASP.NET Web Site and use Silverlight 3:

image

 

Once the project is created, you can delete the SilverlightGadgetTestPage.aspx from the web site (we aren't going to use it). I also renamed the SilverlightGadgetTestPage.html file to just gadget.html as Donavon recommends.

2.) Next, add a new .xml file to the web site. I called this file gadget.xml to match the naming of the HTML file. Copy the generic <gadget> contents shown above into this new file. You can update information in the file as you see fit. For purposes of this demo, I'll just leave it the way it is except for the gadget's <name> which I'll call SilverlightGadget. The really important line is this file is:

<base type="HTML" apiVersion="1.0.0" src="gadget.html" />

Make sure "src" points to your HTML file.

3.) In gadget.html, we have a couple of changes to make:

a. Make the "html, body" style read "height: 80px; width: 130px;"

   1: html, body {
   2:     height: 80px;
   3:     width: 130px;
   4: }

Make sure to remove the overflow style. It was causing me problems, specifically causing horizontal and vertical scrollbars to display.

The height value was arbitrary; you'll want to adjust based on the content of your gadget. But the width of 130px was a maximum under Vista for a docked gadget. In Windows 7, however, this doesn't seem to apply as I was able to make the gadget as wide as I wanted. Still, all of the other docked gadgets that I have do not exceed this width, so I went with the standard 130px.

b. Add the following param to the list of object <param> tags:

<param name="windowless" value="true" />

This seemed to have the effect of enabling the gadget handles when you mouseover the gadget.

4.) Now, in the XAML, I'll remove the height and width attributes from the UserControl and add a simple button inside the default grid. This gives me:

   1: <UserControl x:Class="SilverlightGadget.MainPage"
   2:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   3:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   4:     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
   5:     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
   6:     mc:Ignorable="d">
   7:  
   8:     <Grid x:Name="LayoutRoot" Background="RosyBrown">
   9:         <Button Background="AliceBlue" Width="70" Height="30" Content="Click"  />
  10:     </Grid>
  11: </UserControl>

Yes, I do realize this is a completely useless Silverlight control, but, for now, I'm just trying to demonstrate how to build the gadget by laying some groundwork. Perhaps in a future post I'll share some more useful Silverlight controls to host inside a gadget.

That should be it for the project/code changes. Now, let's install the gadget and see just how useless my one button control is.

Installing the Silverlight Gadget

As mentioned above, a gadget is a just a zip file with the extension .gadget. The easiest way to create a .gadget file is therefore to just use your favorite zip program. Mine is 7za, which I use inside a batch file so that I just double-click or run the batch file from the command line in order to both create and install the gadget.

Here's the sequence of commands (I run this from the project root; the batch file sits alongside the .sln file):

   1: cd SilverlightGadget.Web
   2: del *.gadget
   3: 7za a -r silverlightgadget.zip *
   4: rename *.zip *.gadget
   5: silverlightgadget.gadget
   6: cd ..

I'm just zipping up the whole web site, including the .xap and even the web.config, which isn't needed but this is just demo code so who cares. ;-)

Installing the gadget is as easy as double-clicking the .gadget file or typing the name at the command line and hitting enter. You'll be prompted to install the gadget. Click "Install" and prepared to be impressed:

image

Here it is alongside some other gadgets for better context:

image

Conclusion

While there are a handful of manual steps involved in creating a Silverlight gadget, they're fairly easy ones. It would be great if Visual Studio just had a project template for this, but it doesn't. There are, however, some alternatives out there, including one that does not create a base Silverlight project by Tim Heuer and another by Ioan Lazarciuc which does, but which creates a plethora of projects in the process. In other words, I haven't found a satisfactory Silverlight gadget template yet, so the above steps will have to do for the time being.

Download: SilverlightGadget.zip (solution in VS2010 format)

Resources

[Follow me on Twitter]