Delete temporary file sent through StreamContent in ASP.NET Web API HttpResponseMessage

Recently I had to delete a temporary (temp) file/resource sent through HttpResponseMessage. The code I tried first was like this:

var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
var response = new HttpResponseMessage();
                response.StatusCode = HttpStatusCode.OK;
                response.Content = new StreamContent(fileStream);
                response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = fileName
                };
File.Delete(filePath);
return response;

Fooling myself I didn’t notice that one cannot do File.Delete(filePath); before returning the file because it’ll be deleted from the server disk before arriving at the client – see that response.Content receives a StreamContent, that is, the file is yet to be streamed to the client – only after it’s been streamed is that we can delete the file.

This is the exception that was being logged:

20131028 18:29:10 435 [7299] ERROR com.itvizion.data.services.Controllers.DataTablesController - Unhandled exception during file action Could not find a part of the path 'C:\ITVizion\MyProject\FileExportService\Files\datatable.csv'.

Sure it could not find the file, it had already been deleted. D'oh

So how can we dispose a managed resource (in this case the file) after the client has successfully downloaded it? That’s a damn good question I made myself and Google yesterday.

Googling I found this StackOverflow question:

How to delete the file that was sent as StreamContent of HttpResponseMessage

The asker pointed me in the right direction. One has to inherit from HttpResponseMessage and override the Dispose method like this:

public class FileHttpResponseMessage : HttpResponseMessage
{
    private string filePath;

    public FileHttpResponseMessage(string filePath)
    {
        this.filePath = filePath;
    }

    protected override void Dispose(bool disposing)
    {
        base.Dispose(disposing);

        Content.Dispose();

        File.Delete(filePath);
    }
}

Note the order of the calls inside the Dispose method. This is an essential part that differs from the hint given by the SO question I mentioned above.

Now what’s left is put FileHttpResponseMessage to use like this:

var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);

var response = new FileHttpResponseMessage(filePath);
response.StatusCode = HttpStatusCode.OK;
response.Content = new StreamContent(fileStream);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
    FileName = fileName
};

return response;

FileHttpResponseMessage will take care of calling Dispose on the correct time deleting the temporary file from the server disk right after the client has finished downloading the file.

Cleaning up the server disk is a good practice after all. This can avoid future headaches.

Hope it helps.

Detecting and fixing Ajax.BeginForm and Partial View stale data

This blog post describes a technical hurdle and how to solve it with some (actually 2) clever lines of code.

In a recent ASP.NET MVC application called Vizion Logs, me and my buddy Mario Brenes from IT Vizion were facing a difficult situation: our Save action method returns a PartialView but the Model value passed to this partial view was not being displayed correctly under the covers, that is, the View was keeping the previous/stale Model value. This was completely ruining our business logic on the Controller side. This was a nasty problem because the first time the view/form is rendered the Model has an ID property set to -1. After post backing the Model and saving it we then pass this same Model to the partial view but now it has the ID property set to the ID automatically generated by an Oracle sequence defined in the database side. We count on this ID property value for subsequent save operations in which case this specific Model will be updated and not saved again as a new row in the database.

It’s worth mentioning that we use that Save action method to handle both Saving and Updating the log objects.

Here you can see the form being constructed with an Ajax.BeginForm on the View side:

@using(Ajax.BeginForm("Save", Model.Field,
    new AjaxOptions
    {
        HttpMethod = "POST",
        UpdateTargetId = "logs",
        InsertionMode = InsertionMode.Replace,
        OnFailure = "handleFailure",
        OnSuccess = "setupForm();parseFormForUnobtrusiveValidation();",
    }))

We did a Google Hangout to investigate what was going on… two minds working together to detect a problem is better than just one. It was Pair Programming (remotely) at its best. These hangouts with Mario are helping me to exercise my English too – WOOT! It’s a double gain or why not say a bargain!?
During this investigation Mario kept asking me questions that led us to the correct places in the code path. This allowed us to solve the problem in less than 30 minutes…

At first we tested the condition that was leading to the buggy path: saving the logs for the first time worked great but then hitting the save button a second time was causing duplicate entries on the database instead of updating the log entries already created.

As our Save method counts on the log’s ID property for subsequent saves (updates to be technically correct) it was fair enough to check the model that was being passed to the partial view right after hitting the save button for the first time. We saw that it had the ID property set correctly to the ID generated by the database. So this was the expected behavior. On the view side we use @Html.HiddenFor(l => l.ID) to keep the ID property as part of the post back values. This is important because with this we know when inside the Save action method that that specific log entry must be updated and not saved. A log entry must be created when it has an ID = -1 and it must be updated when ID != -1. Now what was left for us to check was see if the correct ID was present in the HTML generated by the partial view. Bingo: the ID property was still -1. Houston we have a problem. Now let us look at the jquery.unobtrusive-ajax.js file that handles the Ajax.BeginForm. What interest us on this JavaScript file is the asyncOnSuccess method:

function asyncOnSuccess(element, data, contentType) {
    var mode;

    if (contentType.indexOf("application/x-javascript") !== -1) {  // jQuery already executes JavaScript for us
        return;
    }

    mode = (element.getAttribute("data-ajax-mode") || "").toUpperCase();
$(element.getAttribute(
"data-ajax-update")).each(function (i, update) { var top; switch (mode) { case "BEFORE": top = update.firstChild; $("<div />").html(data).contents().each(function () { update.insertBefore(this, top); }); break; case "AFTER": $("<div />").html(data).contents().each(function () { update.appendChild(this); }); break; default: $(update).html(data); break; } }); }

We placed a breakpoint in this method and analyzed the data parameter that contains the HTML that’s going to be rendered by the partial view. To our surprise we saw that the ID property was still –1 despite it being 10 for example on the Controller side right before passing the model to the PartialView.

Jesus Christ… this is crazy! Confused smile How can that be the case?!

Well I thought… this sounds like a cache problem. This was the first time I was using the Ajax.BeginForm construct. Before using it I was used to use plain @Html.BeginForm and jquery $.ajax calls and as such I had never experienced this let’s say “bug” before. With this caching hint on mind I Googled about the problem and AS ALWAYS StackOverflow is our best friend. I found this question:

MVC Partial View Model Not Refreshing

jgauffin tells us to use the OutputCacheAttribute to disable cache for that specific action method and also clear the ModelState object. Something like this:

[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult Save(LogFormViewModel model)
{   
    // Custom Save/Update logic here...
    
    ModelState.Clear();
    
    return PartialView(model);
}

After decorating our Save action method with the OutputCache attribute and calling ModelState.Clear() we retested the form and to our surprise it just worked and we told each other: that’s great buddy!

We just solved the problem with some clever lines of code thanks to our collaborative thinking and to StackOverflow that never ceases to amaze me. For 99% of questions I have I can be sure that they’ve already been answered there – it’s just a matter of using the correct wording in a Google Search, but hold on: before searching you must first know why and what you need to search for. I think this is one lesson learned with this post.

That’s it. Hope this post is useful to the next soul/spirit/human being that might stumble on this.

Creating a custom ASP.NET MVC @Html.ValidationSummary template styled with Bootstrap 3 panel

Today I had to customize the standard @Html.ValidationSummary that comes with ASP.NET MVC. Searched for it as always using Google and found this question at StackOverflow with two promising answers. One of them presented a nice approach that is the creation of a custom partial view called ValidationSummary.cshtml that lives in the standard Views\Shared folder. Initially I was afraid of implementing this because as one of the commenters said it didn’t play ball with jQuery Validate. I decided to experiment and see what would happen in my case. Guess what? It didn’t play ball with jQuery Validate. So it’s not OK. I was not satisfied and did further investigation regarding Microsoft's jquery.validate.unobtrusive.js file and it led me to the correct implementation to get the custom Validation Summary working with jQuery Validate. Let’s look at the code that Microsoft uses to fill the Validation Summary with errors:

function onErrors(event, validator) {  // 'this' is the form element
    var container = $(this).find("[data-valmsg-summary=true]"),
        list = container.find("ul");

    if (list && list.length && validator.errorList.length) {
        list.empty();
        container.addClass("validation-summary-errors").removeClass("validation-summary-valid");

        $.each(validator.errorList, function () {
            $("<li />").html(this.message).appendTo(list);
        });
    }
}

As we can see the code looks for a container that has a data attribute [data-valmsg-summary=true]. So when creating our custom Validation Summary template we must add that data attribute to our <div> container like this:

@model ModelStateDictionary

<div class='@(Html.ViewData.ModelState.IsValid ? "validation-summary-valid" : "validation-summary-errors") panel panel-danger'
     data-valmsg-summary="true">
    <div class="panel-heading">
        @Localization.CorrectErrors
    </div>
    <div class="panel-body">
        <ul>
            @foreach (var modelError in Model.SelectMany(keyValuePair => keyValuePair.Value.Errors))
            {
                <li>@modelError.ErrorMessage</li>
            }
        </ul>
    </div>
</div>

This Partial View approach gives you total control over what HTML structure/tags, CSS classes, etc you want applied to the validation summary.

Two things to take not in the above code:

1 - When the form is accessed for the 1st time, ModelState.IsValid is true and the CSS class validation-summary-valid is applied to the containing <div>.This is so so that it conforms to the standard ValidationSummary that comes with ASP.NET MVC and because this CSS class is used by jQuery unobtrusive validation code.
The standard Site.css file that comes with an empty ASP.NET MVC project also uses this very CSS class to hide the validation summary initially. It has this CSS rule:

.validation-summary-valid {
    display: none;
}

When post backing the form data, the view Model may pass the unobtrusive client side validation but may not pass the server side validation and in this case ModelState.IsValid will be false. Again to be conformant with jquery validate unobtrusive code we must set the class validation-summary-errors to the validation summary container. This is imperative; if we do not do this, then we won’t see the validation errors that come from the server side since the validation summary will be hidden.

2 - panel panel-danger are Bootstrap’s CSS classes that give some charming to our custom ValidationSummary. You can check Bootstrap 3 panel component here.

Following the above simple HTML structure it’s possible to make the custom validation summary compatible with jQuery Validate.

Here’s the end result:

ASP.NET MVC Custom Validation Summary with Bootrap 3 Look & Feel using Panel component

To get the above look & feel I changed some CSS classes in ~/Content/Site.css file to override Bootstrap’s CSS. Here are them:

.panel-body {
    padding: 10px;
}

ul, ol
{
    margin-bottom: 0;
    padding-left: 17px;
}

.panel
{
    margin-bottom: 0;
}

.form-group {
    margin-bottom: 0;
}

As a final take on this matter, it’d be great if the standard ASP.NET MVC @Html.ValidationSummary had a method overload accepting a template name. Let’s hope that in the future this gets added.

I assembled a sample ASP.NET MVC project and uploaded it to GitHub. Feel free to play with it and adapt it to your use case. Here’s it is: https://github.com/leniel/AspNetMvcCustomHtmlValidationSummary

Happy coding! Party smile

Prevent JavaScript code blocking the UI thread with setTimeout + a handy stopWatch to profile JS code

In early January of this year I was implementing some JavaScript code that does a lot of processing on the client side with the help of jQuery. It’s part of a project where my customer asked for the possibility of answering a questionnaire in two ways: using a Wizard (one question at a time) and Listing (all questions at once) in a single form. The client side code for the Listing is the culprit and the subject of this post. It’s also related to this question I posted at StackOverflow on February 19:

Why ASP.NET MVC default Model Binder is slow? It's taking a long time to do its work

That question on SO is the inverse part, that is, the server receiving the client side data, but that’s just the other “part” of the problem which I also managed to solve. I really hope that this post helps you understand the problem with the client side part at least…

One of the things that I didn’t like in that JavaScript code was that while the questions were being processed to be rendered subsequently by the JavaScript/jQuery client side code, the browser UI thread hung/froze a lot of times – I think it’s worth mentioning here that I didn’t get Firefox’s warning prompt for "Unresponsive script". Anyway, the simple fact that the page freezes gives the user and me the developer a feeling that something is wrong with the code. As users we expect things to be fluid – we expect a good UI experience and seeing your browser freezing while loading a web page is not the best impression one may have of your software product.

I’m more experienced with server side code and haven’t ever seen any of my JavaScript code run slow on the client. I then started searching on Google why this was happening and just stumbled on this really helpful and insightful article at O’Reilly Answers:

Yielding with JavaScript Timers

Read it carefully to get a grasp of the concepts involved. I read it maybe thrice at least to understand the code and adapt it to the problem at hand. It fitted so well in my situation that the result I got after adapting the code was mind blowing.

The part that really got my attention was the Timed Code section - way bellow that O’Reilly article. It tells us that batch processing items (questions in my case) instead processing everything once or one at a time is more efficient to avoid blocking the UI.

JavaScript UI Queue and UI Thread lanes depicted: timed code is intercalated taking turnsFigure 1 - JavaScript UI Queue and UI Thread lanes depicted: timed code is intercalated taking turns

The JavaScript code I implemented processes a bunch of questions I receive from the server to prepare them to be shown to the user. Using a AJAX GET request’s success callback I dumped all the questions (usually 100 up to more than 200 sometimes and each one formatted with the help of a ASP.NET partial view) inside a div element $("#questions") like this:

// Loading Questions for the Chapter selected...
function loadQuestions(chapterId)
{
    $("#questions").fadeOut('slow').empty();

    $.ajax({
        type: "GET",
        url: "@Url.Action(MVC.UserAssessment.ActionNames.List, MVC.UserAssessment.Name)",
        data: { assessmentId: @Model.AssessmentId, chapterId : chapterId },
        cache: false,
        success: function(questions)
        {           
            $("#questions").html(questions);
            
            setUpQuestions();
        },
        error: function()
        {
            alert("@Html.Raw(Localization.UnknownErrorAjax)");
        }
    });
}

With this I had all the questions’ HTML beautifully inserted on the page but I needed to process this HTML before showing it to the user. That’s where the setUpQuestions(); method played its role. It does the heavy lifting and was where the whole thingy just got screwed up – the browser hung from time to time while inside that method… How did I discover that the problem was inside that method? I used Firebug’s Console and the JavaScript’s Date object as shown in that O’Reilly article. In setUpQuestions I use jQuery’s find, setup form fields validation with jQuery validation plugin, disable/enable fields, apply CSS styles to the questions, etc and all of this was tackled all at once by the poor browser JavaScript engine.

To profile setUpQuestions I created a stopWatch JavaScript method that receives setUpQuestions method as the func parameter:

function stopWatch(func)
{
    var start = +new Date(), stop;

    func();

    stop = +new Date();
if (stop - start < 50)
{
//alert("Just about right.");
console.log("Just about right.");
} else
{
//alert("Taking too long.");
console.log(“Taking too long.");
} }

According to that O’Reilly article, the author recommends never letting any Javascript code execute for longer than 50 milliseconds continuously, just to make sure the code never gets close to affecting the user experience – blocking the UI thread.

When I ran the code selecting different chapters with varying number of questions I kept getting “Taking too long” and then I found where the problem was. I knew it was time to adapt the code presented in the Timed Code section of that O’Reilly article. So here it is and commented where appropriate to make understanding it a little bit easier:

/// More about it here: http://answers.oreilly.com/topic/1506-yielding-with-javascript-timers/
function
timedProcessArray(items, process, callback) { var todo = $.makeArray(items); // The first call to setTimeout() creates a timer to process the first item in the array. setTimeout(function () { var start = +new Date(); do { // Calling todo.shift() returns the first item and also removes it from the array. process(todo.shift()); } // After processing the item, a check is made to determine whether there are more items to process and if the time hasn't exceeded the threshold of 50 milliseconds while (todo.length > 0 && (+new Date() - start < 50)); if (todo.length > 0) { // Because the next timer needs to run the same code as the original, arguments.callee is passed in as the first argument. setTimeout(arguments.callee, 25); }
else { //If there are no further items to process, then a callback() function is called. if (callback) { callback(items); } } }, 25); }

This code made the whole thing fluid and now the user has a much better experience while interacting with the page despite it having a lot of form controls. What it basically does is: process a batch of items/questions and then allows the UI thread to take some processing time and then it repeats until there’s no more questions left in the todo array. The process method is actually the setUpQuestions method that gets passed as a parameter called process.

In my specific case, each question has 4 HTML input elements (input/text, select, etc). If the user selects a Manual’s Chapter to answer and this Chapter contains 230 questions for example, the <form> element will contain about 920 controls = 4 x 230.That's a lot of controls to be processed by the JavaScript code inside the setUpQuestions method. Now no matter how many controls are present in the HTML code. timedProcessArray will handle this easily allowing the UI thread to breath from time to time.

This is the modified version of the loadQuestions method that makes use of this life saving timedProcessArray method where setTimeout shines:

// Loading Questions for the Chapter selected...
function loadQuestions(chapterId)
{
    $("#questions").empty();

    $.ajax({
        type: "GET",
        url: "@Url.Action(MVC.SAvE.UserAssessment.ActionNames.Answer, MVC.SAvE.UserAssessment.Name)",
        data: { assessmentId: '@Model.AssessmentId', chapterId : chapterId, format: '@Assessment.Format.List' },
        cache: false,
        success: function(data)
        {
            var questions = $(data);

            questions.hide().appendTo("#questions");

            //stopWatch(function(){ return timedProcessArray(questions, setupQuestion, stats)});

            timedProcessArray(questions, setupQuestion);

            //stats(questions);
}, error: function() { alert("@Html.Raw(Localization.UnknownErrorAjax)"); } }); }

I didn’t pass a callback function to timedProcessArray but that’s up to you.

Hope it helps you take the most out of your highly intensive processing JavaScript code.

As a last note, with the arrival of HTML5 we now have Web Workers but browser support is still limited. Things are getting better for us developers. Smile In the near future this will be standard for sure but till then we must find a way to solve the problem with the proven tools/code. setTimeout is one of them.

Manage folders & files in your ASP.NET MVC app with elFinder.Net

Recently I had to evaluate what were my options when it comes to managing folders and files in an ASP.NET MVC project – a files manager somewhat like what a Content Management System does but I needed something way simpler and intuitive and principally of easy integration.

The Story
As part of a project requirement, a super user wants to able to offer other users some files like PDFs, Images, Videos, etc. This super user should be capable of creating a folder structure as he sees fit and then upload files to a central point (the server). All this looks like a difficult task to accomplish through a client server architecture since we’re dealing with clients and their files that need to go to the server. At first I thought about using a SharePoint module/web part but then it seemed overkill for what I wanted.

As always I just put some simple words in a Google search and to my surprise I found an outstanding open source project called elFinder by Studio 42. Here’s their ASCII art for your amusement:

      _ ______ _           _           
     | |  ____(_)         | |          
  ___| | |__   _ _ __   __| | ___ _ __ 
 / _ \ |  __| | | '_ \ / _` |/ _ \ '__|
|  __/ | |    | | | | | (_| |  __/ |   
 \___|_|_|    |_|_| |_|\__,_|\___|_|   

elFinder is an open-source file manager for web, written in JavaScript using jQuery UI. Creation is inspired by simplicity and convenience of Finder program used in Mac OS X operating system.

After going through the readme file for a moment, I thought: Oh my god, this is just what I need. The only drawback in my case was that the connector (server part) of elFinder is written in PHP and I’m developing an ASP.NET MVC app. Then let me go to Google once again and type elFinder ASP NET. To my surprise there are some ports to the .NET arena but they seem to lack integration simplicity, that is, the dependencies these ports need just interfere with my current code as was the case of the elFinder ASP.NET Connector that uses Autofac as a dependency. I use Castle Windsor for the IoC part and then this was a no go. A more careful read at the original elFinder wiki let me know about different ports of this amazing project: 3rd party connectors, plugins, modules. This page pointed me to ElFinder.NET connector for elFinder 2.x hosted at CodePlex.

I downloaded ElFinder.NET’s source code that comes with a sample ASP.NET MVC app and played with it. When I saw the amount of features available [ Client options + Connector options ] I almost cried in excitement Crying face. ElFinder.NET is a very well written and organized port put together by Evgeny Noskov. Congrats to him and to Studio 42 from Russia for sharing the code with the community. It works great and so I started integrating it with my ASP.NET MVC 4 app.

Along the way I hit some missing features that I saw are part of the original elFinder by Studio 42. They are startPath and uploadMaxSize. I contacted Evgeny through the CodePlex contact form and asked him about the option to set a start path in the root directory. Thinking he wouldn’t even answer me, I decided to implement it myself looking at the original elFinder codebase. Today I got an e-mail from Evgeny telling me that he just added the start path option to elFinder.Net. What a joy! Then I wanted to set a max upload size and I just saw that this option was also not present in elFinder.Net. Asked about it in this discussion and Evgeny promptly added it to the library. I even had no time to try to implement this one… he went even further and added a must have feature that I didn’t notice was missing: file download.

So after all this amazing story of “is giving that you receive” I decided to spread the word and write a blog post about elFinder.net…

It’s enough of background info. Let me show you one simple use case and how you can take advantage of such outstanding open source project.

The Use Case
Let’s say you want to let one super user with read/write permissions create a folder structure inside a given root directory in the server and upload files there. Other users accessing the app will then be presented with a page that has links that point to the 1st level folders of that root directory. These users will be able to only read those folders/files uploaded by the super user. Note: this app has some kind of membership implemented with roles and permissions granted to users. I’ll omit this part in this sample code for simplicity sake.

The super user has access to a screen (Files menu option) like the following one that contains elFinder files manager:

Figure 1 - elFinder.Net file manager UI styled with jQuery UI supporting any folder depth, file/folder upload/download, delete, rename, copy/cut/paste, preview, properties, drag and drop, etc.Figure 1 - elFinder.Net file manager UI styled with jQuery UI supporting any folder depth, file/folder upload/download, delete, rename, copy/cut/paste, preview, properties, drag and drop, etc.

Other users when logging in for example will have access to a page (Home menu option) listing the 1st level folders like this:

Figure 2 - 1st level folders links allow users to click on them and have the selected folder opened in elFinder’s file manager automagicallyFigure 2 - 1st level folders links allow users to click on them and have the selected folder opened in elFinder’s file manager automagically

When clicking the folder name link, the user will be sent to elFinder’s file manager and the folder will be selected automatically showing its content to the user. The user without super powers then is allowed only to read the folder content and if they want they can even download the files to their machines. The possibilities are endless…

The Code
The full code is available at this GitHub repo: https://github.com/leniel/elFinder.Net

You’ll find comments throughout the code. Make sure you read them carefully.

Let’s start defining two action methods in the HomeController.

public partial class HomeController : Controller
{
    [GET("")]
    public virtual ActionResult Index()
    {
        DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/Files/MyFolder"));
        // Enumerating all 1st level directories of a given root folder (MyFolder in this case) and retrieving the folders names.
        var folders = di.GetDirectories().ToList().Select(d => d.Name);

        return View(folders);
    }

    [GET("FileManager/{subFolder?}")]
    public virtual ActionResult Files(string subFolder)
    {
        // FileViewModel contains the root MyFolder and the selected subfolder if any
        FileViewModel model = new FileViewModel() { Folder = "MyFolder", SubFolder = subFolder };

        return View(model);
    }
}

The Index action method corresponding View has this code:

@model IEnumerable<string>

@{
    ViewBag.Title = "Index";
}

Available 1st level Folders - clicking will navigate you to the File Manager setting the selected folder as elFinder's start path.

<ul>
    @foreach (string folder in Model)
    {
        <li><a href="@Url.Action(MVC.Home.ActionNames.Files, MVC.Home.Name, new { subFolder = folder })">@folder</a> </li>
    }
</ul>

The Files action method corresponding View has this code:

@model FileViewModel

@{
    ViewBag.Title = "Files";
}

@Html.Partial(MVC.Shared.Views.FilesForm, Model)

The FilesForm partial view has elFinder’s client side interesting pieces of code:

@model FileViewModel

@{
    ViewBag.Title = "Files";
}

@* Bundles with elFinder's CSS and JavaScript files configured in App_Start\BundleConfig.cs*@
@Styles.Render("~/Content/elfinder")
@Scripts.Render("~/Scripts/elfinder")

<script type="text/javascript">
    $(function ()
    {
        var myCommands = elFinder.prototype._options.commands;

        var disabled = ['extract', 'archive', 'resize', 'help', 'select']; // Not yet implemented commands in ElFinder.Net

        $.each(disabled, function (i, cmd)
        {
            (idx = $.inArray(cmd, myCommands)) !== -1 && myCommands.splice(idx, 1);
        });

        var selectedFile = null;

        var options = {
            url: '/connector', // connector route defined in the project folder App_Start\RouteConfig.cs
            customData : { folder : '@Model.Folder', subFolder: '@Model.SubFolder' }, // customData passed in every request to the connector as query strings. These values are used in FileController's Index method.
            rememberLastDir: false, // Prevent elFinder saving in the Browser LocalStorage the last visited directory
            commands: myCommands,
            //lang: 'pt_BR', // elFinder supports UI and messages localization. Check the folder Content\elfinder\js\i18n for all available languages. Be sure to include the corresponding .js file(s) in the JavaScript bundle.
            uiOptions: { // UI buttons available to the user
                toolbar: [
                    ['back', 'forward'],
                    ['reload'],
                    ['home', 'up'],
                    ['mkdir', 'mkfile', 'upload'],
                    ['open', 'download'],
                    ['info'],
                    ['quicklook'],
                    ['copy', 'cut', 'paste'],
                    ['rm'],
                    ['duplicate', 'rename', 'edit'],
                    ['view', 'sort']
                ]
            },

            handlers: {
                select: function (event, elfinderInstance) {

                    if (event.data.selected.length == 1) {
                        var item = $('#' + event.data.selected[0]);
                        if (!item.hasClass('directory')) {
                            selectedFile = event.data.selected[0];
                            $('#elfinder-selectFile').show();
                            return;
                        }
                    }
                    $('#elfinder-selectFile').hide();
                    selectedFile = null;
                }
            }
        };
        $('#elfinder').elfinder(options).elfinder('instance');

        $('.elfinder-toolbar:first').append('<div class="ui-widget-content ui-corner-all elfinder-buttonset" id="elfinder-selectFile" style="display:none; float:right;">'+
        '<div class="ui-state-default elfinder-button" title="Select" style="width: 100px;"></div>');
        $('#elfinder-selectFile').click(function () {
            if (selectedFile != null)
                $.post('file/selectFile', { target: selectedFile }, function (response) {
                    alert(response);
                });
               
        });
    });
</script>

<div id="elfinder"></div>

The last part is the FileController that gets called in every connector request:

public partial class FileController : Controller
{
    public virtual ActionResult Index(string folder, string subFolder)
    {
        FileSystemDriver driver = new FileSystemDriver();

        var root = new Root(
                new DirectoryInfo(Server.MapPath("~/Files/" + folder)),
                "http://" + Request.Url.Authority + "/Files/" + folder)
        {
// Sample using ASP.NET built in Membership functionality... // Only the super user can READ (download files) & WRITE (create folders/files/upload files). // Other users can only READ (download files) // IsReadOnly = !User.IsInRole(AccountController.SuperUser)
            IsReadOnly = false,
Alias = "Files", // Beautiful name given to the root/home folder MaxUploadSizeInKb = 500 // Limit imposed to user uploaded file <= 500 KB }; // Was a subfolder selected in Home Index page? if (!string.IsNullOrEmpty(subFolder)) { root.StartPath = new DirectoryInfo(Server.MapPath("~/Files/" + folder + "/" + subFolder)); } driver.AddRoot(root); var connector = new Connector(driver); return connector.Process(this.HttpContext.Request); } public virtual ActionResult SelectFile(string target) { FileSystemDriver driver = new FileSystemDriver(); driver.AddRoot( new Root( new DirectoryInfo(Server.MapPath("~/Files")), "http://" + Request.Url.Authority + "/Files") { IsReadOnly = false }); var connector = new Connector(driver); return Json(connector.GetFileByHash(target).FullName); } }

Hope it helps.

IIS 8 Web Site in Windows 8 externally accessible to the World

Today I needed to allow a per to access an application that’s under development. Instead of buying a cheap ASP.NET hosting account I decided to host the app on my local IIS 8 server. The process to get this configured and working was somewhat exciting since I learned new things along the way.

I’ll show in this post the steps I followed to have this working as expected…

My setup:

  • Windows 8 running inside a virtual machine in Parallels 8 with IP address 192.168.1.107;
  • ASP.NET MVC 4 app deployed in the Default Web Site in IIS 8 that is configured to accept incoming connections in the standard port 80;
  • Linksys WAG200G router/modem connected to the outside/external World.

Steps to follow:
1 - Go to the router’s management interface. In my case it’s located in the address 192.168.1.1.

2 - You’ll need to set a port forwarding configuration. In my case it’s located in Applications & Gaming / Single Port Forwarding. It’ll vary slightly depending on your router vendor and model.

Application: HTTP
External Port: 80
Internal Port: 80
Protocol: TCP
IP Address: 192.168.1.107 (your Windows/IIS machine IP address)
Enabled: True (checked)

Linksys WAG200G Single Port Forwarding configurationFigure 1 - Linksys WAG200G Single Port Forwarding configuration

Make sure to hit the Save Settings button way bellow the page.

3 - Go to Windows 8 Control Panel / System and Security / Windows Firewall / Turn Windows Firewall on or off.
Turn off Windows Firewall for Private Networks.

Turning off Windows 8 Firewall for Private NetworksFigure 2 - Turning off Windows 8 Firewall for Private Networks

4 - Take note of your internet IP address. You can see it in the router’s status page. In my case it’s located in Status / Gateway. Again where you’ll find this info will vary depending on your router vendor.

Taking note of the internet/Gateway IP that uniquely identifies the machine on the internetFigure 3 - Taking note of the internet/Gateway IP that uniquely identifies the machine on the internet

You can also see your current IP Address using Gmail’s Last Account Activity report if you happen to have a Gmail account of course.

5 - Open a browser window and type your internet Gateway IP address taken in step 4. You should be presented with the beautiful IIS 8 default web page if you have no app deployed in the Default Web Site; otherwise you should see your app’s default page/login view.

IIS 8 Default Web Site pageFigure 4 - IIS 8 Default Web Site page

That’s it! Now the web site/app is available externally to any user in any part of the WORLD directly from my development machine.

Anytime I want I can hit Publish from within Visual Studio 2012 and deploy directly to the local IIS 8 server. The user that knows my IP address can then see my ongoing work remotely and free of charge for now.

Note 1
I do not have a static IP address, that is, my ISP here in Brazil (Oi Velox) gives me a dynamic IP address. This means that if there’s a power outage or if the router resets for whatever reason I’ll get a different address – it’s really important to know about this. To overcome such limitation there are some services that can help. One of them is No-IP. It basically allows you to access your computer by a hostname instead of an IP address by using dynamic DNS. They have a free utility app that runs in the background and that automatically syncs your current dynamic IP address with your custom hostname defined in No-IP service.

Excerpts from No-IP site:

What is a hostname?
A hostname is a name given to a computer to make connecting to it easier. Instead of typing out a long IP address you can enter the hostname followed by the domain name, such as myhostname.no-ip.com.

What is dynamic DNS?
Dynamic DNS makes it possible to connect to computers with dynamic IP addresses without needing to know the actual IP address.

They have a free account available with some limitations but it’s worth trying anyway.

Note 2
If for some reason your ISP blocks the default IIS port 80 (something common – hooray! not in my case today) you can try forwarding from a different external port like 8888 in step 2 above. In this case, you’d have to specify this port address when trying to access your IIS server. For example:

189.xxx.xxx.xxx:8888

where 189.xxx.xxx.xxx is your internet IP address.