Saturday, January 10, 2009

Using Custom Fields to create a dynamic sidebar

WordPress has the ability to allow post authors to assign custom fields to a post. This arbitrary extra information is known as meta-data. This meta-data can include bits of information such as:

  • Mood: Happy
  • Currently Reading: Cinderella
  • Listening To: Rock Around the Clock
  • Weather: Hot and humid

With some extra coding, it is possible to achieve more complex actions, such as using the metadata to store an expiration date for a post.

Meta-data is handled with key/value pairs. The key is the name of the meta-data element. The value is the information that will appear in the meta-data list on each individual post that the information is associated with.

Getting Custom Fields

To fetch meta values use the get_post_meta() function:

 get_post_meta($post_id, $key, $single);<br />
  • $post_id is the ID of the post you want the meta values for. Use $post->ID to get a post's ID.
  • $key is a string containing the name of the meta value you want.
  • $single can either be true or false. If set to true then the function will return a single result, as a string. If false, or not set, then the function returns an array of the custom fields.

Highly Customized Sidebar using Custom Fields and Categories Per-Post


I've used WordPress for a few years now, but currently I am in need of help of building custom sidebars on a per-post basis using information stored in custom fields and categories. I'm a web designer by trade, not a programmer, and have some experience with PHP but not enough to do what I need.

Setup
I'm currently designing a website that uses WordPress as a CMS and will be used by location scouts for potential movie and commercial shooting locations. Posts act in two ways: 1. as News (much like a blog) and 2. as an individual location.

Each individual location is categorized using the WordPress category system, however there are over 75 categories including children. Some locations may have up to 3 different categories. On top of that, each location also has a series of custom fields.

Intention
When an individual location is being viewed, the purpose of the sidebar is to feature two sets of 3+ locations: 1. via a category based on the posts categories and 2. locations nearby using a custom field stored in the post.

Since some posts may have up to 3 categories in all, I don't know how to narrow down the category to just one. For instance, the post may have the main category of House with children of Historic & Period 1950s. All I would want is to pull the House category when someone is viewing a home location and list other locations categorized under Houses in the sidebar.

The same is for the Custom Fields application. Here the intention is to pull the zoning area for the location and list other locations in the same zone.

So if I'm looking at a post for a particular location that is categorized under Gas Station and is located in Zone 1, I should see in the sidebar at least 3 other gas stations and 3 different locations in the zone 1.

Since each post is unique concerning a location, the sidebar must spit out specific information. I've tried to figure out the code, but can't make anything work correctly.

Try something like:

<?php $thumb = get_post_meta($post->ID, "post_thumb", true); if (!empty($thumb)) { ?><img class="alignright size-thumbnail" src="<? echo $thumb;?>" width="120" alt="Thumbnail image for '<?php the_title();?>'" /><? } ?>

Another way to handle this issue

I recently finished the redesign of my blog, The Humanaught, and as these things tend to - it came with a few forehead slapping mind scratchers.

The key one being that the design utilized the post’s footer to store comments. On many posts you wouldn’t even know there was a problem, however when I - on occasion - veer from my usual rambling and only write a tiny little blurb, the issue is evident.

Take, for example, a standard page layout. On one side (in my case, the left) you have your content, on the other you have your sidebar, and hanging out at the bottom you’ve your footer (fig. 1). If your content and your sidebar have a roughly equal amount of doodats in them, you’re golden - but when you short change your comment box, your sidebar extends its full length and makes everything look goofy

Digging into my WordPress template, I needed a dynamic way of determining the size of the content box. For this I threw the following code just above The Loop of my single.php and page.php pages.

<?php
$post = get_post(the_ID(), ARRAY_A);
$contlen = strlen($post[‘post_content’]);
?>

I come out of that with a variable ($contlen) that gives me the character count of my content. Now all I needed to do was pass that variable to my sidebar and use some conditionals (IF bla bla bla) to decide what should be displayed and what should be cut.

The problem with the standard WordPress template is that the <?php get_sidebar(); ?> that WordPress uses by default to load all the goodies in sidebar.php doesn’t pass variables defined in other areas of the template.

To fix this we change:

<?php get_sidebar(); ?>

to

<?php include (TEMPLATEPATH . ‘/sidebar.php’); ?>

Now any variables you set in single.php/page.php will carry over to sidebar.php.

Next up, we need to attribute some values to that prioritized list we made a bit earlier. We need to decide after what character count certain sidebar elements will be displayed. As this is all very much a “give or take” solution, figures will vary depending on things like font-size, the size of elements in the sidebar, etc. However, let’s use my numbers for the sake of … well… just because.

  • All - Search Box, Recent Posts
  • >1,000 - Badges
  • >3,500 - Recent Comments
  • >5,000 - Blogroll

To implement this, we just wrap the sidebar elements in IF statements:

<?php if (is_home() || $contlen > 3500) { ?>
<h2>Recent Comments</h2>
<ul>
<?php get_recent_comments(); ?>
</ul>
<?php } ?>

The IF statement simply says if it is the home/index.php (is_home()) or (||) our content’s length ($contlen) is greater than 3500, display this crap - otherwise, move along.

That about does it, but for the sake of re-illustration, here’s the conditional to display the blogroll:

<?php if (is_home() || $contlen > 5000) { ?>
<h2>Blogroll</h2>
<ul>
<?php wp_list_bookmarks(); ?>
</ul>
<?php } ?>

What this doesn’t take into account are pages that display things like search results, particularly if those results are few to none. But with some simple modifications, I’m sure you can adjust this method to suit your blog’s particular needs.

Technorati Tags: , , , , ,

Thursday, January 8, 2009

How to Unlock a File in Team Foundation Server

We've all been in the
situation before when a developer goes away for a long weekend (usually
leaving on Thursday) and they forget to check in a file and ensure the
solution builds. Here is how to deal with that in TFS. Unlock the
file according to the instructions found here:


http://blogs.msdn.com/rimuri/archive/2006/03/06/544686.aspx


The gist is that running this command will unlock the file:


tf undo /workspace:TheirWorkspace;DOMAIN\TheirUserAccount $/path/to/file


To get a list of workspaces run this:


tf workspaces /owner:DOMAIN\TheirUserAccount /computer:*

Another way to do this:

One of the rare but critical tasks of Configuration Management is
the unlocking of items locked or checked out by someone else, like an
ex-employee or a developer in the Bahamas while an emergency patch
needs to be pushed out.


Unfortunately, the unlock action is not available in the
context-menu or a GUI but needs to be executed from a command line. I
wonder why it’s not in the GUI, granted deleted files and pending
changes will not necessarily be visible in the GUI but at least the
Undo should be available for visible items while the command line still
provides the all-encompassing functionality.


The help was not very clear, so I’ll simplify the command for you.


There are 2 possible options for unlocking, viz. unlock or undo (if checked out for Edit).

The respective command to use is tf lock /lock:none or tf undo


The parameters in both cases are the same:


filename (in the help topic, this is the itemspec parameter)

This is the file you want to unlock


/workspace: [user's workspace]:[user name]

The user’s workspace needs to be figured out…by right-clicking the locked item and selecting Properties… and then the Status tab

The user name is the fully qualified user name, in the form: domain/user


/s:[server path]

This is the TFS server in question. Typically it’s http://servername:8080/


So, a sample command would be something like:

tf undo $/Applications/Dev/Branch1/file1.aspx /workspace:”Ra Dev Notebook”;corp1\ra /s:http://altair:8080


(You run this is on a VS client, at the Visual Studio command prompt)


PS: Hope the color coding helped


Another command I found useful during the process was tf status /user:Joe /s:server path, which essentially lists all files locked by Joe. I piped it to a text file (with >> C:\joe.locked.txt) to get a report.


A User-Friendly C# Descriptive Statistic Class

Today I found and used this class, I highly recommend it for simple statistics calculations required for many reporting systems.

http://www.codeproject.com/KB/recipes/DescriptiveStatisticClass.aspx


The author says:

"The 80-20 rules applies: even with the advances of statistics, most of our work requires only univariate descriptive statistics – those involve the calculations of mean, standard deviation, range, skewness, kurtosis, percentile, quartiles, etc. This article describes a simple way to construct a set of classes to implement descriptive statistics in C#. The emphasis is on the ease of use at the users' end."

It has great reviews and ratings.

Tuesday, June 19, 2007

Digg wins news industry sites comparison

During the last 3 years there has been an enourmous shift in the news industry from classic news sites such as CNN.com and BBC.co.uk to web2.0 news site made of User generated content, such as Digg, Delicious and StumbleUpon. I checked these 5 sites on alexa to see how they do head to head.


first I looked at the 1 year graph. Everyone seem very stable, with CNN and BBC leading, Digg takes the middle, followed by Delicious and StumbleUpon. The weekend effect is apparent at 3 of the sites.


when I looked at the 3 Year graph, i could easily see that CNN and BBC where at approximatly the same ranking, where as the web2.0 sites were nowhere in site 3 years ago. After 2 years of rising sharply Digg and Delicious (strangly matching all the way) leveled around 100, 150. Another thing is that CNN and BBC started declining 2 years ago, and they keep going slowly but steadily. It so happened that Digg and CNN has very similar rank, as one takes the others place.

I expect great things for digg, and I think they will lead the revolution of web2.0 many years to come.

CNN is dead, Long live Digg ;-)

Benny.

Monday, June 18, 2007

Designing Business Objects for web2.0 Applications

When we sit down at the beginning of the process to design our brand new shiny web2.0 application (Please, not another social network...) we should consider several issues regarding Object Oriented design in general, as well as web2.0 application specifically.

Find your objects
This is true for every program. First thing to do is read the product specification (if working in medium or large company) or just describe the system in words. Notice the objects in your sentences as candidates for being objects in the system. For each one ask yourself: "Does it contain any information i should use?" This Information is the object properties. "What actions can this object perform?" leads to a list of methods. Objects on the list that have no properties or methods should not be objects in the system.

Remember the Channels
When selecting parameters for the methods and types for the properties remember who is on the other side. Is that a web page calling? A web service? Some Embedded code from this blog?
What are they asking for? What language do they speak?
You may consider writing a Data Access Layer that speaks SQL with the database and sends DataSet objects to the Business Objects. The business objects receive requests from Server-Side code that runs inside a web server. Those requests use a certain textual format to pass data to the server. Simple applications may send single values over Query Strings, but any real application should use JSON or XML as a data protocol with the web client. On this web client you may like to have some cool AJAX controls to smooth the User Experience, So you will need a set of Client-Side objects, written usually in Javascript.

Design Serializable Objects
If you are using JSON or XML you should design your objects to be serializeable. That means using only string, int, bool, object and array as the types of your properties. Any JSON Serializer can read such objects and this saves you iterating through all the object properties to read it's values. You just write something like MyJSONString = Serializer.Serialize(MyObject) and Bam! you got yourself a JSON string to send back to the browser.

Match Server and Client Objects
Since we have two sets of objects, one on the server and one on the client, we should match their properties to allow for smooth data transfer. There are JSON and XML serializers in javascript too, of course. You can avoid this problem all together by using a Library planned for this purpose like the Microsoft Ajax Extensions 1.0. Take a look but be careful, this package is only for professionals. It requires the best understanding of Internet technologies and much patience for Microsoft heavy object models.

Plan Great Utilities
Well, What do we do with all this? We can start by writing a set of utilities that will simplify our coding and will make the application more robust. One function we should write is a generic DataSet2Object function, that reads a dataset and returns a collection of the desired objects. There may be some others, but you get the idea.

Remember to breath :)

Benny.

Wednesday, June 13, 2007

Reporting Page Url from Flash video player = Monitization

Recently the web got at least one more layer in the spaghetti of sites we are used to. Since the rising of the social networks and the User Generated Content sites everyone is providing the users with tools to embed parts of their web site in the user's blog, profile or other personalized web space. Now instead of many sites operating in solitude we now have one web page that includes information from many web sources.

A more recent development was the rich media, Images and video mainly. Most video sites now allow their users to embed their videos everywhere (except of MySpace... but that is another story that will probably have it's own post.). How can the video site owner know when someone is playing his video on some blog or profile? Remember that most of the video sites business model are commercial-based, and the commercials should run along-side with the video content, So targeting your embedded audience even just for GeoLocation can be worth a lot.

Most video players are written in flash, and the communication between Flash and web server never was that amazing. There are several things you need to do in order to have a Flash application report to a web server the Url of the page it is running inside.

First you need to use an ActionScript command called ExecuteExternalCall to call a javascript that reports the Page Url with the property document.location.href.
Set the AllowScripts attribute of the embed tag to "Always", and make sure that the hosting site allows those scripts to run. MySpace doesn't, so do try to execute any Javascript in any form on MySpace.

this will take you to a point where everything works fine in FireFox but no information received from explorer browsers. To allow this info to run through IE you need to add the Flash ClassId attribute to the embed tag, and remove the Type attribute (should be there before, with Flash/Application or something like that in it's value). At this point we got the Url from IE as well but our application stoped working.

We are still resolving this issue, and we might try sending Ajax request to the server straight from the "ExecuteExternalApplication" function, because we realized that the function call works fine, only getting the value back in ActionScript fails.

I'll update on this when we have more info, also I will appreciate any comments on how to handle such a trick.

benny.PublishPost();

Tuesday, June 5, 2007

The place of Intuition in the Development process

I'm developing software for the last 10 years, and operating computers for 20. I have watched endless programmers, team leaders, project managers and CTOs bang their heads (or do other stupid things) with anger and frustration every time they observed the non-disputable fact of life that computers don't always do what we want them to. Hell, they sometimes don't even do what they were asked to do (Which is something completely different from what we expect them to do.)

This is a universal truth and software developers can benefit the most from integrating it into our systems: Things don't always work as we expect. The difference between us is what we do with this fact.

As i see it there are mainly two ways to handle this. Some ignore reality and stick to their opinions. We can see these guys shouting and hitting their computers and some of them develop habits of "saying YES and doing NO", always being late and other behaviors that express repressed anger. On a more professional level you may notice some programmers that insist on sticking to their bugs and can spend days with them, even if they could solve them quickly. By struggling with their work they achieve much self feedback like "I'm working so hard" and "This job is so difficult, I must be so smart to be doing it".

Others accept reality and recognize the emotions that this reality stir in them. Those people will usually act according to decisions and not emotions. They also can be stressed or relaxed in their work, but they will at least do a genuine effort to make things better both professionally and inter-personally. The amount of stress that we acquire in work is directly connected to the way we recognize and process our feeling and emotions during the day of work. If we know how to harness these powerful emotions to our use we can achieve so much more then if we are fighting the emotions, working hard to keep them inside.

The development of software is a very complex task, constructed of many many little tasks that we perform and put together in order to create a complete product or feature. All this complexity it done using a very, very, very and some more complex hardware that includes billions of tiny electrical components. I wonder it actually works at all ! No wonder it has it's glitches. To me it reminds a sentence from chaos theory that states that systems become more chaotic as they become more complex. I believe that computers are so complex that they conform to this rule.

Those that accept reality looks at every bug as an opportunity to improve, to learn new things, a challenge that needs to be met, not a problem that needs to be solved. Such state of mind creates a relaxed, interesting, fruitful working environment. This is the right ground to promote creative thinking and creative solutions. With such inner position we can learn new things easily and enjoy the learning. After all, if there are no more bugs our work is done. The essence of our work is bug fixing. This is what we do. Everyone can create bugs. not all of them can solve them.

After a while working in this state of mind one starts to write less, but more efficient code. One is found more time thinking then hitting on keys, but get more work done faster. When it comes to approaching new challenges, one starts to use it's intuition. Sometimes we "just know" things. It is stupid to ask a beginner to use Intuition. He should work by the rules for a while. But after a while, the solutions start popping up like popcorn. There are many ways to do each task and choosing the right one is many times an intuitive decision. We usually don't have time to explore all the options well, and we have to choose. These decisions should be taken by an experienced person, and he will be stupid NOT to use intuition in his decisions.

Our intuition is our highest inner voice (emotions-thoughts-intuition) and only by using it can we achieve self-completion in our life and in our work.

I know, there is no code sample with this post. I think developers can still benefit from it...

yours,

Benny.