Archive for the ‘Web Technologies’ Category
Interesting code with HtmlAgilityPack
Posted by fr3dr1k | Filed under Browsers, C#
Yesterday I was busy with HTML to PDF conversion and for this I used the HTML Agility Pack. Everything worked great, except it seemed IE and FF/Chrome render different HTML. So today I took some fairly straightforward HTML and pushed it through HTMLAgility:
New Website Under Construction
And if I use this code to loop through the childnodes:
HtmlDocument doc = new HtmlDocument();
string s;
StringBuilder builder = new StringBuilder();
using (StreamReader reader = new StreamReader(@"C:\Documents and Settings\user\Desktop\fremus.net\index.htm"))
{
while ((s = reader.ReadLine()) != null)
{
builder.AppendLine(s);
}
}
doc.LoadHtml(builder.ToString());
Console.WriteLine(doc.DocumentNode.ChildNodes.Count);
foreach (HtmlNode node in doc.DocumentNode.ChildNodes)
{
Console.WriteLine(node.Name);
foreach (HtmlNode childNode in node.ChildNodes)
{
Console.WriteLine("\t\t" + childNode.Name);
foreach (HtmlNode grandChildNode in childNode.ChildNodes)
{
Console.WriteLine("\t\t\t" + grandChildNode.Name);
}
}
}
I get the following result in my command line window:
As you can see from the output the html node has a text node. The head node has a text node, and it has 9 childnodes including 5 #text nodes. The body node has a text node as well, and it has 7 childnodes, four being #text and the other three being div. So what is this #text node? If you read this article on the W3C site you will see that it states:
A common error in DOM processing is to expect an element node to contain text.
However, the text of an element node is stored in a text node.
On the same page it then gives an example using a title tag. If you do a Google on “html #text node“, you will see that the second result points to an article and if you read the bit on the nodes it seems that each #text node is a child. The #text nodes that appear in the body node seem to point to the text spaces after each div or each element inside the body node. If I change my code slightly:
Console.WriteLine("\t\t" + childNode.Name);
foreach (HtmlNode grandChildNode in childNode.ChildNodes)
{
Console.WriteLine("\t\t\t" + grandChildNode.Name);
Console.WriteLine("\t\t\t\t" + grandChildNode.HasChildNodes);
}
It tells me that the divs have child elements, but the #text nodes do not. Thus it seems for each ‘empty space’ inside a node there exists a #text node. If I amend the HTML from earlier like this:
Then the footer div will have two text nodes, and the paragraph node will have a textnode. My issues yesterday had to do with the way IE rendered the HTML and that when I used HTMLAgility to parse it, the node counts weren’t the same. From the sample HTML I have given so far that difference is negligble, but I found that if I went to a site like this one and I saved the HTML from IE and Chrome into separate HTML files and I ran my code with that HTML, I got different node counts. Here are two screenshots that illustrate this:
The first screen is the html from the page saved from chrome and the second one is from ie. Notice the extra text nodes.
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.
Getting to understand JavaScripts prototypal nature
Posted by fr3dr1k | Filed under AJAX, Web Technologies
One of the things that are quite weird to get use to, from a C# developer’s perspective, is JavaScript’s prototypical nature. Check out this basic example:
var objXMLHTTP =
{
getXMLHTTPObject: function(url,elementName) {
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("GET", url, true);
xmlhttp.send(null);
}
};
objXMLHTTP.getXMLHTTPObject("http://localhost/YieldTester/Handler.ashx", "testDiv");
The code above creates a simple XMLHTTPRequest object, but you do not create an instance of the object, you call it directly. Note objXMLHTTP.getXMLHTTPObject. In C# you might have created an object and then you instantiate it through an instance of that object. I have taken the code as is given on W3Schools and modified it a little.
Is Firefox slowly dying?
Posted by fr3dr1k | Filed under Browsers, Chrome, Firefox, Internet Explorer
I mean really, the performance sucks! The Firebug add-on is a 600Kb+ download and it feels as if it really, really slows it down. I have for a while now switched over to Google Chrome, because it is such a fast and responsive browser. I have found one or two issues when using Facebook with Chrome, but other than that its a pretty cool browser. The thing I dislike the most about Firefox is that its process does not terminate completely sometimes, and if you start a new instance of the browser the OS complains that Firefox is still running. Even IE is way quicker than Firefox. I used Firefox for development, and specifically the Firebug and Web Developer plugins, but I have decided to switch over to Chrome, because it does have a developer plugin. IE 8 also has a developer plugin. Thats my two cents for now.
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.
How do you put a value to social media?
Posted by fr3dr1k | Filed under General, Web 2.0
I went to a seminar on SEO and the like last year. A company called Quirk hosted it, and at the time I spoke to one of their people and she indicated to me that they have yet to establish a way to determine the value that social media can bring in terms of monetary benefit. That thought stuck in my head and accidentally I have been a Twitter user for quite some time now and this morning I came across a website called Twendz that ‘analyzes’ trends on Twitter and specifically it listed a lot of American Idol stuff. I know this has probably been done before, but by analyzing what people say on Twitter you get an insight into their thoughts and you can develop trends on those thoughts. I use Twitter to follow developers and I generally get fresh and new articles from them. Following the thoughts of developers might give you insight into their trends. A trend I see sometimes is that a lot of developers from Microsoft are either going to presentations or preparing for them. It also seems developers are developing apps that make use of social media platforms.
Social Media provides trends which to me directly relates to a measurable value. I also think Social Media relates to things such as Cloud Computing.
