Archive for October, 2009
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.
Uploading files with a generic handler (.ashx)
Posted by fr3dr1k | Filed under ASP.NET, C#
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);
A website requires dedication
Posted by fr3dr1k | Filed under General
One thing I kinda realised again today is that a website is much like a garden, the care you take with it shows. It applies perfectly to a website, because a website needs constant maintenance. Sure you can use a blog engine like Wordpress and get a blog up and running quickly, but it still needs an active person to build the content for the blog. And Wordpress is no longer just a Blog CMS alone, it functions as a web 2.0 tool for communicating. A blog is a social media tool because Wordpress allows you too seamlessly integrate with social media such as Faceboook and Twitter. The whole point though is that even with all the greatest plugins and add-ons in the world a blog is just a static thing that requires one unique thing – a human. In the hands of any individual a blog becomes your personal fingerprint on the www.
The same logic really applies to any other website whether it be a big corporate or a non-profit organisation. The people that run the website make the website what it is, thats the single biggest truth ever.
Getting search results from Bing REST service and using LINQ to process results
Posted by fr3dr1k | Filed under Bing, C#, LINQ to XML
So today I started reading about the Bing API and I got myself an API key and I read through the basic instruction manual, which tells you how to get search results from the web through the Bing REST service. Its pretty straight forward, just get your own key though! But here is some sample code that does the trick and uses Linq to XML to process the results:
XDocument document = XDocument.Load("http://api.search.live.net/xml.aspx?Appid=&query=sushi&sources=web");
XElement root = document.Root;
XNamespace web = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/web";
var searchItems = document.Descendants(web + "Results").SingleOrDefault();
IEnumerable testelem = from el in searchItems.Elements()
select el;
foreach (XElement myElem in testelem)
{
context.Response.Write(myElem.Value + "");
}
That is very easy!
What are extension methods?
Posted by fr3dr1k | Filed under C#
Extension methods in C# enable you to extend existing types without having to create a new type. This essentially means that you can take the class String and add methods to it that extends it, and when you create a string those methods become available. You just have to make sure you include the namespace of the class that implements the methods. A very basic example would be to create an extension method that returns the length of a string. So you start off first by creating:
namespace MyExtensionMethods
{
public static class MyExtensionMethods
{
public static int ReturnText(this String text)
{
return text.Length;
}
}
}
Notice the this keyword before String. Also notice that the class is static and that the method is static, which means that the class can only contain static methods. If you create an instance method in a static class you will get a compiler error. To use the extension method you include the using directive:
namespace ExtensionMethods2
{
using MyExtensionMethods;
class Program
{
static void Main(string[] args)
{
string s = "Test";
Console.WriteLine(s.ReturnText());
}
}
}
Notice that the string s now has an extra method associated to it called ReturnText.
Using video on the web – what are your options?
Posted by fr3dr1k | Filed under General
So you want to use video on your website? Well there are a few options to consider and they all have their distinct advantages and disadvantages. The first thing that you need to understand is that the majority of people, those regular non-techie ones, use browsers that will need some form of plugin, or a new browser. Thus support for video on the NET can be divided into two broad categories:
- A plugin, usually in the form of Adobe’s Flash or Microsoft’s Silverlight
- Browser support, in the form of HTML 5
The first option utilizes some sort of proprietary plugin and both Flash and Silverlight have great development support. Adobe’s Flash is the dominant video-player plugin on the net, with Youtube being a prime example. Silverlight is the less dominant of the two but it also provides a rich set of development tools and is backed by some of the best tools Microsoft has to offer.
The second option you have is to use HTML 5, but the browser support for HTML 5 is limited to Safari, Chrome and Firefox 3.5. None of the Internet Explorer (6,7,8) support HTML 5, thus if you decide on this option you would have to convince your audience to get a better browser.
C# and streams
Posted by fr3dr1k | Filed under Application Development, C#
C# uses a lot of streams, or at least it seems so in some of the code examples I have looked at.
Having said that I felt the need to read up on the Stream class. The stream class is an abstract class and an abstract acts as a type of base class from which other classes can inherit. And just to recap, abstract methods do not have a method body and must be implemented by the class inheriting from it. A method marked as virtual can be overridden but it does not have to be implemented. Methods that are marked as abstract can be overriden.
So the stream class is an abstract base class for a set of other classes that do various operations such as reading content from files, reading files in a directory, etc. Each of the classes that inherit from the base stream class can be seen as a type of stream. Streams can be read from, written to and they support seeking.
The classes that inherit from the Stream class can be divided into three broad categories:
- Classes that are used for File I/O
- Classes that are used for reading and writing to streams
- Common IO stream classes
The reason for taking a look at these classes is because I was looking at a PowerPoint presentation recently. More specifically I was looking at PowerPoint 2007 (pptx) and its underlying XML. If you save a Powerpoint 2007 as XML and you look at the source you will note that there are sections called pkg:binaryData. It got me wondering that maybe that same binary data can be processed in C# code. Take a look at the following sample C# code:
Image img = Image.FromFile(@"C:\Users\fredrike\Documents\LEGAL SUITE.bmp");
byte[] myByte = File.ReadAllBytes(@"C:\Users\fredrike\Documents\LEGAL SUITE.bmp");
Console.WriteLine(myByte.Length);
MemoryStream stream = new MemoryStream(myByte);
int lengthOfByte = Convert.ToInt32(stream.Length);
byte[] mySecondByte = ReadFully(stream, lengthOfByte);
Console.WriteLine(mySecondByte.Length);
Image img2 = Image.FromStream(stream);
img2.Save(@"C:\Users\fredrike\Documents\LEGAL SUITE3.bmp");
Notice a couple of things I have done in the code. I created a Image class instance and read it from an existing bitmap image. I then create a byte array and used the static ReadAllBytes method supplied by the File class. I then just simply wrote the length of the file to the screen because in the next couple of lines I create a MemoryStream instance using the byte array, after which I also get the length property of the MemoryStream instance because I use it in a function called ReadFully:
public static byte[] ReadFully(Stream stream, int initialLength)
{
// If we've been passed an unhelpful initial length, just
// use 32K.
if (initialLength < 1)
{
initialLength = 32768;
}
byte[] buffer = new byte[initialLength];
int read = 0;
int chunk;
while ((chunk = stream.Read(buffer, read, buffer.Length - read)) > 0)
{
read += chunk;
// If we've reached the end of our buffer, check to see if there's
// any more information
if (read == buffer.Length)
{
int nextByte = stream.ReadByte();
// End of stream? If so, we're done
if (nextByte == -1)
{
return buffer;
}
// Nope. Resize the buffer, put in the byte we've just
// read, and continue
byte[] newBuffer = new byte[buffer.Length * 2];
Array.Copy(buffer, newBuffer, buffer.Length);
newBuffer[read] = (byte)nextByte;
buffer = newBuffer;
read++;
}
}
// Buffer is now too big. Shrink it.
byte[] ret = new byte[read];
Array.Copy(buffer, ret, read);
return ret;
}
I got this from Jon Skeet’s website. Be sure to check out his other C# articles. In my code I then created a second byte array which is generated by the ReadFully method. Once the bytes have finished reading I created a second Image instance, img2 and pass it the MemoryStream instance, and I then call img2’s Save method and create a second image based on the first one.
So my question is, can the binary data from Powerpoint presentations be used in the same way?
New look MSDN
Posted by fr3dr1k | Filed under News
Those of you who haven’t noticed yet MSDN has changed its look and feel from the frame-based layout to a brand new layout. My first impressions are that it really rocks.
Reading the content feels much easier. I would have liked to see some more AJAX. Notably you can also switch to the old classic view.
