Archive for the ‘Web Development’ Category
Getting POST values with an ASHX file
Posted by fr3dr1k | Filed under AJAX, C#, Web Development, Web Technologies
Today I had this scenario where I wanted to post items from multiple HTML input elements to a generic handler (.ashx) file without using the action attribute of the form. Specifying the action meant that that you are navigated away from the page where the action is happening, which means re-creating UI logic. How did I achieve this? By using an XMLHttpRequest and using a POST method. GET places everything inside a querystring, which is ok, but I just wondered what would happen if the content was too long for the querystring. I guess the same can be said for POST, but it just seems POST uses a different way to transfer the data. So lets say you had this JavaScript:
getXMLHTTPPostObject: function(url, elementName, parameters) {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
alert("Your browser does not support XMLHTTP!");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
document.getElementById(elementName).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", url, true);
xmlhttp.send(parameters);
}
I use this function to create an XMLHttpRequest object by passing it:
- the URL for the AJAX call
- an elementName to put the result of request in
- A parameter list
I then have a function like this:
addPost: function() {
objXMLHTTP.getXMLHTTPPostObject("url to handler", "categoryTemp", "postTitle=" + document.getElementById("txtPostTitle").value + "&blogpost=" + document.getElementById("txtBlogPost").value);
}
The function gets the values of two HTML input elements and passes it as parameters. The parameters are then used in the POST HTTPMethod. My next challenge was to get the data in the generic handler (.ashx) so that I can process it. I also wanted to return the data from the ASHX file to see that its processed successfully. So in my handler I created this code:
context.Response.ContentType = "text/plain";
System.IO.Stream body = context.Request.InputStream;
System.Text.Encoding encoding = context.Request.ContentEncoding;
System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding);
//if (context.Request.ContentType != null)
//{
// context.Response.Write("Client data content type " + context.Request.ContentType);
//}
string s = reader.ReadToEnd();
string[] content = s.Split('&');
for (int i = 0; i < content.Length; i++)
{
string[] fields = content[i].Split('=');
context.Response.Write("
" + fields[0] + "
");
context.Response.Write("
" + fields[1] + "
");
}
//context.Response.Write(s);
body.Close();
reader.Close();
I first create a class of type Stream that is instantiated through the Response.InputStream property, after which I set the content encoding for the response object. I then create a StreamReader instance and call its ReadToEnd method. After this I do some string manipulation and return the text back to the XMLHttpRequest object, which then writes the content to an HTML Element.
JavaScript alphabetical sorting (A is less than a)
Posted by fr3dr1k | Filed under AJAX, Web Development, Web Technologies
So A < a, which means if you use the sort() function and your array contains elements starting with upper and lowercase then the uppercase will appear first, i.e.:
Art, ASP.NET, LawDeed, LINQ will appear as:
ASP.NET
Art
LawDeed
LINQ
To get this working correctly you need the following function:
charOrdA: function(a, b) {
a = a.toLowerCase(); b = b.toLowerCase();
if (a > b) return 1;
if (a < b) return -1;
return 0;
}
This function will make sure your alphabetical sortorder is correct so that the list appears like this:
Art
ASP.NET
LawDeed
LINQ
You have to pass the function name to the sort function like this:
arrCategories.sort(charOrdA);
Note that there are no parenthesis.
Choosing a JavaScript library/strategy
Posted by fr3dr1k | Filed under Web Development
JQuery, prototype, scriptalicious, moo tools and Microsoft Ajax are all JavaScript libraries that encapsulate common functionality, or rather commonly repeated tasks, into a re-usable form. One such example is accessing DOM elements. Usually you would type document.getElementById to get to a div element for example, which also implies for each element you access you have to type document.getElementById. Most JavaScript libraries provide an easy way to access elements, usually through a dollar($). In jQuery you simply type $(‘elementID’) and in Microsoft Ajax you type $get(‘elementID’) to get to the object. So basically the library has encapsulated the document.getElementById in some JavaScript function, and that function simply returns the object. Most JavaScript libraries also provide built-in AJAX functionality, which means that the library makes it easy to create XMLHTTPRequests. The libraries also make it easy to do all kinds of special effects such as animations and modal popups.
So which one do you use? What determines which one you use? Well personally I would take a pragmatic approach and say that no matter which library you choose, you still have to learn the basic concepts such as how HTTP requests work and how things are executed. Once these things are understood you can pick a library and make sure you learn it. Whether you pick jQuery or Microsoft Ajax is irrelevant, because with both you will have to spend time learning how the API works. I often find myself in a situation where I want to jump between libraries because I feel that there is a wow feature in the one and not the other. I also find myself creating my own JavaScript at times because I just don’t need the entire library. The most important thing to know though is that you have to commit your time and energy to learning JavaScript with or without the use of a library.
Mimicking AJAX behaviour with Generic Handler (.ashx) file uploader
Posted by fr3dr1k | Filed under ASP.NET, C#, Web Development
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.
Deciding on a web-based user login system
Posted by fr3dr1k | Filed under General, Web Development
This article aims to discuss some of the web-based user login systems that are available to .NET developers, and aims to provide some clarity. In my view there are three approaches that can be followed to developing a web-based user login system for .NET:
- Write a custom solution
- Use existing ASP.NET Membership and Roles
- Use OpenID
Writing a custom solution
I think its easy thinking I can write my own custom login system, right? I mean what are the things I must consider for writing my own custom login system. I must consider that users will each have an unique login and that users will be grouped into roles. Thats as far as basic structure goes. But how do you maintain a user’s login session for example, or when do you consider the session over? I have also seen systems that store user passwords in clear text, which means your system MUST use some sort of hashing or encrypting of passwords. There is a lot involved in writing a custom user login system, a lot more than meets the eye.
Use existing ASP.NET Membership and Roles
The ASP.NET Membership and Roles ships with .NET 2.0, and is implemented as an API in code.
Use OpenID
Stackoverflow uses it!
using System.Web.UI.DataVisualization.Charting;
Posted by fr3dr1k | Filed under ASP.NET, C#, Web Development
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:
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.
HTML 5 and other new web technologies
Posted by fr3dr1k | Filed under Web Development, Web Technologies
Read the spec here. The most interesting aspect of HTML 5 to me is this:
HTML 5 will be great step forward, standardizing things like dragging and dropping elements on web pages, in-line editing of text and images on sites and new ways of drawing animations. There’s also support for audio and video playback without plug-ins, a boon for usability and a worrisome sign for Adobe’s Flash, Microsoft’s Silverlight and Apple’s QuickTime. The language will also give a boost to web apps, as there are new controls for storing web data offline on your local machine.
On that Session-less shopping cart issue
Posted by fr3dr1k | Filed under ASP.NET, Web Development, Web Technologies
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.
Thoughts on PHP
Posted by fr3dr1k | Filed under Web Development, Web Technologies
Wordpress runs on PHP, and PHP runs on Apache, this blog uses PHP and Apache to serve up content, and .NET doesn’t. So whats the point then? Well, for all intents and purposes I have a technology that can be used to develop and maintain large commercial websites without having to change to a .NET hosting provider. The point being that while I love .NET I cannot really develop commercially websites with it unless I pay for extra hosting and in these lean economic times I cannot see myself paying more money for hosting. That means that I have to rely on technologies such as PHP.
I have been reluctant to use PHP simply because the software tools available cost money, such as Zend Studio, but I did find PHP Development Tools as part of Eclipse and today I started doing some basic PHP stuff, and its amazing to see how easy it is to adapt to PHP if you have used C#. The syntax is very similar. One of the biggest differences between PHP and .NET is the way pages are handled. .NET uses postbacks, and all the .NET code is compiled, not interpreted. PHP on the other hand interprets its code and the way it basically works is that Apache passes a request over to PHP if it detects any PHP. The PHP interpreter then executes the PHP. As far as syntax goes PHP is similar to most programming languages. Features such as assignment operators and conditional statements are similar.
jQuery and Microsoft
Posted by fr3dr1k | Filed under AJAX, ASP.NET, Web 2.0, Web Development
I susbscribe to The Code Project’s newsletter and today I got some great news, jQuery will be supported in Visual Studio 2008. Now this is some awesome news. Makes one wonder if the Microsoft AJAX library will become redundant.
You can read the full article on Scott Gu’s website.
