99 Problems and a Bit Ain’t One

99Problems

If you have ever worked on a project that involves interactions between 32-bit and 64-bit applications and referencing their DLLs, you may have encountered this guy before :

BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)

This nasty BadImageFormatException generally stems from referencing legacy libraries (or any libraries containing unmanaged code) that were not really designed to run on 64-bit machines. If your all of the code within your 32-bit libraries is managed, then you should be just fine and you shouldn’t see much of this guy at all. This post will cover two methods for hopefully resolving this issue using configuration features available in both Visual Studio and within IIS.

Troubleshooting this Issue

When running into this, I’m sure that your first instinct will be to toggle through the various settings within your Project / Solution regarding it’s Build target. You’ll probably switch back and forth from x86 (32-bit) to x64 (64-bit) and attempt to re-build and run your application countless times :

When encountering this issue, you'll undoubtedly toggle between x64, x86 and the Any CPU options. Success may vary by user.

When encountering this issue, you’ll undoubtedly toggle between x64, x86 and the Any CPU options. Success may vary by user.

Then you’ll likely say “well the Any CPU setting should work” and you’ll try that, only to again be met with the same error that you encountered previously. This isn’t always the case, as I have found that one of these settings may occasionally work, but success may vary by user and application.

Resorting to IIS

If tinkering with the available settings and targets within the Build tab of your Solutions properties didn’t help, you might need to pull out the bigger guns and try to handle this at the Application Pool level in IIS. Try opening up the IIS Manager that your application is targeting and go through the following steps :

1.) Open up your Available Applications pools within IIS :
AppPool

2.) Right-click on the Application Pool that houses your troubled Application and choose the “Advanced Properties” option :

ApplicationPoolAdvanced

3.) Set the “Enable 32-Bit Applications” option to “True”

Enable32BitApplications

4.) Finally, restart / recycle your Application Pool for these changes to go into effect :
Recycle

I’ve found that this should fix the issue a majority of the time, however there are performance considerations that you might want to review over prior to making this change. The primary one being memory availability / access to a much larger possible memory space. If you are using this approach, you might want to consider reading through this related Stack Overflow discussion on using this setting within IIS to get an idea of a few other possible side-effects.

More Information

If you want to learn a bit more about how 32-bit and 64-bit processes interact with one another within the CLR, I would encourage you to give Scott Hanselman’s post on this same issue a read. Scott describes the article as “obscure”, but again, if it is something that you are interested in, it’s certainly worth a read and goes into quite a bit of depth.

 

ASP.NET vNext Community Stand-up Series

I just thought I would post a quick recommendation to any readers out there with an interest in the upcoming vNext release for ASP.NET. Scott Hanselman recently began a weekly web series with various members of the ASP.NET Development team detailing the progression of vNext and reviewing over many of the available features in place and those yet to come.

I strongly encourage anyone out there even remotely interested in vNext to check it out. It’s extremely informative and provides a bit of a behind-the-scenes look at how the technology is being developed and might answer many questions that you have about how vNext will change .NET in the future.

Integrating TinyMCE into an MVC 5 Project

TinyMCEHeader

I thought I would take some time to address a question that has frequently appeared in a few forum questions over the past month or so and that is “How do I use the TinyMCE Editor within ASP.NET MVC?”. Since I’ve answered this quite a few times, I thought I would take a few minutes to share the process with the rest of the net so prevent this from popping up in the future.

Let’s address a few of the extremely common questions.

Can I use TinyMCE with ASP.NET MVC? Or Web Forms?

Of course you can. TinyMCE is simply a pure Javascript rich text editor that has no reliance on MVC, Web Forms or any other server-side related technology. All you need to use it is some simple HTML markup and the appropriate TinyMCE Javascript and content files (which are included within the download).

How or where can I download TinyMCE?

The easiest approach would be to download the latest TinyMCE package via NuGet through the following steps :

  • Right-click on your Project.
  • Choose Manage NuGet Packages from the Context menu.
  • Select the Online tab on the left within the dialog box.
  • Search for “TinyMCE” in the upper right-hand corner.
  • Install the TinyMCE package to your project.

If you aren’t using ASP.NET or simply do not have access to NuGet, you can always visit the TinyMCE site and download the latest version of the editor from there.

A Simple Walkthough for Getting Started with TinyMCE

Let’s create a simple new MVC 5 Application through Visual Studio. For simplicity’s sake, I’ll just be using an Empty Project with the appropriate MVC references added :

Create a new Empty Project with the appropriate MVC references.

Create a new Empty Project with the appropriate MVC references.

Next, you’ll need some way to access the TinyMCE files. Two of the most common approaches (downloading the NuGet package or directly downloading from TinyMCE) are detailed above, this example will use the NuGet approach, but both of them should be similar.

Use the NuGet Package Manager to easily install the TinyMCE Package

Use the NuGet Package Manager to easily install the TinyMCE Package

You should now see several new files within a newly created “~/scripts/tinymce” folder. This folder contains everything that you need to use and configure the TinyMCE editor.

In order to actually use the editor, you’ll need to create a Controller with a single action that points to a View. For all intents and purposes, we will call this one “TinyMCEController” and it will have a an action called “Index” and another Index action that is decorated with an [HttpPost] attribute (and will accept a class that we will define below) :

public class TinyMCEController : Controller
{
        // An action to display your TinyMCE editor
        public ActionResult Index()
        {
            return View();
        }

        // An action that will accept your Html Content
        [HttpPost]
        public ActionResult Index(ExampleClass model)
        {
            return View();
        }
}

Next, let’s actually flesh out this very simple class that will just have a single, but very important property and an even more important attribute decorating it :

// An example class to store your values
public class ExampleClass
{
        // This attributes allows your HTML Content to be sent up
        [AllowHtml]
        public string HtmlContent { get; set; } 

        public ExampleClass()
        {

        }
}

The [AllowHtml] attribute is going to by-pass ASP.NET serialization protection (which can aid in preventing nasty XSS or any other types of garbage input that might fly on it). Without this attribute, you would need to disable RequestValidation for the specified action which is a bit overkill in this scenario as you just need to check for HTML.

The next step will be to add a View that targets your Index action. Right-click on your Index Controller Action and choose the available Add View… option that appears in the context menu. In this example, we won’t be using a Layout page or a Template, so you can leave those options :

You'll just need to create a very basic View without any templating or Layouts. Usage may vary.

You’ll just need to create a very basic View without any templating or Layouts. Usage may vary.

After generating your View, you’ll need to add a few references in to target and configure your TinyMCE scripts. You’ll also need a very simple <form> element to post your content from the TinyMCE editor as detailed below :

<!-- This View uses your Model -->
@model TinyMCE.Controllers.ExampleClass
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>TinyMCE Example</title>
    <!-- TinyMCE Script Reference -->
    <script src="~/scripts/tinymce/tinymce.min.js"></script>
    <!-- Script to wire up your TinyMCE editor -->
    <script type="text/javascript">
        // Initialize your tinyMCE Editor with your preferred options
        tinyMCE.init({
            // General options
            mode: "textareas",
            theme: "modern",
            // Theme options
            theme_advanced_buttons1: "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
            theme_advanced_buttons2: "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
            theme_advanced_buttons3: "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
            theme_advanced_buttons4: "insertlayer,moveforward,movebackward,absolute,|,styleprops,spellchecker,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,blockquote,pagebreak,|,insertfile,insertimage",
            theme_advanced_toolbar_location: "top",
            theme_advanced_toolbar_align: "left",
            theme_advanced_statusbar_location: "bottom",
            theme_advanced_resizing: true,

            // Example content CSS (should be your site CSS)
            content_css: "css/example.css",
        });
    </script>
</head>
<body>
    <!-- This will automatically post to your Index method (that is decorated with a HttpPost attribute) -->
    @using (Html.BeginForm()) 
    {
        @Html.AntiForgeryToken()
        <div>
            <!-- This will contain your HtmlContent and use the TinyMCE editor-->
            @Html.TextAreaFor(model => model.HtmlContent)
           
            <input type="submit" value="Create" />
        </div>
    }
</body>
</html>

Obviously, the configuration code that is used above within the <script> tag might look a bit overwhelming. You can visit the TinyMCE Examples page which demonstrates a few varying levels and features depending on your needs.

After adding your View in, you should be able to run your application and see the following :

Editor

Once you hit the Create button within the View, your content will be posted with its associated markup to your Controller and you should be able to see it without any issues :

Posted

Alternatives and Other Editors

Although this walk-through explicitly targeted the TinyMCE editor, it is my no means limited to just it. The same basic steps should work with any of the popular client-side Rich Text Editors such as Redactor, CKEditor, HTML Editor and more. You’ll just need to include the proper references and content files and ensure that you are targeting the proper element when using the configuration code.

It should be noted that there are a variety of other NuGet packages out there for using TinyMCE as well if this felt like too much of a hassle. The TinyMCE.MVC relies on an HTML Helper to build and wire up your editors for specific areas and can be useful if you don’t like messing with Javascript at all. It’s just a matter of preference.

A Quick Fix for Responsive Bootstrap Menus on Windows Phone

bootstrap-in-windows-phone

During a bit of site testing, I encountered a rather strange bug when viewing a site that was developed using the incredible Twitter Bootstrap. The Responsive collapsing navigation menu didn’t appear to work at all and all of the menu items that were present were all jumbled around. It not only looked bad, but it severely hindered the usability of the site at all.

After some research, I came across the following snippet that appeared to resolve the issue. Simply paste this into the <head> section of your application and it should hopefully resolve your Bootstrap issues on Windows Phone devices :

<!-- Bootstrap Fix for Windows Phone -->
<script type='text/javascript'>
        (function() {
            if ("-ms-user-select" in document.documentElement.style && navigator.userAgent.match(/IEMobile\/10\.0/)){
                var msViewportStyle = document.createElement("style");
                msViewportStyle.appendChild(document.createTextNode("@-ms-viewport{width:auto!important}"));
                document.getElementsByTagName("head")[0].appendChild(msViewportStyle);
            }
        })();
</script>

An Interesting List of Development Stuff (July 2014)

july2014

It’s been a rather busy month, so without further ado, here is this months ILODS.

Bootstrap on a 386

If you ever encounter a client that simply hasn’t migrated to anything newer than a 386, but needs you to write a new web application for them, then you are in luck! Mark Otto and Jacob designed BOOTSTRA.386, a 386-themed Bootstrap theme that will be sure to bring back memories.

How to Destroy Developer Productivity

An excellent article from George Stocker regarding all of the everyday activities that can absolutely crush developer productivity. From developer arguments to open floor plans, George rattles off his experiences with what has and hasn’t worked for him in being more productive.

30 Days with Bootstrapping ASP.NET MVC

Fellow ASP.NET MVC James Chambers provides a very well written series on integrating the Twitter Bootstrap (not the previously mentioned BOOTSTRA.386) into ASP.NET MVC Applications. This 30-part series covers just about everything that you could think of and hits a number of common use-cases that developers may encounter when using Bootstrap. Highly recommended for any ASP.NET MVC Developers.

The Unspoken Truth about Managing Geeks

If you are reading this blog post, the likelyhood is rather high that you could be classified as a “geek” or one of the many synonyms there are out there and there is absolutely nothing wrong with that. In this 2009 article from Computer World, Jeff Ello addresses many of the concerns that are faced when actually managing “geeks”. It’s not only a great article to read if you are in management and it likely wouldn’t hurt to read it if you are one of the “geeks” being managed either.

vNext, vNext, Read all about it!

ASP.NET vNext has slowly been creeping into the Microsoft Development realm recently and although it is still in it’s earlier phases, it’s never too late to Get Started learning it. This ASP.NET tutorial series introduces vNext and walks through how to not only Get Started with vNext, but it provides a step-by-step tutorial for several different projects (and platforms).

A Compilation of Architecture and Patterns in ASP.NET

The patterns are strong with this one. In this post, .NET Developer Andras Nemes compiles an absolutely monstrous list of .NET implementations of just about every major design pattern that you could think of (and many that I am sure you couldn’t). It doesn’t only feature code snippets of their implementations, but also sample projects.

 

Using Visual Studio AutoRecover to Avoid Losing Your Work (and your Mind)

Mondays

If you have ever worked in an environment that may not have been the most reliable or you are simply a worry-wart when it comes to possible data loss, then this might be for you.

When discussing a recurring issue with another developer, he complained that his older computer frequently crashed which resulted in him losing data quite often. He didn’t seem to be aware of a feature within Visual Studio called AutoRecover that would help him ensure that his data wasn’t always “gone forever”. While it typically works on it’s own, this post will discuss AutoRecover, configuring it and locating all of the temporary files it creates if you need to find them.

What is AutoRecover?

AutoRecover is an option within Visual Studio that will allow you to define a particular interval in which to save information about all of the files that may be changing or have changed within your application. It’s perfect for scenarios where you might have a machine that is on the verge of death, intermittent power issues, data-loss anxiety and just about anything else that might have you spouting off expletives when your screen goes black (or blue).

How do I use it?

You can access the AutoRecover option in Visual Studio through the following steps :

  1. Select Tools from the Toolbar in Visual Studio.
  2. Choose Options
  3. Select AutoRecover beneath the Environment tab on the right.

You’ll then be presented with the AutoRecover dialog box :

Autorecover

You’ll just need to adjust these values depending on your needs and how erratic your machine can be.

Accessing AutoRecover Files

Accessing the files themselves is quite easy as well. By default, Visual Studio will store all of these files within a “Backup Files” directory which is typically located at the following location :

~/Documents/{Your Version of Visual Studio}/Backup Files/{Your Project Name}

Within this folder, you will see a collection of files that are both original and those that have been previously recovered as seen below :

files

Visual Studio will typically prompt you to open these files if your system experienced an unexpected shut down when opening an affected solution or project, but this should provide an easy way to access these files if things do go horribly wrong.

 

Using the NuGet Package Explorer to Create, Explore and Publish Packages

Nuget

Although there is often some debate regarding its pronunciation, I believe that most of us can agree that NuGet is pretty great.

In the past few years, NuGet has become one of the easily and most commonly used tools within a .NET Developers bag of tricks and rightfully so. Long gone are the days of searching for a DLL file in some shady site and hoping that it doesn’t brick your application. Now you can find just about every possible reference you would want to include within your application in just a few clicks (and letting it sort out all of the dependencies).

Most developers have likely interacted through NuGet within Visual Studio, however this post is going to introduce another way to interact, explore and even publish your own NuGet packages called the NuGet Package Explorer.

What is the NuGet Package Explorer?

The NuGet Package Explorer is a open-source product of NuGet developer Luan Nguyen and was developed as an extremely user-friendly GUI application for easily creating and exploring NuGet packages. After installing the ClickOnce application, you can simply double-click on a NuGet Package file (.nupkg) to access all of its content or you can load packages directly from the official NuGet feed.

How to use it?

First, you’ll need to visit the NuGet Package Explorer page on CodePlex, where the tool is currently available and download it. After a short download, you can launch the ClickOnce application and be presented with the following screen :

JustLaunched

These are your primary options when it comes to creating or exploring the contents of any available NuGet packages (in addition to simply clicking on any NuGet Package files as mentioned earlier). The easiest approach to get started would probably be to open up a package from the feed, which will present you with a searchable dialog with all of the most popular NuGet packages :

PopularPackages

After clicking on a package, you can choose the particular version you wanted to explore :

allversions

You also have the option of manually opening up any packages that you might have locally installed, but simply grabbing them from the feed is usually going to be the way to go.

Exploring a Package

Once you select a package that you want to explore a bit more, you can just double-click on it to present the details about that package :

An example of exploring the EntityFramework NuGet Package.

An example of exploring the EntityFramework NuGet Package.

While exploring a package, you’ll see many of the summaries, details and descriptions that you might be accustomed to seeing when managing your NuGet packages through Visual Studio along with a bit more.

You’ll see an area called Package Contents, which display all of the files that are contained within the package and it can help give you an idea of the different versions of the framework that it targets, any transformations that will be applied to configuration files and any additional utilities or executables that might be run when the package is installed :

PackageContents

This is where you can really actually explore the packages by digging into the contents a bit more. By simply double-clicking on a file within the contents, you will be shown a preview (if available) of the contents :

ContentsDetails

This can be done for just about any kind of file that would normally support previews and it can be extremely useful if you wanted to see exactly what is going down inside some of these packages.

Creating a NuGet Package

The Package Explorer isn’t limited to just exploring existing packages. It provides a very easy-to-use interface to allow you to create your own packages and upload them to NuGet to share with others.

With a simple click of the File > New option menu or by using the CTRL+N shortcut :

started

You’ll be transported to a new package screen to begin building your own NuGet Package. You can click the Edit Metadata icon ( EditMetadata) to began actually editing information about your package :

MetaData

You can find a complete reference of all of the available fields listed above and exactly what they are used for by visiting the Nuspec Reference page here.

After defining all of your metadata, supported assemblies and dependencies, you will then be ready to add your files and content to your packages. You can do this by just clicking a file within the File Explorer and dragging it into the Package Contents area on the left :

SampleFile

All of the DLL files that are entered will be placed into the lib directory and all other basic content will be placed into an aptly named content directory as seen below :

PackageContent

Additionally, if you need to add other folders (or any other “special” types of folders), you can do so by using the Content menu :

OtherContent

 

You can continue to add all of the additional files and folders for your package in this same manner until your package is complete.

Publishing to NuGet

Publishing to NuGet is fairly simple after you have build your package.

The first thing that you’ll need to do is Register and Sign In to the NuGet Gallery, which takes a matter of seconds. This will provide you with an API key that you will need to use in order to publish packages to NuGet :

Api

After you have your API Key, you’ll just need to use the Publish option (File > Publish) within the NuGet Package Explorer :

Publish

Just enter in your API Key in the Publish dialog and hit Publish and you are done!