Archive for the ‘ASP.NET’ Category

Mimicking AJAX behaviour with Generic Handler (.ashx) file uploader

Earlier today I posted a blog about using a generic handler (.ashx) to upload a file to a web server, and in the back of my head I wanted to use it somewhere neat and special, and I also want to find the most reliable and working version. And I also want to learn what the approaches are to doing so, and why not to do it a certain way, etc.

So back to the topic of the post and the first thing that needs to be understood is that you CANNOT upload files with AJAX/JavaScript. This is because of you cannot retrieve the contents of a file off a local system, and if this was so it would cause major security headaches. So what I ended up doing is following the IFRAME approach, by which you make it look as if the upload is happening all AJAX-like when in actual fact its not. So what I did was create an IFRAME:

Notice that I added a div called divTimerValue, which I use to display some progress indicator, in my case it will be busy that will grow and subside with dots. In the source file (where the IFRAME points to) I create a form:

Notice that it has the ReturnValue.ashx action and that I have added an onclick function to the submit button, which looks like this:

        function dotsAnimate() {
            parent.document.getElementById("divFrame").style.display = 'none';
            var dotspan = parent.document.getElementById("divTimerValue");
            dotspan.style.display = '';
            setInterval(function() {
                if (dotspan.innerHTML == 'busy...') {
                    dotspan.innerHTML = 'busy.';
                }
                else {
                    dotspan.innerHTML += '.';
                }
            }, 1000);
        };

The dotsAnimate function uses the setTimeout function to create the animation. The generic handler then returns some HTML that contains a javascript function that clears the timeout and prints a message in the divTimerValue div:

        context.Response.Write(@"");
        context.Response.Write(savedFileName);

And this code produces the desired result.

  • Share/Bookmark

Uploading files with a generic handler (.ashx)

In recent times, the last year or so, I have come to move away from web forms and move more towards an architecture that involves plain html combined with web services or in some cases generic handlers. I like this approach because it allows me to perfectly control the quality of the HTML that is rendered, which in turn is good for a few reasons, one being search engines and the other being true to web standards (or at least trying to). Its relatively easy to combine an asynchronous call with an ASHX file. ASHX files are lighter in terms of processing than their ASPX counterparts. With that in mind I decided to write or create a generic handler based on Scott Hanselman’s example here. And it works! Thats the key thing.

First create an HTML file and add code for a form like this:

Then you create the code in the ASHX file like this:

        string savedFileName = "";

        foreach(string file in context.Request.Files)
        {
            HttpPostedFile hpf = context.Request.Files[file] as HttpPostedFile;
            if (hpf.ContentLength == 0)
                continue;
            savedFileName = context.Server.MapPath(Path.GetFileName(hpf.FileName));
            hpf.SaveAs(savedFileName);
        }
        context.Response.Write(savedFileName);
  • Share/Bookmark

Sites that use Silverlight, updated

Last year July I wrote a blog post that listed some sites that use Silverlight to power rich application content. Twelve months later and I have found a few more cool ones, although the Hardrock Memorabilia site still remains my favourite.

ShineDraw still remains a great site for checking out the same things done in either Flash or Silverlight. And its updated regularly, which is always great.

In the meantime though I have found two other cool examples of Silverlight:

  • Share/Bookmark

My opinion on webforms and such

Today someone asked me what my opinion on webforms are or were, and sometimes I feel like the proverbial deer that gets caught with the light in his eyes. It probably seemed like I knew nothing about web forms, which is not entirely true. I mean I did a lot of my first ASP.NET programming with web forms, and its a really great platform for several reasons. Firstly you can develop a working demo of something in really short order, you don’t have to really go out and code a user control from scratch, because the controls that are already there are pretty good. I mean the Gridview/Datagrid control is pretty cool and it is pretty customizable. Secondly ASP.NET does a good job of taking HTTP from the stateless protocol it is, to a model that maintains state quite well. I coded a lot with ASP.NET Webforms and its not a bad technology or platform to work with.

In the same breath, however, I have been working with SOAP calls and web services for the last 8 to 9 months and what I like the most about this approach is the freedom to totally control the markup that is rendered in the browser. With web forms you had to deal with something called ViewState which could in some scenarios make a mess of your code. I like clean HTML. What the SOAP/Webservice model also kinda reinforces is that HTTP is stateless and should be treated as such.

I have also been doing some ASP.NET MVC and I personally like it, a lot, and will continue developing a bit more with it. There is a clean and clear separation between your presentation logic and your business logic and there is no viewstate.

Maybe I need to do some more webforms for a bit to get to grips with it again, maybe not. I do prefer spending time learning C# language features actually.

  • Share/Bookmark

using System.Web.UI.DataVisualization.Charting;

Ok so I recently got a request to do a project that uses all kinds of pretty charts, and initially the development team wanted to use Open Flash Charts, but the developer I was working with on the project was on leave for two days and in that time I decided to check out New ASP.NET Charting Control: . First thing you need to do is download the free Microsoft Chart Controls and install that on your machine. Note that once installed it creates a folder under Program Files called Microsoft Chart Controls, with another folder called Assemblies under that, which contains DLL’s for both web and application. Once you have installed Microsoft Chart Controls you can choose to add the VS 2008 add-on if you are going to be doing web-forms development, but if like me you use a lot of web services and AJAX, you may not need it. So how do you get to use it then otherwise? By adding these two lines in your web.config file:



You then have access to a range of classes by typing the fully qualified namespace like this:

System.Web.UI.DataVisualization

Once you have access to the classes you can do all sorts of interesting things. You get to choose from 35 different chart types, that you can format with colours, 3D effects. And you can also use data with it very easily with a datareader, which impressed me. You can also save your charts as images.

  • Share/Bookmark

My Top 5 .NET Resources

I use Google a lot for .NET resources, but I do have a few places I read a lot, and not just to get solutions but also to read about other people’s solutions. Reading about other people’s solutions is a key to learning, and learning is important to any developer’s success. Here are my top resources for .NET related topics:

  • ASP.NET Forums: Ever noted that a lot of the Google search results for ASP.NET point to posts on this forum. Do yourself a favour and register, and try to visit as regularly as possible, try and answer a few questions, or just read the solutions that are posted there. You will learn something. The posts are very fresh and is updated by the minute, so the content grows, so no chance of stagnant content.
  • Scott Guthrie’s blog: This blog has all the latest stuff on it, from ASP.NET MVC to Silverlight. If you want to know whats new make sure you read this blog.
  • Shine Draw: Looking to do something in Silverlight that you have seen done in Flash? Take a look here and maybe you can draw some inspiration.
  • 4 Guys from Rolla: Scott Mitchell has written a lot about .NET, and I read his article about URL Rewriting in ASP.NET on MSDN, so the articles on 4 Guys From Rolla really cover relevant and good topics. I also found that they write the articles in relatively easy to understand language.
  • Codeplex: Is Microsoft’s Open Source project hosting site and contains a lots of .NET projects
  • Share/Bookmark

On that Session-less shopping cart issue

In my post yesterday I mentioned that I would like to develop a session-less shopping cart through the use of web services and classes. Well, I changed my mind a bit because I am not sure if AJAX can maintain state. Can it? How will AJAX retain state? I’m not sure yet, so sessions it is.

There are some important reading bits that need to be covered before you can get stuck into sessions, and its always better to try and understand something as far as possible before you simply jump in and implement it. The first article that proves invaluable (and very important) is the ASP.NET Page Lifecycle where after I can recommend you read the State Management Overview Article to understand the difference between Client side and Server side state management and what each offers. Why is state management such an issue? Well firstly because HTTP is stateless, after you make a request to a web server for a web page there is no further communication between you and that server. So to create a state, you use a state management technique, which can either be client or server side. With either technique you have several options and each option has some advantages and disadvantages.

My fear with session state management was the performance hit my server might take, but I have not really tested it enough to make that assertion.

  • Share/Bookmark

Unobtrusive JavaScript and a Session-less shopping cart

What is the idea behind unobtrusive JavaScript? What makes JavaScript unobtrusive? Does it mean removing any onlclick events in your markup and handling those click events with an approach as provided with jQuery? With jQuery its very (extremely) easy to traverse between DOM elements and its even easier associating events to elements and executing them.

I havent been doing a lot of JavaScript recently but you cannot really avoid it, but you can also not build an entire website with JavaScript and HTTPRequests alone (not search engine friendly), but you can also not rely entirely on server side code to do all the magic for you.

The other issue that has been bugging me of late is the idea of creating a session-less shopping basket, a shopping basket that uses a combination of web services and traditional classes. Within the .NET environment the only reason you might need to use sessions is to store DataTables or DataSets, but the question is how expensive is that on server resources. Would I be able to create the same session-based application with web services and traditional classes? After all you are adding web references to your web applications, and those web references all contain class declarations.

  • Share/Bookmark

ASP.NET, handlers and IHTTPHandler

I have never used handlers (.ashx) files in any of my .NET web development projects, but this all changed in the last two days. The way I understand a handler is that it acts as a ‘process’ handler and does not write any output to the browser. Where would you use this? Well I used it for a shopping cart (but in hindsight I will change this) by using a handler to process the items added to the cart. The handler took a querystring and created a datatable of none existed or added the data to a datatable if that datatable already existed and stored the datatable in a session variable, which could then be accessed throughout the application. Accessing querystring variables in a handler file requires that you implement the IHTTPHandler interface, i.e. you cannot simply type Request.Querystring in the handler.

  • Share/Bookmark

Panel and its DefaultButton property

ASP.NET has a server control called a panel, which allows you to display other server controls or HTML elements inside it, and one of its properties is DefaultButton. By setting the DefaultButton to the ID of a button within the panel you basically set its default keyboard event that will fire the click event associated with that button. The other alternative to this would be to add the property to the TextBox in your CodeBehind.

  • Share/Bookmark
Get Adobe Flash playerPlugin by wpburn.com wordpress themes