Paste XML as Classes Missing In Visual Studio

Just wanted to pass along a quick tip for working with the Paste Special features in Visual Studio.  You may be aware that Visual Studio has options for generating classes based on XML and JSON under the Edit, Paste Special menu.

Paste Special

The Paste Special menu and options in Visual Studio 2013.

These options will generate VB.NET or C# classes that work with the built-in .NET serialization libraries.  However, you may only see the option to “Paste JSON as Classes” from the menu in your Visual Studio window.  This is because XML option is only available in projects targeting .NET Framework 4.5 and above.  Change your project’s target framework version and the option will become available.

If you are not able to upgrade your project, you could always create a new .NET 4.5 project, generate the classes there and then copy them to the destination.  You may need to correct some version specific errors, but this option will still get you most of the way there.

Advertisements

SuperSecretary

The following is the beginning of a series of posts with detailed information on my open source personal projects. The intention is to provide information about the application, development, design decisions and lessons learned.  Enjoy!

Overview

I don’t recall exactly when I started working on SuperSecretary, but I originally looked at a folder of various photos on my machine and set out to look for a way to keep them under control. I looked for software to sort photos by date taken and couldn’t find anything to meet my criteria. It didn’t seem that there were any options that were user-friendly, and there certainly weren’t any that were free.

I started building SuperSecretary specifically as an app to manage photos, but quickly realized that the concept could be expanded upon to manage all types of files. There are even some features, such as sorting music files by ID3 tags that are on my to-do list for future versions.

Design

I knew from the beginning that I wanted the application to eventually support plugins for users to handle files in any matter that they deemed necessary. This led me to the creation of the “Handler” in SuperSecretary. It is essentially just a simple, verbatim implementation of the Strategy pattern. Each handler has a Do method that passes in the path to the file that is being acted upon, along with some options that have been selected by the user. The handler returns the name of the folder that the file should be sorted into.

For example, when the user chooses to sort a photo by the Date taken attribute, the system uses a DateTakenHandler. The sorting engine loops through the files that need to be sorted and runs the DateTakenHandler for each one. The DateTakenHandler will retrieve the Date taken property from the EXIF data and format it based on the format selected by user. For cases when the user chooses to sort based on multiple attributes, the system will return and then move on to the next Handler. The handlers all inherit from the same interface, allowing a plugin system to be implemented.

The only thing I dislike about this design is that it is not the most efficient option. The system loops through each file, then loops through each of the handlers and acts before moving on to the next. However, some processes are more efficient when grouped together. For example, if the user chooses to sort on two EXIF attributes, say Camera Model and Camera Maker, it makes sense to retrieve that information together. However, batching these operations together makes the system less extensible. Ultimately I chose the more modular approach.

Development

I started development on a proof of concept right away. Since the application was meant to be a small utility that I used myself, I did not put much effort into researching features or deciding on what options to provide right off the bat. I kept the user interface compact and simplified as possible.

After completing the proof of concept, I began to think about the bigger picture of all of the things that could be possible. I pondered on a plugin system and the possibility of multiple interfaces, including a console front end for automating the application as a scheduled task. I even started building a WinRT front-end, which didn’t go so well. More on that in another post.

All of these more end user focused features led to many development decisions. I re-factored the application into two projects, a core library and the Windows Forms application. I focused on keeping the Windows Forms view as thin as possible and moved all of the logic to the core library.  I moved detailed output of the results of each run to an update event that could be implemented in to display information in the UI, a log file, or any manner that is specific to the target platform.

Packaging

Releasing a desktop application as a product was an entirely new concept for me. All applications need a few common elements, one of which is a deployment package. I had very little knowledge on creating a Windows installer. I really only knew that Visual Studio Installer Projects had been recently discontinued and that I needed to find a new option.

I discovered the WiX Toolset, a fantastic framework for building MSI installers. I admit that my implementation is very simple, but to this point I have not run into anything that I needed that I could not achieve using WiX.

The other common element that an application needs is assets and branding. I come from a primarily web focused background and working as a part of a team, so I had never had the complete responsibility of creating assets for a project. Icons, logos, screenshots and information were all things that I had never created and compiled from scratch. I am not a designer so I tackled those to the best of my ability. Paint.NET became my friend.

Distribution

I initially built the Razium web site specifically for hosting an installer for SuperSecretary. I created the site in a format that was more focused on the end user as a target audience, rather than toward developers. I will do a post in the future entirely focused on the creation of the Razium site, since there are some interesting tidbits there.

Originally I hosted the files there as well, but I have since moved those to Sourceforge. Hosting on Sourceforge obviously requires that your application be open source, but for those that are, it provides the added benefits of handling bandwidth costs and also the exposure that you get from being included in their library. In the first day on Sourceforge I had more downloads than the whole time that SuperSecretary was up on the Razium site.

Thanks for reading.  For more information on SuperSecretary, or to download version 1.1, click here.  To view the source code or fork the project, visit the GitHub repository.

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!

.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!

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!

An in depth look at ASP.NET MVC’s TempData

Ask around about using TempData in ASP.NET MVC and you’ll get plenty of opinions, but few answers to real questions. “It’s contrary to the MVC pattern,” the more respectful responses will say, others will simply “answer” your question with, “Just don’t use it.” It can be a frustrating wall to encounter when you are simply looking for information to evaluate it as an option for your application or when you need to support code that already uses it.

Few technologies actually deserve that “do not use” label for all situations. The amount of technology elitism that is spread around forums and the internet is staggering. As developers, we have all found small applications for less commonly used technology, even if it is just that sparingly used script or internal web site. There are pros and cons to every technology, and any developer worth their weight in dirt should be able to recognize that.

So, OK, end rant. The point is that despite internet opinion, there are some valid uses for TempData. A wizard based process comes to mind. There are times when you just don’t want to post unused data back to the server every time. It’s a cumbersome process and leaves you responsible for validating what comes back from the client every time, whether you’ve already validated it or not.

What is TempData?

TempData is essentially managed session storage. ASP.NET persists your objects on the session between a single request and then removes them afterward, unless you say otherwise. See the code snippet below for a quick sample:

[HttpPost]
public ActionResult WizardStep1(WizardStep1Model model)
{
     if (ModelState.IsValid)
     {
          TempData["Step1"] = model;
          // OR TempData.Add("Step1", model); works fine as well.
          return RedirectToAction("WizardStep2");
     }

     return View(model);
}

In the WizardStep1 action, we save the model from step 1 to TempData if it is valid, and then we move on to step 2. TempData is essentially a dictionary with a key of string and a value of object, so we can use most of the methods that we would normally use for a Dictionary.

Retreving from and keeping TempData

Let’s consider a three step wizard process. Step 1 is as shown above. We start getting data from the user and move on to Step 2. During Step 2, we gather even more data and move on to step 3 where we (finally!) save everything to the database.

In order to get our data from steps 1 through 3 (cue Brian McKnight), we will need some mechanism to keep the data from step 1 while also adding the data from step 2, since it is only persisted for one request. This is where the Keep method comes in.

[HttpPost]
public ActionResult WizardStep2(WizardStep2Model model)
{
     // We use the same key from when we set the data to get it back...
     WizardStep1Model step1 = (WizardStep1Model)TempData["Step1"];
     // BUT, we can also use ContainsKey or TryGetValue in cases
     // where the data might be null...
     if (step1 == null)
     {
          // The user may have skipped step 1, so we go back.	
          // We could save the step 2 data to TempData if we wanted to.
          return RedirectToAction("WizardStep1");
     }

     // We need to tell TempData to keep the Step 1 model for one more request.<br />	
     TempData.Keep("Step1");
     if (ModelState.IsValid)
     {
          // And, if Step 2 is valid, we'll save it as well.	
          TempData["Step2"] = model;	
          return RedirectToAction("WizardStep3");
     }	

     return View(model);
}

We’ll need to keep the data for Step 1 whether the Step 2 model is valid or not, so we do that outside of the if block for ModelState.IsValid.

It is important to note that TempData only persists for one request. The following GET request following the RedirectToAction qualifies as a request. This means that in the get method for each step, we need to keep the TempData so it is there when we post back. Here is how this would work on the redirect to Step 3.

public ActionResult WizardStep3()
{
     TempData.Keep();
     return View();
}

Notice on the call to TempData.Keep in WizardStep2 that we provided the key that we used to store the Step 1 data to TempData. That marks only that object for retention in TempData, meaning that all others that are not marked will be disposed. In WizardStep3, we have both Step 1 and Step 2’s data in TempData. We can call TempData.Keep with no parameters to mark all objects in TempData for retention.

When we post to WizardStep3, we can retreive both Step 1 and Step 2’s data from TempData, using a similar method to Step 2. There we can save them all to a database at the same time using Entity Framework or any other database persistence.

Why TempData over Session?

You can see from the example above that once the user is finished with the wizard process, that we will no longer need the data from those forms. If you were to save this data to the session, it would stay there until you removed it manually, abandoned the session, or the session expired. Like TempData, the session has its benefits, but in this case it is easier to tell TempData on the off chance that we need to keep the data, rather than to always tell the session to get rid of it.

Conclusion

The truth is that many of the complaints about TempData are valid. It is a loophole outside of the MVC pattern and it is a volatile approach to persisting data. The problem is that despite the views of many opinionated developers, no one pattern is the solution to every problem. If anything else, I hope you have the information to decide whether using TempData is right for you.

Thanks for reading. Feel free to leave any questions or comments.

ASP.NET MVC Validation Messages using jQuery UI Tooltips

Traditionally in ASP.NET you add a single Validation Summary above your form that describes the errors that the user has made, or add validation messages next to each control in the form to grab the user’s attention to each particular field.  The example below from the default MVC 4 application illustrates this.

Default Validation Behavior

The default validation behavior in the ASP.NET MVC 4 internet application.

The problem comes when trying to format a form with a large number of fields in a way that is pleasing to the user and also does not use much space on the screen.  jQuery UI tooltips are an alternative option.  The user would see a general message that some errors have occurred on the form or a style change to indicate the fields that are problematic.  This could be a red border around the field, or even an asterisk.  When the user clicks that field to change the data, they are presented with the full error message in a tooltip.  It works well in limited space and it’s flashy!

What You Will Need

This particular walk through uses a strongly-typed Razor view in an ASP.NET MVC 4 project.  Specfically, the Login view from the default “Internet Application” project generated by Visual Studio.  MVC 3 will work fine as well.  If your project does not include jQuery UI, you will need that as well.  The default project does have jQuery UI already included, but not the tooltip libraries, so I just included the newest version from jQuery’s CDN.

Setting Up the Validator

Most commonly, forms in ASP.NET MVC use the Html.ValidationMessageFor method to generate a validation message based on the model field that is passed in.  This causes a problem with jQuery UI tooltips because the ValidationMessageFor method generates span elements and other HTML around the message for formatting purposes.  What we need to use here is the ValidateFor method, which will attach all of our validation data to the input field.  We can still set all of our information in the model as we usually do, but with out all of the extra HTML.  Here are my modifications to the User Name and Password fields to use the ValidateFor method.

<li>
     @Html.LabelFor(m => m.UserName)
     @Html.TextBoxFor(m => m.UserName)
     @{ Html.ValidateFor(m => m.UserName); }
</li>
<li>
     @Html.LabelFor(m => m.Password)
     @Html.PasswordFor(m => m.Password)
     @{ Html.ValidateFor(m => m.Password); }
</li>

One thing should jump out at you right away, and that  is the usage of the ValidateFor method on lines 4 and 9.  ValidateFor is a void method that has no return value, so we need to call it inside of a code block instead of directly like we call Html.TextBoxFor.  A semicolon is necessary as well to terminate the statement.

Adding on a jQuery UI Tooltip

Attaching the jQuery UI tooltip to the control is a piece of cake.  All you need to do is add this snippet of JavaScript to your log in page:

<script type="text/javascript">
    $(function () {
        $(document).tooltip({
            items: ".input-validation-error",
            content: function () {
                return $(this).attr('data-val-required');
            }
        });
    });
</script>

We attach the tooltip only to fields that have the “input-validation-error” class. This allows us to only show the error if there is something wrong with the data that the user has entered. If the data for a field is OK, the user will never see the tooltip.  Our custom content function grabs the “data-val-required” attribute from the input tag to display as the tooltip mesage, which contains the validation message that you set in your model.

Validation with jQuery UI Tooltip

Validation with jQuery UI Tooltip

Here’s our new and improved (and much more compact) log in form!  You can see that we have the red borders to tell us which fields need updating, but the tooltips will hide unless the user focuses on the field.  In this case, the password validation message will show when the user switches to that input, and the User Name validation will hide.

The possibilities for styling and positioning the tooltip with jQuery UI are endless.  For example, you could add a bright red alert box and you could position it anywhere in reference to the field; above, below, or to the side.

It’s really that easy.  Please feel free to leave a comment if you have any questions.