Archive for July, 2012

July 31, 2012

Introduction to data structures and algorithms in javascript: Arrays

This is a continuation of a series on data structures in javascript. This week’s topic is the Array. An Array is an enumerated list of variables; meaning that each value can be referenced by a numerical index. The index number is referenced using square bracket syntax and Arrays in javascript are zero based.

document.writeln(someArray[0]);

Numerical based indexes make it easy to loop through an Array.

for (i=0; i < 10; i++) {
    document.writeln(someArray[i] + '<br>');
}

There are two different ways to create an Array in javascript. The first way is to use the new operator, but current best practices dictate that the new operator should not be used on javascript primitives.

var someArray = new Array(10);

However, since the new operator has a chance (very slim) to produce unexpected results, standard practice for creating an Array is to simply use square brackets.

var someArray = [];

If you have some experience with Arrays in other programming languages like C or C++, you may be wondering how to define the size of the Array. In javascript it is not necessary because the size will be automatically increased as needed.

Javascript Arrays can be initialized with data or you can create an empty Array and add data at a later time.

var someArray = [ 1, 2, 3 ];

var anotherArray = [];
anotherArray[0] = 1;
anotherArray[1] = 2;
anotherArray[2] = 3; 

You can skip indexes when populating the array and the value of the skipped indexes will be ‘undefined’

var someArray = [];
someArray[0] = 1;
someArray[1] = 2;
someArray[3] = 3;
document.writeln(someArray[2]);     // prints 'undefined' 

Arrays in other languages can be rigid about the type of data that is stored. Typically all of the data stored in the Array would need to be of the same type. This is not the case in javascript where you can store any type of data in the same Array. This means that you can add strings, functions, objects, booleans, or even additional Array’s to a single Array.

var someArray = [];
var someArray[0] = 1;
var someArray[1] = 'yojimbo';
var someArray[2] = {'firstName': 'John', 'lastName':'Doe'};
document.writeln(someArray[2].firstName); // prints 'John' 

An important characteristic of javascript Arrays to understand is that they are passed by reference to functions. This means that anything that you do inside of the function will alter the original Array.

var someArray = [0, 1,2];

function updateArray(passedArray) {
    passedArray[0] = 3;
} 

updateArray(someArray);
document.writeln(someArray[0]);    // prints '3'

Similarly, javascript Arrays are assigned by reference. This means that if you create an Array by assigning it to an existing Array, anything that you do with the second variable will alter the original Array.

var someArray = [0,1,2];
var anotherArray = someArray;

anotherArray[0] = 3;
document.writeln(someArray[0]);    // prints '3'
Advertisement
Tags:
July 24, 2012

Introduction to data structures and algorithms in javascript: Associative Arrays

This is the first of a series of posts that will provide a beginner level introduction to data structures and algorithms in javascript.

A fundamental data structure in javascript is the Associative Array. An Associative Array is an abstract data type that is composed of a collection of key, value pairs such that each key exist only once in the collection.

The reason that an Associative Array is considered to be a fundamental data structure in javascript is that every object in the language is in fact an Associative Array.

Consider the following example:

var someArray = new Object();
someArray["A"] = 0;
someArray["B"] = 1;
someArray["C"] = 2;

You can get the values stored in the array by referencing the indexes or by object qualified naming:

alert(someArray["C"]);  // value by index
alert(someArray.C); // value by object qualified naming

An Associative Array can also be created using object literal notation:

var someArray = {A:0,  B:1, C:2};

Doing so creates the exact same array as the earlier example.

An important characteristic of the Associative Array in javascript is the fact that it is an object. In other languages, creation of an array requires that you explicitly define the data type. Any addition to the array that is of a different data type would result in an error. In javascript, the array object is defined by its members.

For example, you can add a method to an associative array:

var someArray = {A:0,  B:1, C:2}
someArray.Count = function() {
    return 3;
}

This is an important concept for beginners to understand because it may lead to some unexpected behavior. For example, looping through the array will show that there are four elements rather than three.

for(ind in someArray) {
    alert(ind);
}

This problem is typically solved in javascript by creating your own collection object.

var Collection = function() {
    this.count = 0;
    this.collection = {};
}

This defines a property for the count and an empty array. To make the collection object useful, it needs methods for adding and deleting elements from the collection array. These methods will update the count property.

this.add = function(key, item) {
    this.collection[key] = item;
    this.count  +=  1;
}
this.remove = function(key, item) {
    this.collection[key] = item;
    this.count  -=  1;
}

The collection object can now be used in the following manner:

var someCollection = new Collection();
someCollection.add("A", 0);
someCollection.add("B", 1);
someCollection.add("C", 2);
alert(someCollection.count);
alert(someCollection.collection["A"];
someCollection.remove("C");
Tags:
July 9, 2012

List recent WordPress Blog Posts with javascript

Last week we discussed listing recent blog posts in ASP.NET MVC using the SyndicationFeed class. One thing that I do not like about that solution is that it is server side, so this week we will look at getting the same functionality client side using javascript.

After searching a bit for existing solutions, I found that the Google Feed API is ideal for the task. It’s extremely simple to implement and provides the expected functionality.

The first step is to add the api to your page.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"> </script>

Note that jQuery is not required for the api, but it will be used later in this document.

Next, load the Feed API with the google.load method.

<script type="text/javascript">
	google.load("feeds", "1")
</script>

Once the ‘feeds’ module is set up to be loaded, create a div that will act as a container for the blog post list.

<div id="feedContainer" ></div>

Lastly, with some simple javascript we can dynamically build a list of the feed items.

<script type="text/javascript">
	var feedUrl = "https://blog.yojimbocorp.com/feed/";
	var feedContainer=document.getElementById("feedContainer");
	
	$(document).ready(function() {
		var feed = new google.feeds.Feed(feedUrl);
		feed.setNumEntries(10);
		feed.load( function(result) {
			list = "<ul>";
			if (!result.error){
				var posts=result.feed.entries;
				for (var i = 0; i < posts.length; i++) { 
					list+="<li><a href='" + posts[i].link + "'target=_blank'" + "'>" + posts[i].title + "</a></li>";
				}
				list+="</ul>";
				feedContainer.innerHTML = list;
			}
			else {
				feedContainer.innerHTML = "Unable to fetch feed from " + feedUrl;
			}					
		});
	});
</script>

Once complete, your page should look similar to the following.

<!DOCTYPE HTML>
<html>
	<head>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
	<script type="text/javascript" src="http://www.google.com/jsapi"> </script>
	<script type="text/javascript">
		google.load("feeds", "1")
	</script>
	</head>
	<body>
		<div id="feedContainer" ></div>
		<script type="text/javascript">
			var feedUrl = "https://blog.yojimbocorp.com/feed/";
			var feedContainer=document.getElementById("feedContainer");

			$(document).ready(function() {
				var feed = new google.feeds.Feed(feedUrl);
				feed.setNumEntries(10);
				feed.load( function(result) {
					list = "<ul>";
					if (!result.error){
						var posts=result.feed.entries;
						for (var i = 0; i < posts.length; i++) {
							list+="<li><a href='" + posts[i].link + "'target=_blank'" + "'>" + posts[i].title + "</a></li>";
						}
						list+="</ul>";
						feedContainer.innerHTML = list;
					}
					else {
						feedContainer.innerHTML = "Unable to fetch feed from " + feedUrl;
					}
				});
			});
		</script>
	</body>
</html>

If your page requires additional information about each post (description, author, categories, etc), be sure to look into using feed.setResultFormat and google.feeds.Feed.JSON_FORMAT.

July 2, 2012

List recent WordPress Blog Posts in ASP.NET MVC

Recently I was tasked with adding a list of recent blog posts from our WordPress site inside of an ASP.NET MVC web site. The initial strategy was going to involve fetching from the RSS feed, but after discovering the WordPress supported XML-RPC, I decided to explore that route first.

Using XML-RPC was supposed to be easy considering there is an available .NET library for it created by Charles Cook. The task should have been further simplified because there are several C# WordPress wrappers available.

After spending time with a couple of the WordPress wrappers available, it quickly became clear that the process of updating the wrappers to comply with the latest version of WordPress would be far more work than it was worth; especially considering the scope of this task.

So it was back to the original strategy of creating an RSS reader specifically for WordPress. After digging around a bit, I thankfully stumbled across the Syndication Feed class that is available in .Net 4.0 and above.

The Syndication Feed class basically provides the quick and easy solution that I was looking for while exploring the XML-RPC route. It really turned out to be a lot easier than I thought it could ever be.

So let’s get started. For this, I will assume that you are using an existing MVC application.

The first step is to add a reference to System.ServiceModel to your project as this is where the Syndication Feed class resides.

The second step is to create a View Model that will define a List of SyndicationItem’s:

using System.Collections.Generic;
using System.ServiceModel.Syndication;

namespace MvcApplication1.Models
{
    public class FeedViewModel
    {
        public FeedViewModel()
        {
            Posts = new List<SyndicationItem>();
        }

        public List<SyndicationItem> Posts { get; set; } 
    }
}

And in the Controller, we will need to populate the list:

using System.Linq;
using System.Web.Mvc;
using System.ServiceModel.Syndication;
using System.Xml;
using MvcApplication1.Models;

namespace MvcApplication1.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var model = new FeedViewModel();

            using (var reader = XmlReader.Create("https://blog.yojimbocorp.com/feed/"))
            {
                var feed = SyndicationFeed.Load(reader);
                foreach (var post in feed.Items.Take(10))
                {
                    model.Posts.Add(post);
                }
            }

            return View(model);
        }
    }
}

You will of course want to customize the reader URL to be your own and most likely will want to create a configuration entry for it.

And finally, display the data in your view:

@model MvcApplication1.Models.FeedViewModel
           
@foreach (var post in Model.Posts)
{
    <td><a href="@post.Id" target="_blank">@Html.DisplayFor(model => post.Title.Text)</a></td>
    <br />
    
}

I highly recommend reviewing the SyndicationItem documentation when creating your view.