Generating an Image of a PDF Page

I recently completed a project that required a thumbnail image automatically be generated from the first page of every PDF file that is uploaded to the system.  I was rather surprised to find that there was no drop in solution for such a thing.  There are many libraries out there that can create a PDF file from HTML content or an image, but no standalone libraries that could go from PDF to an image.  After testing out a couple of methods, I was able to find what I believe to be the easiest and least invasive method to implement it in a web application..

What You Will Need

To generate images from PDF in your project, you will need a couple of things.

Ghostscript, a set of libraries for working with a PDF.  You will need to download the version specific to your environment (32 bit/64 bit).  You can download those here.

GhostscriptSharp, a wrapper for using the Ghostscript libraries in .NET.  You can download it here.  It is written in C#, so if you are using VB.NET you will need to create a code sub-directory in your Web.config to use the file in your project.

Setup

You will need to do a couple of things to get the Ghostscript components to function before you write any code.  First, you need to extract the gsdll file to a location on your system.  (Either gsdll32.dll or gsdll64.dll depending on your CPU.)

Then, you need to modify GhostscriptSharp.cs to specify the path to the Ghostscript library that you extracted before.  Look for this code on line 12 of the GhostscriptSharp.cs file:

#region Hooks into Ghostscript DLL

[DllImport("gsdll64.dll", EntryPoint = "gsapi_new_instance")]

private static extern int CreateAPIInstance(out IntPtr pinstance, IntPtr caller_handle);

[DllImport("gsdll64.dll", EntryPoint = "gsapi_init_with_args")]

private static extern int InitAPI(IntPtr instance, int argc, string[] argv);

[DllImport("gsdll64.dll", EntryPoint = "gsapi_exit")]

private static extern int ExitAPI(IntPtr instance);

[DllImport("gsdll64.dll", EntryPoint = "gsapi_delete_instance")]

private static extern void DeleteAPIInstance(IntPtr instance);

#endregion

You will need to change the paths in the DllImport constructors to the location of the file on your machine.  The DllImportAttribute only accepts a constant string, so you cannot pass a variable with the path or using a Web.config value.  This prevents you from using Server.MapPath to generate the path to your project’s bin folder, which is also unfortunate.

The Code

The actual implementation of the image generation from PDF is very simple once you have reached this point.  You just need to make a call to the GhostscriptWrapper.GeneratePageThumb method with the path to the PDF, and the path where the image should be saved.  You also specify the page number you want to generate from and the height and width of the final image.  A call to GeneratePageThumb might look like this:

// Creates a 100 x 100 thumbnail of page 1.
GhostscriptWrapper.GeneratePageThumb(pdfFileName, outputFileName, 1, 100, 100);

You will also need to import the GhostscriptSharp namespace in your code file.  That is all that there is to it!  After running your application, you will see the image file in the specified path.

Its important to note that GeneratePageThumb is a shortcut method that will only generate a JPG image.  If you need to have more control over the output of your image, then you will need to use the GenerateOutput method and pass in a GhostscriptSettings object that contains all of your required values.  The GhostscriptSharp link above provides more detailed examples if you need them.

Thanks for reading!  If you have any troubles with the process, feel free to leave a comment below.

Fixing reCAPTCHA.net 404 Errors

Last week, Google decommissioned the reCAPTCHA API components that were hosted on recaptcha.net.  According to reCAPTCHA support, the change was supposed to have occurred back in April, but for some reason or another the site has only now been replaced with a 404 error.

The good news is that Google has not made any changes to the reCAPTCHA API, so you will just need to change the reCAPTCHA path from the old location to the new location hosted with Google.

In your application, all instances of this URL:

http://api.recaptcha.net

need to be replaced with this:

http://www.google.com/recaptcha/api

You will need to change all references to that URL, including the recaptcha.js or recaptcha_ajax.js files and the /verify URL.  It is as simple as that.  Keep in mind that if your site uses SSL then you need to change the “http” in the URL to “https”.

Many Joomla users have been affected by this problem as well.  Luckily a proposed fix has already been committed to Joomla’s GitHub repository.  To view those changes or to download the updated file, click here.  If you’re not confident enough to fix the issue on your own, a formal patch should be on it’s way from Joomla soon.

Feel free to leave a comment if you have any questions.  Thanks for reading!

Iterating Over an Enumerable – Creating a “Days of the Week” Drop Down Menu

Enumerations are extremely valuable for managing sets of numeric values such as status codes or days of the week.  Most of the time, you would create an enumerable to simplify values used in multiple points that have the same representation, in order to improve the readability and re-usability of your code.  However, there are some situations where using the enumeration’s name and value directly on the presentation layer can make sense.

For example, let’s say we have a form where we need the user needs to choose a day of the week to assign to a particular record.  We can easily generate a drop down list of values using the built in DayOfWeek enum that is included by default in the System library.

Code

Let’s create a Drop Down List on our page.  We will generate the list items in code behind, so we will just leave those blank.  It should look something like this:

<br />&lt;asp:DropDownList ID="ddlDay" runat="server"&gt;&lt;/asp:DropDownList&gt;<br />

In our code behind file, we will use a couple of helpers from the System.Enum namespace to allow us to loop through our enumerable's values and get their names for use in the list item.  Here's the code for our page load event:

<br />Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load<br /><%%KEEPWHITESPACE%%>    If Not Page.IsPostBack() Then<br /><%%KEEPWHITESPACE%%>        ' Get the values of the DayOfWeek Enum (0-6).<br /><%%KEEPWHITESPACE%%>        Dim daysOfTheWeek = System.Enum.GetValues(GetType(DayOfWeek))<br /><br /><%%KEEPWHITESPACE%%>        For Each value In daysOfTheWeek<br /><%%KEEPWHITESPACE%%>            ' Get the name that corresponds to each value.<br /><%%KEEPWHITESPACE%%>            Dim name = System.Enum.GetName(GetType(DayOfWeek), value)<br /><br /><%%KEEPWHITESPACE%%>            ' Add a new list item, using our name and value.<br /><%%KEEPWHITESPACE%%>            ddlDay.Items.Add(New ListItem(name, value))<br /><%%KEEPWHITESPACE%%>        Next<br /><%%KEEPWHITESPACE%%>    End If<br />End Sub<br />

It's that simple.  Now you know that the value that gets posted back to the server will match directly with the values defined in the enumeration, even if the values were to change at a later date.

A Caveat

One thing to keep in mind are that this is only a user friendly option for single word names.  For example, if you have a value that represents a process' status that is named "InProgress", it would appear as a single word in the drop down as well.  You could parse the name to add the space, but there are cases where that could over complicate the process.

Thanks for reading!

Integrating Google Apps With Your Application Using GData and Extension Elements

Google Apps for Business is quickly becoming the go-to solution for email, calendar and file applications.  Thanks to the available web service API for developing extensions and utilities on Google Apps, you can easily integrate your existing systems as needed.

What You Will Need

I’ll be using the GData API for .NET and the Google Calendar Service for the below examples, but you can access Google’s web services in pure XML form on any platform.  Alternatively, Google provides many pre-built libraries for many popular programming languages.  You can find them here.

You can also interchange any of the other Google Apps services, such as the Contacts Service and perform the same actions to meet your needs.

Extension Elements

Extension Elements are configurable attributes that can be attached to all Google Apps entities.  These attributes are only able to be accessed through the API, so your end users will not notice any difference in how they use Google Apps.

With an Extension Element, we can add an external identifier for an outside system that will allow us to connect the two entities as necessary in the future.  For example, let’s say that we want to use a custom system that contains metadata for calendar events specific to our business and we want to keep them synchronized.  We can create a calendar event using the API and attach the ID to our system’s records.

Creating a Record With Extension Data

Here is an example of how to create a new calendar event with an external identifier.

public EventEntry CreateEvent(Guid Id)
{
	EventEntry entry = new EventEntry();

	// Set the information for your event here.
	entry.Title.Text = "Event Title";

	// Create an ExtensionElement and add your external system's ID.
	ExtendedProperty prop = new ExtendedProperty();
	prop.Name = "ExternalIdentifier";
	prop.Value = Id.ToString();

	entry.ExtensionElements.Add(prop);

	// Create the service and insert the new event.
	CalendarService service = new CalendarService("YourAppNameHere");
	service.setUserCredentials("UserName", "Password");

	return service.Insert(new Uri("https://www.google.com/calendar/feeds/default/private/full"), entry);
}

Getting the Extension Element Value with LINQ

Once we have our events created with our external identifier, we need to be able to access that information later when we synchronize the metadata.  Here is a quick shortcut for handling that with LINQ.

// Get events from Calendar.
CalendarService service = new CalendarService("YourAppNameHere");
service.setUserCredentials("UserName", "Password");

EventQuery query = new EventQuery("https://www.google.com/calendar/feeds/default/private/full");

EventFeed events = service.Query(query);

foreach (EventEntry entry in events)
{
	// See if our entry contains the external identifier.
	ExtendedProperty prop = entry.ExtensionElements.SingleOrDefault(x => x is ExtendedProperty && ((ExtendedProperty)x).Name = "ExternalIdentifier");

	if (prop != null)
	{
		// Do our work for each system here.
	}
}

Conclusion

This only scrapes the surface of what is possible with Google Apps.  You could add any type of data here that you would like.  You could even store all of the information that your application needs on the event itself instead of in an external database.  The Google Apps API makes custom integration with your systems easy.

Thanks for reading.  Any questions?  Feel free to leave a comment!

.NET Decompiler Software Options

Every once in a while a project comes along that requires integrating with a third-party library or working with existing compiled code.  On occasion those libraries can come with either poor or no documentation at all.  This can make debugging a nightmare.  In this case, having a peek at the source code can point you in the right direction or even solve the problem altogether.  Believe it or not, there are several solutions available for decompiling .NET code on any budget, including many that are completely free.  You can even (gasp!) make changes to the library and re-publish!  Here is a look at the options.

Red Gate .NET Reflector

Reflector was previously the only solution available for decompiling .NET assemblies.  They offer a complete desktop application and an option for Visual Studio integration.  I say “previously” because .NET Reflector recently switched to a paid application, which spurred many of the competitor products.  Pricing for Reflector starts at $95.

Jetbrains dotPeek

dotPeek is my favorite .NET decompiler application.  It has a clean, familiar design and also has many IDE-like features for navigating through the decompiled code.  My only complaints are that it only decompiles to C# code at the moment and that it does not allow direct editing of the library.  You can however save the code as Visual Studio project and rebuild it on your own.  Best of all, it’s free.

Telerik JustCompile

JustCompile has many of the same features as dotPeek including the ability to create Visual Studio projects.  It is also very fast and provided free of charge.  I ended up using JustCompile for a recent project because it is compatible with Reflexil, a plugin that allows you to directly edit the library.  It is not as simple as just writing new code, but it is very helpful for situations where you just need to make small changes and don’t want to rebuild.  (Note: Reflexil also works with Reflector, but JustCompile is the only free application that it supports.)

CodeReflect

CodeReflect is a decompile-only product, meaning that it does not provide any of the Visual Studio project features of some of the other options.  It has a very simple interface and is also free of charge.  CodeReflect can decompile .NET code into either VB.NET or C#, whichever you prefer.

ILSpy

I have not used ILSpy, but I wanted to include it in the roundup since it is the only open source .NET decompiler.  ILSpy can decompile to either VB.NET or C# and save as a project in C#.  If you are a developer who is curious about decompiling, you can check out the source code to learn how it all works.

Thanks for reading.  Do you have a favorite .NET decompiler that is not on the list?  Feel free to leave a comment!

Choosing a Game Development Framework

Lately I’ve had an idea for a game that I just can’t get out of my head.  Combined with the recent unveiling of the Nintendo Web Framework I’m compelled to make an attempt to get a demo of the game running on the Wii U.  At a recent presentation from Unite ’13, Nintendo touted how easy game development is for the Wii U using JavaScript and HTML5.  I’ve always wanted to explore the limitations of HD gaming within the browser so this is the perfect opportunity to test Nintendo’s claims.

Our weakness as developers is that when we have an idea we just want to code.  I don’t want to plan or design, I want to get something up and running and see the fruits of my labor as soon as possible.  As much as I love technology, some times I’m so compelled to code that I don’t even want to vet the best framework for the job.  Sometimes I’ll just grab what I’m most familiar with and start working.  With game development, that is difficult to do.

I wrote a previous post about the pitfalls of game development in JavaScript where I mentioned not reinventing the wheel.  I see so many horror stories of indie developers spending all of their time on an engine and not ever making a game.  I suggested a couple of frameworks in that post, but now that I’ve completed a more extensive vetting process I’d like to share some insight on the decisions that I made.

2D vs. 3D

If you are planning on making a 3D game, you should look no further than Unity.  You can quickly get prototypes of your game running by relying on Unity as a backbone.  There are a number of resources already available that you can take advantage of for development.  These include 3D models, plugins and tutorials for your project.

If you insist against Unity, CryEngine, Unreal Engine and the Source Engine are other options, but aren’t exactly targeted to indie developers.

I was dead set on making a 2D game; many aspects of my game rely on it.  Making a true 2D game in Unity is just not possible.  You can create a game with a fixed camera that limits movement to two dimensions but ultimately the assets and game will run 3D.  My inexperience with 3D game development had me a bit nervous going that route.

Web, Mobile or dare I say it…consoles?

I mention above that I already had some interest in the Nintendo Web Framework as a potential target, so the decision to make the game using JavaScript and HTML5 was practically made for me.  However, that wouldn’t make for a very interesting post now would it?

If I wanted to make a game for mobile platforms and perhaps PC/Mac/Linux, my previous experience would lead me to look toward cocos2d.  I have previously worked with cocos2d-iphone and found it easy to work with.  cocos2d-x is essentially the cross platform version of cocos2d, which has support for those and many other platforms.

Whittling It Down

A quick Google search turns up many JavaScript game development frameworks.  How do you decide which one to use?  I ended up filtering out options based on features that I saw as valuable to me.  This is obviously a subjective process, so your criteria may lead you to a different result than mine.

First, I needed something free and open source if possible.  I would hardly even consider myself an indie developer and I really can’t see myself financially contributing to a pet project like this.  Second, I’d prefer a framework that can work out of the box with standard tools such as Tiled for tile based map creation.

At this point I had narrowed my decision down to two options: cocos2d-html5 and melonJS.  It is going to sound odd based on my recommendation of cocos2d above, but after working with both options I eventually settled on using melonJS.  cocos2d has its applications but for lightweight, simple JavaScript game development it is my opinion that melonJS is the best framework out there.

Thanks to the great documentation, I had a simple platformer up and running using the melonJS boilerplate project within an hour of getting started.  I have yet to thoroughly stress test, but I’ve had no hiccups running the game at 720p within Chrome.

Why did I turn away from cocos2d-html5?  After some exploration it just didn’t seem like the best way to go for a lightweight JavaScript game.  Ultimately, cocos2d-html5 is meant for cross platform games between the web and iPhone, and the API reflects that.  I wanted something built for JavaScript from the ground up.

Have you been working with a framework that you really like?  Leave a comment to let me know.

Code Wars: Training in Programming Arts

As developers we have to frequently consult outside resources for information on how to complete certain tasks.  Whether it’s a book or an online tutorial, a quick refresher is always helpful to get a push in the right direction.  The problem is that we will often look for these resources when we know specifically what we need to do, rather than using them to buff up our skills.

There are many sites out there that allow you to do programming challenges to work on your proficiency with a language.  Project Euler, TopCoder or the Daily Programmer subreddit come to mind.  My newest addiction of this type of site is Code Wars.

What is Code Wars?

I like to explain Code Wars as a combination of small programming challenges and Xbox style achievements.  You complete a series of code “katas“: short snippets or bug fixes that test basic understanding of programming language concepts.  For each kata that you complete, you work your way up to higher ranks and increasingly more difficult tasks.

Code Wars Dashboard

The user dashboard in Code Wars.

Code Wars tracks the type of the katas that you complete into different types, such as bug fixes, algorithms and reference.  You can also complete katas in either JavaScript, Coffee Script or Ruby.  Since Code Wars starts with the basics, it is perfect for supplementing your learning of a new language.

Test Your Might

Code Wars provides you with a very simple code editor with syntax highlighting.  It works surprisingly well in the browser, complete with handling of indentation and other features.  You are also provided with the ability to write unit tests against your solution to test any cases that will help you complete the kata.  Then you submit your solution.  There becomes nothing more addicting than getting that green check mark every time you complete a kata.

The best feature of Code Wars comes after you complete a kata.  Once you submit your solution and it is verified, you get to see the solutions that other developers submitted as well.  Sometimes you will see solutions that are more complicated than your own, but quite often you will see solutions that are mind blowing in their simplicity.  I typically spend just as much time reviewing other’s solutions as I do coming up with my own.

Future Wars

I have no doubt that in the future Code Wars will bring support for more languages.  I’m excited at the possibility of completing code katas with Python or PHP.  I can’t help but think that Code Wars would also be an amazing tool for teaching people how to use the UNIX command line.

The beauty of Code Wars is that its katas are populated by user submissions, so it will continue to grow with new content in the as time goes on.

Want to test your skills?  Sign up by completing the example kata at http://www.codewars.com!  Thanks for reading!  If you would like, you can view my Code Wars profile here!

Getting Started with the Stripes Framework

Stripes is an up-and-coming alternative to Apache Struts for developing web applications using Java. Stripes is very well documented, but leaves something to be desired in their sample projects and jump start information.  I’ve also noticed that while some of the features of Stripes are very extensible, it can be hard to understand what is needed and what isn’t.  I’ve included a quick briefing on some of the common pitfalls below.

ActionResolver

ActionResolver is a component of Stripes that discovers your ActionBeans and maps them to URLs for you to use in your views. One common mistake that occurs when setting up a new Stripes project is not having the ActionResolver properly mapped to the package containing your ActionBeans. This is done in the web.xml configuration file for your project.

<filter>
	<display-name>Stripes Filter</display-name>
	<filter-name>StripesFilter</filter-name>
	<filter-class>net.sourceforge.stripes.controller.StripesFilter</filter-class>
	<init-param>
		<param-name>ActionResolver.Packages</param-name>
		<param-value>{Your ActionBean package name goes here.}</param-value>
	</init-param>
</filter>

If this is not configured properly, you may see errors such as this: “Could not locate an ActionBean that was bound to the URL. Commons reasons for this include mis-matched URLs and forgetting to implement ActionBean in your class.” This can be misleading because the actual cause is related to neither of those reasons.

UrlBinding

One particular difficulty that I had when I started working with Stripes was the usage of UrlBinding annotations. The reason for this is that if your ActionBeans are named properly, then you may never need to use them.

For example, let’s say you have an ActionBean class named LoginActionBean. By default, the ActionResolver will automatically bind this to the Login.action URL without any manual configuration required from you. The only time you ever need to use a UrlBinding is if your URL needs to differ from the automatically generated URL.

This is important to know, because at times the error messages returned by Stripes when it is not configured properly, such as the ones above, can lead you to using a UrlBinding even when you don’t need it.

Using HTML5/Custom Attributes

If you try to use custom attributes with one of the Stripes jump start projects, you will find that using HTML5 or other custom attributes will cause an exception to occur in Stripes.

For example, if you want to add an HTML5 placeholder attribute to a text input that is generated by Stripes, you will not be able to do it with the standard Stripes tag library.  This is also the case with JavaScript event attributes such as “onclick” or “onchange”, and custom attributes prefixed with “data-”.

I found the solution difficult to track down, but all you need to do is use the dynamic tag library provided with Stripes.  To use the Stripes dynamic tag library in your project, just add this taglib reference to the top of your JSP file:

<%@ taglib prefix="stripes" uri="http://stripes.sourceforge.net/stripes-dynattr.tld" %>

You can use the standard Stripes tag library and the dynamic tag library together on the same page.  You just need to set the prefix value in the code above to something different than the prefix value you are using for the standard tag library.  This is actually the recommended usage of the dynamic tags, yet it is not used in any of the current Stripes samples.

Never fear

Stripes is a lightweight framework that is great for developing Java web applications. Not many people are using it, and unfortunately that means that there are not many resources available outside of the documentation. However, the documentation is very detailed and technical. The process of getting up to speed may take longer than usual, but having an alternative framework to available is great for the future of Java on the web.

More information, including samples and comparisons to Struts can be found at http://www.stripesframework.org.

System.Web.WebPages conflict between ASP.NET MVC 3 and ASP.NET MVC 4

After installing ASP.NET MVC 4, you may notice that you are unable to load projects that used previous versions of ASP.NET MVC. You may see an error similar to the following:

The type ‘System.Web.Mvc.ModelClientValidationRule’ exists in both ‘c:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 3\Assemblies\System.Web.Mvc.dll’ and ‘c:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v2.0\Assemblies\System.Web.WebPages.dll’

This error occurs because prior to MVC 4, projects did not specify which version of ASP.NET Web Pages to use, since there was only one. Luckily, the fix for this is as simple as updating the project file to the proper reference of System.Web.WebPages. Many developers have not ever needed to modify a project file directly, since the default Visual Studio configuration is often sufficient. This can make editing a project file an intimidating task, so I have assembled detailed steps to solve the problem.

From the Solution Explorer, right click on the project and click “Unload Project” from the context menu.

The "Unload Project" menu item in Visual Studio 2010.

The “Unload Project” menu item in Visual Studio 2010.

You should see that the project is now marked with (unavailable). Right click on the project again and you should be able to select a new item, “Edit {Your Project Name}.csproj”. The extension will be displayed as .vbproj for VB.NET projects.

The "Edit Project" menu item in Visual Studio 2010.

The “Edit Project” menu item in Visual Studio 2010.

An XML configuration file will open. This contains all of the information that tells Visual Studio how to run your project. Scroll down (or search the file) until you find the following line:

<Reference Include="System.Web.WebPages"/>

Replace that entire line with this:

<Reference Include="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"/>

Save the changes to the project file. Right click the project name in the Solution Explorer again. This time, select “Reload Project”. Your project will reopen in Visual Studio and should now build and run properly.

In simple terms, what we have done here is update the Reference tag to include version information, which resolves the conflict for Visual Studio.  It now knows which version of System.Web.WebPages you intend to use for your project.

Thanks for reading.  Still having trouble resolving the error?  Feel free to leave me a comment below!

From the Bookmarks Bar – July 12, 2013

I’m going to give something new a shot here.  From the Bookmarks Bar is a weekly round-up of interesting software development related links from around the web.  In general, it’s just a collection of things that I think you may find interesting.  Without further ado, here some favorites From the Bookmarks Bar for this week:

New Programming Jargon

We’ve all run into these issues from time to time.  This article reads like a book of the best programming related jokes.  Smurf Naming Convention is my favorite.

Raspberry Pi Powered Microwave

Disappointed by the lack of features on your microwave?  Why not overhaul it by integrating a Raspberry Pi?

The Visitor Pattern Explained

Many developers have only a brief understanding of the visitor pattern even after using it.  This is a detailed and practical example of the usage and practices of the visitor pattern.

How to Modify Bootstrap Simply and Effectively

Here is a collection of some great Bootstrap mods as well as some tools to easily modify Bootstrap to your tastes.  Want to make your Bootstrap based site look like Facebook or Metro in Windows?  An add-on can make it happen.

Super Mario Bros. 3 Match Game in Javascript

This is a fun one.  A developer has built a slick recreation of the match game from Super Mario Bros. 3, written entirely in JavaScript.  The project is well segmented and structured and is a good example for those looking to learn modern JS.  Source code is available here:  https://github.com/callmehiphop/mario-cards

That’s it for this week.  I’ll be experimenting with From the Bookmarks Bar over the next couple of weeks.  Feel free to leave a comment and let me know what you think.  Thanks for reading!