Google Knol now open to everyone

Posted by – July 23, 2008

Google’s Knol service is being billed as a Wikipedia killer, and while it has its similarities in purpose it has differences in implementation that set it apart. First of all, the Knols (individual units of knowledge) are not as open as Wikipedia. Individuals can collaborate in groups but you can also make control your own knol and be its sole contributor.

In practice this means that there can be many Knol articles about the same subject and this will mean less consolidation and more diversity. The mission statements are very different as well, and you don’t need to write with a neutral point of view on a Knol and can produce original research. You can probably post a lot of pure garbage that wouldn’t be allowed on Wikipedia on a Knol.

The effect that I predict that this will have is that Knols will be more like individual web pages than a Web Encyclopedia. And they are going to tend to be more commercial and less academic without the encyclopedic purpose and with the revenue sharing of Adsense ads that they will offer their contributors.

Expect a SEO heavy crowd in the early stages. This is going to be more like blogging that Wikipedia in effect.

Convert UTC dates to local timezone offset automatically

Posted by – September 11, 2007

So I was working on an application that printed out lots of dates to the user. However, I get traffic from all over the world, and as this is kind-of time sensitive information, I wanted to display the time in their own timezone. I have don’t this before on things like forums, where you allow the user to select their timezone when they register. But what if your users don’t register?

I decided to build a javascript function that would automatically convert from UTC time to the users’ local timezone. This is a pretty simple task, and should work very effectively. I already store the dates in my database as UTC format, which is a good idea to do so that there is never any confusion later as to what timezone a date is in (What if you and/or your server moves?). Also because this is a javascript function, we have the ability to determine the users local time – something that we normally wouldn’t have.

Without further ado, here is the code:


var dateFunction = {
  convertDate : function (gmtDate){
    var originalDate = new Date(gmtDate);
    var retStr = (originalDate.getMonth()+1) + "-" + originalDate.getDate() + "-" + originalDate.getFullYear();
    return retStr;
  },
  init : function(){
    var elems = YAHOO.util.Dom.getElementsByClassName('utcDate');
    for(var i=0;i

As you can see, I am using the YUI library to do some DOM parsing, and unobtrusively add some event listeners. The code should be pretty straight forward, when the page loads I look for all elements with a class of "utcDate" and pass the innerHTML into a separate function. The other function create a new date object, using the original UTC date as the time. By doing this, javascript automatically will display this new date in the users' local time. I can then return the date in whatever format I want. Finally, I replace the innerHTML of the element with the new date string, and we are all set

This provides a simple way to convert dates to local timezone offset, and all the is required is for you to wrap any date you want converted in an element with a class equal to "utcDate". It also degrades gracefully, because without javascript users will simply see the date in UTC format, which isn't really a bad thing, and probably what you would be showing them anyways, if you didn't have this nifty script!

rss 2.0 feed format tutorial for .NET

Posted by – August 22, 2007

I have been creating custom blog software using csharp.net. One task that I accomplished today was getting both an RSS and an ATOM feed setup. This will allow people to read the blog on sites like netvibes, my yahoo, or google IG. So heres how I did it:

  1. Change the content type of the page to text/xml

    This is needed so that other computers and browsers will know that it is an XML page they are reading, and not the standard HTML. Luckily this is simple to do, simply add ContentType=”text/xml” to the Page directive, like so:

    
    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="rss.aspx.cs" Inherits="rss" ContentType="text/xml"%>
    
  2. Setup RSS 2.0 XML Document

    Now in our code behind file, we can write directly to the output stream, as the proper header is already set. You may think about using Response.Write to create the RSS XML tags, but there is a much easier way. You can use an XmlTextWriter to achieve the same result, without needing to escape all characters that can’t normally be in an xml file

    
            // Create a new XmlTextWriter instance
            XmlTextWriter writer = new XmlTextWriter(Response.OutputStream, Encoding.UTF8);
    
            // Create Document
            writer.WriteStartDocument();
                writer.WriteStartElement("rss");
                writer.WriteAttributeString("version", "2.0");
                    //Set Channel Information
                    writer.WriteStartElement("channel");
                        writer.WriteElementString("title","[SITE_TITLE]");
                        writer.WriteElementString("link",[SITE_URL]);
                        writer.WriteElementString("description",[SITE DESCRIPTION]);
                        writer.WriteElementString("lastBuildDate",[RFC-822 DATE]);
    

    Here we setup the start of the XML document with all required fields. The lastBuildDate element should be the last time the xml feed has changed, which should also be the last time something new was posted.

  3. Output Post information

    The standard is to display them in reverse chronological order. Most likely you will be creating these in a loop, like so:

    
    for (int i = 0; i < postList.Count; i++)
    {
    
        writer.WriteStartElement("item");
            writer.WriteElementString("title",postList[i].pageTitle);
            writer.WriteElementString("link", postList[i].url);
            writer.WriteElementString("description", postList[i].content);
            writer.WriteElementString("pubDate", postList[i].postDate);
            writer.WriteElementString("guid", postList[i].url);
        writer.WriteEndElement();
    }
    

    Here I am assuming postList is a list of object containing post information. The pubDate tag is the date that the post was published, and guid is a globally unique identifier for the post. If you have a GUID setup in the database for the post you can use it, otherwise it's easiest to just use the permalink (url).

  4. Close Document

    Now that we have displayed all relevant information, we simply need to close open tags, and end the xml document

    
                    writer.WriteEndElement();
                writer.WriteEndElement();
            writer.WriteEndDocument();
    writer.Close();    
    

    Thats all there is to it. You can now use this page to submit to sites such as netvibes, google ig, my yahoo, or any other services that will parse rss 2.0 xml feeds.

CSharp Blog ping code using xml-rpc and weblogupdates.ping for Pingomatic, Technorati

Posted by – August 1, 2007

I am currently writing a custom blog application in csharp.net (c#.net). One requirement for the software was that it needed to send update information to sites like Technorati or Ping-o-matic. After some research, I’ve found that sites allow you to do this utilizing xml-rpc. The process is called pingback, but it more commenly refered to as simply pinging. Basically every time you write a new post, you can ping these services to tell them you have updated content, and let people know about it.

The specific method we want to access via xml-rpc is called “weblogUpdates.ping”. This function is implemented on all blog ping services. Below is a function which defines a list of sites to ping, then goes through and pings them one by one. It takes as parameters the name of your site, and the url of your site.


private void sendPing(String name, String url)
{
ArrayList listToPing = new ArrayList();
listToPing.Add("http://rpc.technorati.com/rpc/ping");
listToPing.Add("http://rpc.pingomatic.com");
listToPing.Add("http://blogsearch.google.com/ping/RPC2");

for (int i = 0; i < listToPing.Count; i++)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(listToPing[i].ToString());
    request.Method = "POST";
    request.ContentType = "text/xml";

    Stream stream = (Stream)request.GetRequestStream();

    using (XmlTextWriter xml = new XmlTextWriter(stream, Encoding.UTF8))
    {
        xml.WriteStartDocument();
        xml.WriteStartElement("methodCall");
        xml.WriteElementString("methodName", "weblogUpdates.ping");
        xml.WriteStartElement("params");
        xml.WriteStartElement("param");
        xml.WriteElementString("value", name);
        xml.WriteEndElement();
        xml.WriteStartElement("param");
        xml.WriteElementString("value", url);
        xml.WriteEndElement();
        xml.WriteEndElement();
        xml.WriteEndElement();
        xml.Close();
    }

    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    {
        using (StreamReader sr = new StreamReader(response.GetResponseStream()))
        {
            string result = sr.ReadToEnd();
            sr.Close();
        }
        response.Close();
    }
}

The Dictionary Object: similar to PHP arrays.

Posted by – July 25, 2007

In a previous post entitled Associative Arrays in VB.NET I spoke of using a Collection Object to achieve similar functionality to associative arrays in PHP. Upon further inspection, I feel that the System.Collections.Generic.Dictionary Object (hereafter written as Dictionary Object) is a closer match.

The reason I initially chose to write about the Collection Object is because the Dictionary Object requires all keys to be of the same type, and all values to be of the same type. Of course .NET (both VB.NET and CSharp.NET) is a strongly typed language, whereas PHP is not.

The main advantage a Dictionary has over a regular Collection, is that you can edit items. It also provides a syntax to add items which is similar to that of PHP.

The first step is to add the System.Collections.Generic library to your file, with the following directive:

CSharp.NET


using System.Collections.Generic;

VB.NET


imports System.Collections.Generic

Then you can declare the Dictionary Object:
CSharp.NET


<%
        Dictionary dict = new Dictionary();
        dict["one"] = "First Item";
        dict["two"] = "Second Item";
        dict["one"] = "Look, I just edited the first Item!";
%>

VB.NET


<%
        Dim dict As Dictionary(Of String, String) = New Dictionary(Of String, String)
        dict("one") = "First Item"
        dict("two") = "Second Item"
        dict("one") = "Look, I just edited the first Item!"
%>

Look at that! Aside from the missing dollar sign in front of variables, this looks like PHP!

Javascript form validation object

Posted by – July 21, 2007

Today I thought I would share with you what I consider to be a fantastic way to handle form validation in javascript. Of course you need to remember that you have to validate any user input on the server side, but it’s nice to do things on the client side also, so they don’t have to wait as long for a response.

My approach to form validation in javascript involves 2 parts. First off is a extensible object that includes a variety of validation functions that I can have at my disposal. Secondly, I always format my forms with particular IDs, so that I can easily add error messages in javascript. First off, lets discuss the form layout (the easy part). The general rule of thumb here is to create a spot below the form element that will hold the error message, and give it an ID that is the same as the element, with ‘_error’ after it. So


Email:
 

Here the class ‘msg’ simply defines it as being hidden. Then with javascript if we determine email to be invalid, we can set the spans innerHTML to the text we want, and the class to something that will make it appear.

The second part is the fun javascript. What I do is create an empty object which i then prototype out with validation functions. Here is the code:


function Validator()
{
}

/**
 *  Check Email Function
 */
Validator.prototype.checkEmail=function(ELEM, EVENT)
{
  if(EVENT)
  {
    var scope = this;
    YAHOO.util.Event.addListener(ELEM, EVENT, function(){scope.checkEmail(ELEM);});
    return false;
  }
  try
  {
	var elem = this._getElem(ELEM);
	var targetElem = this._findTarget(elem);
	var email = elem.value;
	var regex = /^[-_.a-zA-Z0-9]+@[-_.a-zA-Z0-9]+\.[a-zA-Z0-9]+$/
	if (regex.test(email))
	{
           targetElem.className = "msg";
	   return true;
	}
	else
	{
           targetElem.innerHTML = "please enter a valid email address";
           targetElem.className = "msgshow";
	   return false;
	}
  }
  catch(e)
  {
	alert("Error in Validator() -> checkEmail(): " + e.message);
	return false;
  }
}

Here I create the object, and a email validation prototyped function. The function takes to arguments: an element, and an optional event. If an event is passed in, it is used to create a listener using the yahoo YUI library. This listener will fire on the given event, calling the same function without the optional argument (and thus running the validation).

The rest of the function is fairly straight forward. It first makes calls to getElem, and findTarget. if getElem is given a string, it returns the element with the given ID. If getElem is given an element, it simply returns the element. findTarget simply gets the ID of the passed in element, and appends ‘_error’, then gets the element with the new string ID.

From there is simply runs a regex expression, and if the regular expression matches it makes sure the error message is hidden, otherwise it sets the text and displays the error message.

This total solution is very portable and easy to use. After including the YUI libraries needed, and the validator code, one can add validation to an element by simply doing:


var validator = new Validator();
validator.checkEmail('email', 'change');

The only custom bit of code is two lines, and you have a regular expression checking the input field every time the field is changed, and will dynamically display an error message when incorrect.

multiple line strings in C Sharp

Posted by – July 19, 2007

Today I found something that made my day. I have always hated that you can’t have strings span multiple lines of code in ASP.NET. For VB.NET this makes since, because there is no semi-colon at the end of statements. To get strings to span multiple lines in VB.NET, you can add an ampersand + space + underscore to the end of each line, like so:


dim sample as string = "notice how " & _
"the string is on multiple lines!" & _
"just make sure you put double quotes on the" & _
"beginning and end of each line"

This works for VB.NET, but not so for C#.NET. I have tried changing the ampersand to a plus sign (c sharp’s character to concatenate strings) but this didn’t work. I had assumed it was impossible, until I came across a solution today. Simply put an ‘at’ sign (@) before the string!


string sample = @"notice how
the string is on multiple lines!";

As you can see, in c-sharp.net you don’t need to start and stop the string like you do in vb.net. The only thing that is slightly tricky, is if you start concatenating strings. Then you need to add the @ symbol to every section of string that will be on multiple lines. For example:


string sample = @"this string
is on multiple lines" + someVariable + @" notice
how i had to use an 'at' symbol again, 
however i don't if the string section stays on one line, 
such as" + here + "... get it?";

Enjoy this ability to word-wrap you sql queries, or any other code strings which need to span multiple lines!

WordPress code escape plugin: escapeCode

Posted by – July 15, 2007

The problem with most code escape plugins
After starting this blog, I quickly realized that I need a plugin that will automatically escape html in a code block. Otherwise, it is a big pain to go through and convert all symbols to their escaped equivalents (ex: less then signs to ‘&lt;’). I looked into a couple different solutions, but there was a major problem with them all: they convert the code on input. What this means is after you write a code block, it escapes everything inside of it, then saves it to the database. This works fine, until you need to edit your post. When you go to edit, you see ‘&lt;’ instead of ‘<’. Not only is confusing and hard to read, but when you save it again, then it escapes everything a second time, making what is displayed on your blog incorrect.

Why my wordpress code escape plugin is different
I decided to escape the code blocks right before it is output to the page. This means that whatever you type in a code block is saved that way in the database. Because of this, you can edit posts multiple times, with no errors. When editing a post, the code in the blocks looks exactly how you typed it in, so it’s nice and easy to read. However on page everything is escaped for you. This plugin also gets rid of the ‘Smart Quotes’ that wordpress annoyingly tries to use.

Download / Install escapeCode

  1. download the file: escapeCode.zip
  2. unzip and upload to your plugins directory.
  3. activate it

That’s it! Nice and easy to understand code, with nothing to configure. I’ll also post the code below so if you prefer, you can copy the code and paste it into a php file you create. Enjoy!


(.*?)<\/code>/es', "nsa_contentFilter::formatCodeString('\\\\1')", $content);
        return $str;
        
    }
    
    function formatCodeString($str)
    {
      
      
      $str = str_replace('\"','"',$str);
      $str = htmlspecialchars($str);
      $str = str_replace('&','&',$str);
      $str = str_replace(array("&#8216;", "&#8217;", "&#8242;"), "&#039;", $str);
      $str = str_replace(array("&#8220;", "&#8221;", "&#8243;"), "&#034;", $str);

      return "<code>$str</code>";
    }
}
?>

Dynamic Dropdownlist

Posted by – July 12, 2007

Came across a strange problem today. I was dynamically filling a dropdown list, and also was dynamically creating checkboxes from the database. Basically I have a list of options, and the user needs to select a primary choice (via dropdown) and then a bunch of alternates (via checkboxes). I assumed the best way to do this was:


CheckBoxList checkSet = new CheckBoxList();

ListItem leaf = new ListItem();
leaf.Text = categoryList[i].name;
leaf.Value = categoryList[i].categoryId.ToString();
checkSet.Items.Add(leaf);

//primaryCategory is the dropdownlist defined in aspx file
primaryCategory.Items.Add(leaf);

At first everything appeared great. However, when I tried to submit the form somtimes, i would get the following error:
Cannot have multiple items selected in a DropDownList. This confused me, because I wasn’t trying to set the selected value through code. After some digging, I realized they when I select the checkbox item and then post back the form, asp.net sees that the checkbox was selected before, so sets it’s “selected” property to ‘selected’. My code then adds the item to both the dropdown and checkbox list. However, the dropdown had a selected value of it’s own, and therefore I get the error.

The solution, although it seems odd, is to create two different items in code: one for the dropdownlist, and one for the checkbox.


CheckBoxList checkSet = new CheckBoxList();

//add to checkboxlist
ListItem leaf = new ListItem();
leaf.Text = categoryList[i].name;
leaf.Value = categoryList[i].categoryId.ToString();
checkSet.Items.Add(leaf);

//add to dropdownlist
leaf = new ListItem();
leaf.Text = categoryList[i].name;
leaf.Value = categoryList[i].categoryId.ToString();
primaryCategory.Items.Add(leaf);

Database driven radio buttons

Posted by – July 10, 2007

So I had a great post explaining how to get the value of a radio button if they are dynamically created (such as through a database query) and unforunatly it was lost. Just today I noticed that it was somehow changed to another post about breadcrumbs. I’d like to think I will come back and create another quality post on how to get values of dynamically created, database driven radio buttons.. but until then, here is the short version:

Basically what you are going to want to do it assign a loop counter variable, and add it to the end of each radio button name:


$loopCount = 0;
while($result = mysql_fetch_array($query))
{
   echo "$result[name]";
   $loopCount++;
}

Now when we are error checking values, we can start at 0 and loop until the variable no longer exists.


while($_POST['radioSet' . $i])
{
  //Error check value, post to database, whatever needs to be done
}

Here you can see, regardless of how many “radioSet” inputs we have, our error checker will get them all. In this example I only gave one radioButton for each input name. Of course for each loop, you can have multiple numbers of inputs. Also, you can give each element an ID using a similar naming tactic, which would allow you to control them all with javascript using document.getElementById.