Custom HTML "Widgets" for ASP.NET MVC3

I was experimenting with ASP.NET MVC3 and found myself in need of some HTML outputted by the Razor engine that would need to be used many times. I wanted to follow the DRY (Don't Repeat Yourself) principle by having the HTML appear in one spot and allow me to use it many times. Ideally I wanted something like the builtin HTML "widgets".

   @Html.DropDownList("DropDownID", Model.Items)

The way I accomplished this was extension methods. Extension methods are an interesting way to add functionality to a class without inheritence. There are drawbacks, such as not being able to access protected members of the base class, but for some cases this is ok.

I decided to use extension methods to add a method to the class that corresponded to the @Html object in the Razor engine. I found out that this class was the HtmlHelper class in the System.Web.Mvc namespace. By extending the HtmlHelper class via extension methods, I was able to achieve my goal of adding a custom widget.

namespace MvcHtml
{
   using System.Web.Mvc;

   public static class ExtensionHtml
   {
      public static MvcHtmlString CustomWidget(this HtmlHelper htmlHelper, string property)
      {
         TagBuilder tagBuilder = new TagBuilder("div");
         tagBuilder.SetInnerText(property);
         return new MvcHtmlString(tagBuilder.ToString());
      }
   }
}

After this little bit of work, we are ready to use the custom widget in our view template just as traditional widgets provided for us.

   @Html.CustomWidget("SampleProperty")

I hope this helps people understand how Razor is producing HTML from these view files!

Combining the Decorator Pattern with the Template Method Pattern

Design patterns are exactly that, patterns of design. These patterns have been determined to appear frequently throughout software development. These patterns appear so often that they have become well documented and given names. I cannot recommend more highly the book Design Patterns by the "Gang of Four" as a resource on the topic of patterns. Recently I came across the need to combine to of the most common patterns, the decorator pattern and the template method pattern. I needed multiple implementation of a class to simultaneously coexist, the template method pattern, and I also needed to be able to decorate these classes, the decorator pattern. I noticed that while combining these two patterns, the decorator class behaves just as another class that implements the template method.
/* The template method */
interface AbstractClass
{
   void Method();
}

/* One implementation */
class ConcreteClass1 : AbstractClass
{
   public void Method()
   {
      System.Console.WriteLine("   ConcreteClass1");
   }
}

/* Second implementation */
class ConcreteClass2 : AbstractClass
{
   public void Method()
   {
      System.Console.WriteLine("   ConcreteClass2");
   }
}

/* Now comes the decorator, which feels just like any other implementation */
abstract class AbstractClassDecorator : AbstractClass
{
   public AbstractClassDecorator(AbstractClass abstractClass)
   {
      this.abstractClass = abstractClass;
   }

   public virtual void Method()
   {
      this.abstractClass.Method();
   }

   protected AbstractClass abstractClass;
}
Now it becomes time to implement the decorators. The nice thing about the decorator pattern is that it allows you to add decorators simply by extending a class. Here I have two decorators.
class ConcreteDecoratedAbstractClass1 : AbstractClassDecorator
{
   public ConcreteDecoratedAbstractClass1(AbstractClass abstractClass)
      : base(abstractClass)
   {
   }

   public override void Method()
   {
      this.abstractClass.Method();
      System.Console.WriteLine("   Decorator1");
   }
}

class ConcreteDecoratedAbstractClass2 : AbstractClassDecorator
{
   public ConcreteDecoratedAbstractClass2(AbstractClass abstractClass)
      : base(abstractClass)
   {
   }

   public override void Method()
   {
      this.abstractClass.Method();
      System.Console.WriteLine("   Decorator2");
   }
}
And now that the patterns are in place, all we have to do is simply use them. Because of the decoration and template pattern, we are able to create many possibilities to execute the "same" method. We can decorate or not decorate with any of the decorators, and we have multiple implementations of each method.
class Program
{
   static void Main(string[] args)
   {
      AbstractClass concrete1 = new ConcreteClass1();
      AbstractClass concrete2 = new ConcreteClass2();
      ConcreteDecoratedAbstractClass1 decorated1Concrete1 = new ConcreteDecoratedAbstractClass1(concrete1);
      ConcreteDecoratedAbstractClass1 decorated1Concrete2 = new ConcreteDecoratedAbstractClass1(concrete2);
      ConcreteDecoratedAbstractClass2 decorated2Concrete1 = new ConcreteDecoratedAbstractClass2(concrete1);
      ConcreteDecoratedAbstractClass2 decorated2Concrete2 = new ConcreteDecoratedAbstractClass2(concrete2);
      ConcreteDecoratedAbstractClass2 decorated21Concrete1 = new ConcreteDecoratedAbstractClass2(decorated1Concrete1);
      /* Et cetra */

      System.Console.WriteLine("Implementaiton 1");
      concrete1.Method();

      System.Console.WriteLine("Implementation 2");
      concrete2.Method();

      System.Console.WriteLine("Implementation 1 decorated by decorator 1");
      decorated1Concrete1.Method();

      System.Console.WriteLine("Implementation 2 decorated by decorator 1");
      decorated1Concrete2.Method();

      System.Console.WriteLine("Implementation 1 decorated by decorator 2");
      decorated2Concrete1.Method();

      System.Console.WriteLine("Implementation 2 decorated by decorator 2");
      decorated2Concrete2.Method();

      System.Console.WriteLine("Implementation 1 decorated by decorator 1 and decorator 2");
      decorated21Concrete1.Method();
}
This program outputs
Implementaiton 1
   ConcreteClass1
Implementation 2
   ConcreteClass2
Implementation 1 decorated by decorator 1
   ConcreteClass1
   Decorator1
Implementation 2 decorated by decorator 1
   ConcreteClass2
   Decorator1
Implementation 1 decorated by decorator 2
   ConcreteClass1
   Decorator2
Implementation 2 decorated by decorator 2
   ConcreteClass2
   Decorator2
Implementation 1 decorated by decorator 1 and decorator 2
   ConcreteClass1
   Decorator1
   Decorator2
I hope that this was informative in demonstrating the power of patterns and how they can be combined for even greater utility. Please feel free to comment below.

Scrobbler support in DAAP

A popular feature request for DAAP has been Last.fm's Scrobbler support. Scrobbling is a mechanism that allows Last.fm to know what songs you listen to on your personal devices, such as iPods, computer, or your Android device. This allows Last.fm to personalize which songs to suggest more quickly than normal. Big thanks to my brother Michael for implementing this.

The feature is pretty straight forward. First, a Scrobbling application must be installed on your device. For this version, Scrobbling has been tested with scrobbledroid and A Simple Last.fm Scrobbler. Next, navigating to the preferences via Menu -> Preferences from the Servers screen presents an option to enable this feature. From now on, your music listening will be relayed to your Scrobbling application which in turn relays that to your Last.fm account! No interaction required.

You can download DAAP via the android market by
  1. The Android Market Application
  2. Scanning the tag

Don't forget about DAAP

I recently updated some of the Android applications my brother and I have on the market. I left out by far the most popular application that we have. I have now fixed that. The DAAP application last night received a small but very useful bug fix. I expect more features to come out for the application in due time.

The bug fixed was a user experience (UX) design bug. Take the following scenario for instance: Select a song to play. Upon selection, the notification appears and you are free to continue using your phone for other purposes. Suppose that then you decided to return to the home screen or another application via repeatedly pressing the back button on the phone. You can use your phone, but if you returned to the DAAP application, you would have to re-login. If you clicked the notification, there was no way to return to the song selection screen. Essentially there was no way to return to pick a new song without re-logging in, a time consuming process.

The fix was easy. I added a new menu option on the media player (the screen viewed after clicking the notification) that allows you to return to the playlists. To prevent overloading of the menu options, I moved the shuffle and repeat buttons onto the screen. They are viewable at all times now. A screenshot below is included for demonstration purposes.


You can download DAAP via the android market by
  1. The Android Market Application
  2. Scanning the tag

Updates to mOTP and Utlimate Search Widget

I have finally found some free time to fix things that have been bothering me in my Android applications. That means updates!

First, I have fixed a minor bug in the mOTP application affecting some users. The bug was a simple oversight when originally implementing profile editing. When editing TOTP profiles with a non-default time interval, the time interval would  be listed as default. The fix was simple: pre-populate the spinner similar to how the other fields operate.

The second update was much more demanding. The Ultimate Search Widget application had no support for custom search providers. For instance, if I wanted to search my blog using the widget, I could not. I was restricted to a predefined list of search providers. Also, if I constantly switched between providers, I would have to scroll through the huge list of providers to find the search provider I wanted.

I solved the first problem by adding support for custom search providers. Simply fill in the name of the provider, the URL portion that appears before the query, the URL portion that appears after the query, and you are set.


Now this newly created search provider will appear in the list of providers when clicking the icon on the left hand side of the widget!

To fix the second problem, I added a preference type screen where you may click which providers are to appear in the list. This allows you to remove unused providers and make the widget more useful when frequently switching between search providers.


You can find both of the newly updated applications in The Android Market:
 
 

Integrating Doxygen with Autotools

For my thesis source code, I desired to have Doxygen documentation automatically generated by make. However, after searching the Internet, I was unable to find a decent tutorial. Luckily after reading the great book that I cannot recommend enough, A Practitioner's Guide to GNU Autoconf, Automake, and Libtool by John Calcote, I learned a great solution. I intend to outline that solution based off his book.

The first step is to decide how the process will work. In my case, I wrote documentation for a library that I plan for other developers to use. I want the documentation to be able to be viewed using the man utility. The documentation should be generated when the user runs 'make' and should be installed when the user runs 'make install'. If doxygen is not installed, output a warning message during configuration and do not generate any documentation.

The first step is to determine if the user has Doxygen installed. We can do this by searching for the Doxygen program using the Autoconf macro AC_CHECK_PROGS. If Doxygen is not found, output a warning message. We can put all of this logic in an m4 script or in-line in the configure.ac file. For this example, I will just put this in configure.ac:
AC_CHECK_PROGS([DOXYGEN], [doxygen])
if test -z "$DOXYGEN";
   then AC_MSG_WARN([Doxygen not found - continuing without Doxygen support])
fi


Now in configure.ac, we can check to see if we have Doxygen and if so, add some files to later be processed.
AM_CONDITIONAL([HAVE_DOXYGEN],
[test -n "$DOXYGEN"])AM_COND_IF([HAVE_DOXYGEN], [AC_CONFIG_FILES([docs/Doxyfile])])


We see a mention to 'docs/Doxyfile' above. To any Autotools users, this should outline the next step, to write the 'Doxyfile.in' file. This is a file that will be transformed into 'Doxyfile', which will control how Doxygen generates the documentation. The reason we describe the configuration file in a way that configure modifies it is in case that we want certain properties of the documentation to be configurable. For example, we could add a configure option to optionally generate html documentation, --enable-html-doc for example.

In the subdirectory docs of the project, we can start by running:
doxygen -g Doxyfile.in
This generates a template configuration file for Doxygen that we can modify to get our final configuration file. We need to supply the project name, project version, and any other options determined by configure. Change the following properties as below:
PROJECT_NAME = @PACKAGE_NAME@
PROJECT_NUMBER = @PACKAGE_VERSION@
INPUT = @top_srcdir@
Be sure to change other options that you desire, such as HTML output, man output, etc.


Now that we have a configuration file ready to be parsed by configuration script, we need to tell Automake to generate makefiles that have rules to generate the actual documentation. In the docs subdirectory, we can create the 'Makefile.am' file that will be transformed by automake into 'Makefile'. Here is a what it looks like:
if HAVE_DOXYGEN
directory = $(top_srcdir)/docs/man/man3/

dist_man_MANS = $(directory)/man_page_1.3 $(directory)/man_page_2.3
$(directory)/man_page_1.3: doxyfile.stamp
$(directory)/man_page_2.3: doxyfile.stamp

doxyfile.stamp:
   $(DOXYGEN) Doxyfile
   echo Timestamp > doxyfile.stamp

CLEANFILES = doxyfile.stamp

all-local: doxyfile.stamp
clean-local:
   rm -rf $(top_srcdir)/docs/man
endif

Now let's look at this carefully. The first thing that you should notice is that all the rules are only generated if configure set HAVE_DOXYGEN. We can see in the m4 code above that this is set is Doxygen is found.

Next we set up a convenience variable directory to save typing later on. Then we set the man pages that we wish to install when 'make install' is called. We set up a "Product List Variable" dist_man_MANS. This is a normal product list variable with a dist modifier. This means that we want to install these files when we run 'make install'. The man_ portion is the prefix, meaning we want to install these files in the $(mandir) directory. This is set by configure. The MANS portion of this product list is one of the primaries telling Autoconf which types of files are in this list.

We need make rules to build these man pages during the make stage. To do this, we make a rule for each man page to be installed, each one depending on a file called doxyfile.stamp. The reason we use one file is because of the one to many relationship between the one doxygen command and the many files generated. We need to be able to determine when we need to generate documentation, but which file do we check for. It doesn't make sense to pick one documentation file at random and check for its existence, so we use this solution.

The doxyfile.stamp target will generate the documentation by using the $DOXYGEN file determined by configure and the 'Doxyfile' generated from 'Doxyfile.in'. This target must also generate the doxyfile.stamp file also so future documentation file dependency checks are satisfied.

Now we need to tell Automake we want these built not at 'make install' time, but at 'make' time. To do this, we use a hook to the normal all target. By making the target all-local, we are making a target that will get executed before the normal all target. Now we are set. Make will install the man pages with the 'make install' command as we use the product list man_MANS with the dist prefix. We just need to handle cleaning up files on make clean. To do this, we add the 'doxyfile.stamp' file to the CLEANFILES list. This list is automatically cleaned when 'make clean' is run. To remove the directory of man pages is slightly different though. We can't easily remove a directory using the CLEANFILES variable. We simply hook into clean as we did with all and manually remove the directory.

Now we are set and ready to go. Please comment on improvements or errors in my guide.

Network Information

Whenever you join a company's, campus's, or employer's wireless network, does it ever feel like it is missing something? For instance, when you go to a cafe and join their wireless, there is a disconnect between the companies offerings (coffee) and the service you just received (wireless connectivity). Earlier in the semester I thought of a system that would bridge this disconnect. The system would provide information about the network which was recently joined. The information could be anything, but should be tailored to the company providing the wireless. An example of this could be the cafe providing information of products, sales, contact information, or privacy information regarding the internet.

To accomplish this, there would be some server running (could be the router providing internet/wireless) that would store the information to be provided. The information could be stored in anyway, but for me I chose to use XML as there are many parsers available. Here is an example of such an XML file describing the network, and some upcoming events.

 <Network>  
   <name>University of New Orleans</name>  
   <link>http://www.uno.edu</link>  
   <policy>http://www.uno.edu/NonDiscrimination.asp</policy>  
   <Events>  
    <Event>  
      <title>Party at the library</title>  
      <description>Free food</description>  
      <eventLocation>Library</eventLocation>  
      <dtstart>1288515600000</dtstart>  
      <dtend>1288522800000</dtend>  
    </Event>  
    <Event>  
      <title>Campus Meeting</title>  
      <description>Talk with the governor</description>  
      <eventLocation>Administration building</eventLocation>  
      <dtstart>1293890400000</dtstart>  
      <dtend>1293901200000</dtend>  
    </Event>  
   </Events>  
 </Network>  

This XML file describes a campus network that may wish to provide students and other network users of upcoming events, but the idea is clear that other types of information may be presented as described above.

For one of my classes, I decided to craft this idea into an Android project. The fun part about this is that I would use service discovery to automatically discover the server on the network providing the information. This is in contrast to perhaps a static network address or some DHCP information similar to DNS information.

I chose to use zeroconf technology for the service discovery as there was an easy to use java version of mDNS (a portion of zeroconf) that I used for DAAP that works nicely in this situation (well not so nicely, but it works). The idea is that the network server that is providing the information, also registers a service of a network-info service type and clients that join the network request services of the network-info service type that was registered. The server responds and provides the information, which the client displays.

I created an Avahi XML file describing the service so that it would be automatically broadcast on boot. Avahi is an open source implementation of zeroconf and provides utilities such as this to advertise services.

<?xml version="1.0" standalone='no'?>  <!DOCTYPE service-group SYSTEM "avahi-service.dtd">  <service-group>    <name>UNO</name>    <service>     <type>_netfo._tcp</type>     <port>9090</port>    </service>  </service-group>  So now that the service is advertised and the information being provided is set up, we just need clients to connect.

Here are the screenshots of the implementation I wrote for my mobile computing class.

Screen presented after a server is discovered and information provided.
Screen presented when an even was clicked, providing more information.
 This is great. Imagine all the possibilities of having information from your network. If there are any great ideas that could take advantage of this, feel free to comment with them! One idea that I came up with after beginning the project is an emergency channel. Take the university campus example for instance. Imagine that campus police spotted an armed individual and wanted to alert everyone in as many ways as possible. They can send mass emergency texts, emails, etc. Using the clients connected and listening to network information could be alerted also. I wrote this quickly for the android application as well.

Clients receive a notification upon emergency information becoming available.

Information presented when the emergency is clicked.
Ok, so maybe budget cuts aren't as scary as armed individuals, but they are scary!