HTML5 File Drag and Drop Upload With jQuery and ASP.NET Jan 28, 2012 ASP.NET   HTML5   JQUERY   WEB

I came across an article on Tutorialzine which demonstrate file drag and drop upload with jQuery and PHP. As a curious reader, I downloaded the sample files and took a look and also get it running on my LINUX VM. It worked like a charm. But I am a Windows user and .NET programmer, the question is how can I do the same in ASP.NET?

So, to get myself started I used the same downloaded files that I used to check the PHP version of the file drag and drop. The only thing that we are not going to re-use out of these files is the php file. You can delete it if you wish or keep it, it’s of no harm to our ASP.NET app.

Updating The jQuery Part

This example uses an awesome plugin from Weixi Yen and you can found the plugin and it’s sample usage (documentation) on GitHub. The basic or I should say the default functionality provided by this plugin is to allow users to drag and drop the files from desktop to the browser. But before you actually get started with the plugin, I strongly recommend that you make yourself familiar with the parameters and configurations of the plugin.

Open the script.js file and change the URL to point to the web service or the page which will upload the posted file. Here I want you to pay attention to the javascript function named createImage. This method accepts the file as a parameter and returns the image or file data in Base64 format. This is the data which actually gets posted when the user drops a file to the upload area on the web page. This is all up to you whether you want to use a web service or a normal web page to accept the posted file/data. Here is my script.js file looks like after the changes.

$(function () {
 
    var dropbox = $('#dropbox'),
        message = $('.message', dropbox);
 
    dropbox.filedrop({
        paramname: 'pic',
        maxfiles: 5,
        maxfilesize: 100,
        //url: '/Uploader.asmx/Upload',
        url: '/Default.aspx',
 
        uploadFinished: function (i, file, response) {
            $.data(file).addClass('done');
        },
 
        error: function (err, file) {
            switch (err) {
                case 'BrowserNotSupported':
                    showMessage('Your browser does not support HTML5 file uploads!');
                    break;
                case 'TooManyFiles':
                    alert('Too many files! Please select 5 at most! (configurable)');
                    break;
                case 'FileTooLarge':
                    alert(file.name + ' is too large! Please upload files up to 2mb (configurable).');
                    break;
                default:
                    break;
            }
        },
 
        // Called before each upload is started
        //        beforeEach: function (file) {
        //            if (!file.type.match(/^image\//)) {
        //                alert('Only images are allowed!');
 
        //                // Returning false will cause the
        //                // file to be rejected
        //                return false;
        //            }
        //        },
 
        uploadStarted: function (i, file, len) {
            createImage(file);
        },
 
        progressUpdated: function (i, file, progress) {
            $.data(file).find('.progress').width(progress);
        }
 
    });
 
    var template = '<div class="preview">' +
                        '<span class="imageHolder">' +
                            '<img />' +
                            '<span class="uploaded"></span>' +
                        '</span>' +
                        '<div class="progressHolder">' +
                            '<div class="progress"></div>' +
                        '</div>' +
                    '</div>';
 
 
    function createImage(file) {
 
        var preview = $(template),
            image = $('img', preview);
 
        var reader = new FileReader();
 
        image.width = 100;
        image.height = 100;
 
        reader.onload = function (e) {
 
            // e.target.result holds the DataURL which
            // can be used as a source of the image:
            //alert(e.target.result);
            image.attr('src', e.target.result);
        };
 
        // Reading the file as a DataURL. When finished,
        // this will trigger the onload function above:
        reader.readAsDataURL(file);
 
        message.hide();
        preview.appendTo(dropbox);
 
        // Associating a preview container
        // with the file, using jQuery's $.data():
 
        $.data(file, preview);
    }
 
    function showMessage(msg) {
        message.html(msg);
    }
 
});

Check out line number 10 and 11. I have change the url parameter to the one where my files are going to be posted. It can be a webservice or just a normal web page. The other two parameters maxfiles and maxfilesize defines the number of file that can be uploaded asynchronously and maximum size of the file that can be uploaded in MBs respectively. Also note that the demo that you download from the original source will have a validation that the files that are being uploaded by the user should only be images. If you want to override this rule then uncomment the lines from 33-42. This is it from the jQuery/script part. Now time to move on the server side code.

The Server Side Code

To remind you again that we are posting a file to a web service or to a web page and therefore that code for our web service or on our page will look something like this:

If you are using a web service to upload the posted file:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string Upload()
{
       HttpContext postedContext = HttpContext.Current;
       HttpPostedFile file = postedContext.Request.Files[0];
       string name = file.FileName;
       byte[] binaryWriteArray = new
       byte[file.InputStream.Length];
       file.InputStream.Read(binaryWriteArray, 0,
       (int)file.InputStream.Length);
       FileStream objfilestream = new FileStream(Server.MapPath("uploads//" + name), FileMode.Create, FileAccess.ReadWrite);
       objfilestream.Write(binaryWriteArray, 0,
       binaryWriteArray.Length);
       objfilestream.Close();
       string[][] JaggedArray = new string[1][];
       JaggedArray[0] = new string[] { "File was uploaded successfully" };
       JavaScriptSerializer js = new JavaScriptSerializer();
       string strJSON = js.Serialize(JaggedArray);
       return strJSON;
}

Nothing fancy or complicated in the above code. Remember, the files will send to the web service one by one and not in a collection and this is the reason I am working with one file at a time and not with file collections. In my case I have used a web service that return me JSON result which I can show it to the user, though it is not necessary, but just in case if you want to have one for your web service you need to use 2 using statements:

using System.Web.Script.Serialization;
using System.Web.Script.Services;

If you are using a web page to upload the posted file:

HttpContext postedContext = HttpContext.Current;
HttpPostedFile file = postedContext.Request.Files[0];
string name = file.FileName;
byte[] binaryWriteArray = new
byte[file.InputStream.Length];
file.InputStream.Read(binaryWriteArray, 0,
(int)file.InputStream.Length);
FileStream objfilestream = new FileStream(Server.MapPath("uploads//" + name), FileMode.Create, FileAccess.ReadWrite);
objfilestream.Write(binaryWriteArray, 0,
binaryWriteArray.Length);
objfilestream.Close();
string[][] JaggedArray = new string[1][];
JaggedArray[0] = new string[] { "File was uploaded successfully" };
JavaScriptSerializer js = new JavaScriptSerializer();
string strJSON = js.Serialize(JaggedArray);
Response.Write(strJSON);
Response.End();

Same code as I have for the web service, put the above code on the page_load event.

Caution!!

While I was working around with the above code and configuration of the plugin I came across an error that won’t allow me to upload heavy files or I should say large files. The error that I received is:

System.Web.HttpException: Maximum request length exceeded

To overcome this error you have make the below configuration in your web.config file inside <system.web>

<httpRuntime maxRequestLength="102400" executionTimeout="1200" />

A word of caution here, though it will solve your problem but:

  • If the maxrequestLength is TOO BIG then you will be open to DOS attacks.
  • The default executionTimeout is 360 seconds. Change it accordingly and only if you are running on really slow connections.

This is it, if you have followed the steps above then try uploading some file. And if you haven’t and lazy to put all the pieces together then download the code from the below and try it.

Download: HTML5DragNDrpFileUpload.zip (58.15 kb)

Introducing Visual Studio Achievements - Bringing Some Game To The Code Jan 22, 2012 API   MICROSOFT   VISUAL STUDIO

Visual Studio Achievement Logo

Another awesome stuff for developers from Microsoft! This past Wednesday Microsoftie Karsten Januszewski announced the Visual Studio Achievement Beta at Channel9. Guess what? as a developer, you are writing hundred lines of code every day without even getting noticed by the community!!? Well, you will get noticed now. Here is an extract from the official post from Channel9:

Bring Some Game To Your Code!

A software engineer’s glory so often goes unnoticed. Attention seems to come either when there are bugs or when the final project ships. But rarely is a developer appreciated for all the nuances and subtleties of a piece of code–and all the heroics it took to write it. With Visual Studio Achievements Beta, your talents are recognized as you perform various coding feats, unlock achievements and earn badges.

Learn More About Visual Studio

Visual Studio is a powerful tool with tons of features, many of which you may not know about. Earning some of the badges may result in learning about features you didn’t even know existed!

How It Works

With the Visual Studio Achievements Extension, achievements are unlocked based on your activity. Your code is analyzed on a background thread each time you compile. In addition, the extension listens for certain events and actions that you may perform in Visual Studio, reporting progress on these events to the server.

Get the Visual Studio Extension

Download the Visual Studio Achievement Extension from Visual Studio Gallery. Install the extension and fire Visual Studio, sign in with your LiveID and straight away you will achieve 5 points for installing Visual Studio Achievement Extension. Every time you achieve, a pop-up in will be shown inside Visual Studio IDE.

Show off your achievements

Now you are earning some achievements huh!? Why not show it off on your blog. Grab the script to show off your Visual Studio Achievements. You can see my achievements widget on the right hand side of my blog. Just in case you don’t like the widget, then you can customize the look and feel using CSS and providing additional parameters. You can see more widget examples here and customize it as you like. Apart from this you can also see the leading achievers at the Leaderboard.

Visual Studio achievements leaderboard

The Achievement API

Introducing the Achievement and that too with API is super awesome. I haven’t gone through the Achievement API yet, but if you are planning to write a custom tool then mash it up and share with the community.

Visual Studio Achievements Legend

So, what are the achievements that we are going to get? There are 6 different badges at the moment and we are going to see more badges in future. Here is a snap of the 6 badges:

Visual Studio achievements categories

Need to know more in detail about these badges then read about them here. Let’s get started people, bring some game to the code you write from now on!!

Top Visual Studio Extensions Jan 18, 2012 MICROSOFT   UTIS   VISUAL STUDIO

Visual Studio Extensions

Visual Studio comes up with loads of stuff making everyday life of a developer easy. But there are few extensions which Microsoft and other developers have created and are available for free to the community members. I have compiled a list of free and powerful extensions which will take your programming experience few more steps ahead with Visual Studio.

NuGet Package Manager

You should have a very good reason if you are not using this or if you are not aware what NuGet is. NuGet is a free, open source developer focused package management system for the .NET platform intent on simplifying the process of incorporating third party libraries into a .NET application during development.

Visual Studio Achievement Extension

Get noticed, earn achievements while you write code. An awesome extension from Microsoft for programmers to get them in light while they right code. Bring on the game to the code!!

Productivity Power Tools

A powerfull extension from Microsoft with tons of features to make your work a lot easier. A MUST HAVE for every developer.

VSCommands 2010

VSCommands provides code navigation and generation improvements which will make your everyday coding tasks blazing fast and, together with tens of essential IDE enhancements, it will take your productivity to another level.

PowerCommands For Visual Studio 2010

PowerCommands 10.0 is a set of useful extensions for the Visual Studio 2010 adding additional functionality to various areas of the IDE.

Web Essentials

You must have witnessed most of the features provided by this extension in VS 2011 Developer Preview. For Visual Studio 2010, you can make use of these features with this extensions.

JSEnhancements

This extension provides outlining and matching braces highlighting features for Visual Studio JavaScript and CSS editor. Works both in JS/CSS files and HTML script/style blocks. Outlining is like in C# editor. It outlines {}s, []s and #region tags.

DevColor

Microsoft has now introduced feature in Visual Studio 2011 Developer Preview, it is a color picker stuff in the CSS window for the ease of the developers so they don’t have to remember the color codes. But for Visual Studio 2010 developers this is an excellent extension that gives you a similar flexibilty.

CSSCop - FxCop for Stylesheets

We use FxCop to follow beat coding practices, but we neglect when we work with CSS. CSSCop makes it easy to adhere to best practices for writing stylesheets. It catches common errors that affect browser compatibility and much more. You can think of it as FxCop for stylesheets.

FxCop Integrator

If you are analysing your code using FxCop, then get the FxCop extension for Visual Studio. FxCop is also available if you are using VS 11 Developer Preview.

Image Optimizer

Adds a right-click menu to any folder and image in Solution Explorer that let’s you automatically optimize all PNG, GIF and JPEG files in that folder. The optimization doesn’t affect the quality of the images, but optimizes them using industry proven algorithms for removing EXIF and other metadata.

Code Compare

Code Compare is a powerful file and folder comparison tool that demonstrates new level of code comparison.

Spell Checker

The next time you comment on your code or someone else code, be sure that you are using the correct spellings. Plain text files, source code comments and strings and thing that are not HTML/ASP tags are spell checked.

GhostDOC

A great extension which will automatically generates XML documentation comments for methods and properties based on their type, parameters, name and other contectual information.

Numbered Bookmarks

Creating bookmarks in Visual Studio and then remembering them is a tough task when you have thousands lines of code. Numbered Bookmarks allows users to create and recall bookmarks by using numbers. User can create 10 bookmarks (starting from 0 to 9). User can add or navigate to the particular bookmark by using the same shortcut key.

Snippet Designer

The Snippet Designer is an open source plugin which enhances the Visual Studio IDE to allow a richer and more productive code snippet experience.

For the moment, this is it, but I will update the list once I get to know more excellent extensions. Are you aware of any other extensions you think is really cool and excellent, then please do share with me/us.

HTML 5: Show Your Support / Tell The World Dec 3, 2011 WEB

HTML5 Logo

If you really love working with HTML5 the this is then time to show some support for HTML5. Use the HTML5 badge builder to create a badge and use it on your blog/website to show your support. The badge builder allows you to customize the badge with tech you use with HTML5. You can see the badge I customized with the tech under badge section on the right.

HTML5 love

The w3.org site for HTML5 has to offer more than just a badge. You can download HTML5 Logos, stickers, T-shirts, jacket, grey hoodie and beanie to show your love or I must say more precisely show off your HTML5 love. The HTML5 T-shirts are awesome and worth buying if you want to show off. Take a look at HTML5 Logo T-Shirts and buy one if you really like HTML5 and yes if you want to show off and make other jealous.

Get Song Lyrics From LYRDB With ASP.NET MVC And JQuery Nov 26, 2011 API   ASP.NET MVC

Most of the times I have seen people looking for song lyrics on online MP3 or lyrics database sites. Few of them provide API to fetch lyrics which is good for developers. Last.fm has a powerful API but they don’t provide any API call to fetch lyrics. The two most popular APIs on the web that I am aware of is WikiLyrics, LyricsDB (popularly known as LyrDB), there is another API from ChartLyrics but I don’t find it as useful as the other two APIs. The WikiLyrics API works beautifully, but it has one drawback the lyrics fetched from the service is incomplete. I wrote a complete desktop application to fetch lyrics, album art, artist image, album name and album release date but never made it available to download for public. I am planning to release it to general users. But till then you can take a look at this simple little app which I created in my spare time to fetch lyrics from LyrDB. This little simple application is in ASP.NET MVC. I am not a designer so I will take advantage of the default design. In the home controller I have a simple method named GetLyrics which accepts two parameters Artist Name and Song Name. The method returns results in JSON as it will be good for me to parse the results in JQuery. Take a look at the code:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult GetLyrics(string ArtistName, string SongName)
{
          string response = string.Empty;
          string LyrURL = string.Empty;
          string url = "http://webservices.lyrdb.com/lookup.php?q=" + ArtistName + "|" + SongName + "&for=match";
          WebResponse wResp = (WebRequest.Create(url) as HttpWebRequest).GetResponse();
          using (StreamReader sReader = new StreamReader(wResp.GetResponseStream()))
          {
              response = sReader.ReadToEnd();
          }
          if (response == "")
          {
              response = "No Lyrics found on LyrDB for " + SongName + " by " + ArtistName;
              goto Output;
          }
 
          string[] lyrID = response.Split('\\');
 
          response = "";
 
          LyrURL = "http://webservices.lyrdb.com/getlyr.php?q=" + lyrID[0]+"&callback=?";
 
          Output:
 
          return Json(new
          {
              success = true,
              Lyrics = LyrURL
          });
}

The above code does not return the lyrics but the URL to get the lyrics. I am a big Jquery fan and as usual I will be using it here to make an AJAX call and load an IFRAME with the lyrics URL.

$(document).ready(function () {
        $("#btnSearch").click(function () {
            $("#btnSearch").attr('disabled', true);
            $("#lyrics").addClass("loading");
            $("#LyrFrame").attr('src', '');
            var Artist = $("#txtArtistName").val();
            var Song = $("#txtSongName").val();
            var url = "/Home/GetLyrics?ArtistName=" + Artist + "&SongName=" + Song;
            $.ajax({
                url: url,
                type: "POST",
                dataType: "json",
                data: "{'ArtistName': " + Artist + ",'SongName': " + Song + "}",
                success: function (data) {
                    $("#lyrics").html("");
                    $("#btnSearch").attr('disabled', false);
                    $("#lyrics").removeClass("loading");
                }
            });
 
        });
});

The URL in the above script calls GetLyrics method which is inside Home Controller takes artist and song name as query string. On the success of the call the IFRAME gets loaded with the lyrics URL. The output will look something like this:

LyrDB app in action

You can download the application source code from the below link, but I want to tell you that it will not fetch each and every song lyrics for you. It’s a database and it can provide us only information it has. But the desktop application I am will release in future will check around 2 lyrics API at least and I believe that my application guarantees 100% result. So follow my upcoming posts.

Download: LyrDBApp.zip (886.46 kb)

Related Links: