Thursday, October 30, 2008

JTemplates template file cached workaround

I've been using a lot of JQuery and JTemplates after reading a couple really helpful JQuery and MVC posts at Encosia.com. One problem I ran into while doing some development on a new .Net MVC Project that was using JQuery extensively was that my template files were being cached by my browser. I tried clearing the cache but that wasn't helping, so here's a workaround I came up with.


If you take a look at how JQuery's $.ajax(...) function handles the caching problem you can see that they append a random query string parameter to each request.




So that is what I basically did to workaround the caching problem with the template files. I created a function called cacheBust() that just returned the current times milliseconds value and used that to generate my random query string. Here's some sample code:





function cacheBust() {return new Date().getMilliseconds().toString();}

function GetTimeEntries(day) {
// Show the loady
showLoady();

$.ajax({
type: "GET",
cache: false,
url: "/TimeEntry/" + day.replace(/\//g, "-"),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// This method loads the HTML template and
// prepares the container div to accept data.
$('#TimeWrapper').setTemplateURL('/scripts/timeentry.vw?_=' + cacheBust());

// This method applies the JSON array to the
// container's template and renders it.
$('#TimeWrapper').processTemplate(msg);

// Hide the loady.
hideLoady();
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
// typically only one of textStatus or errorThrown
// will have info, I'm not using either.
hideLoady();
$('#TimeWrapper').empty();
$('#TimeWrapper').append("<p class='errord'>There was a problem loading the data from the server. Sorry I got nothing else.</p>");

}

});
}


And now we get the most up to the second versions of our templates. Once I'm done with development it will be beneficial to have the templates be cached. I figure once that happens I'll change my cacheBust() function to return a constant (something like, "ItCompilesSoShipIt").



Now Playing: Snow Patrol - Open Your Eyes

Monday, October 6, 2008

Powershell Count Files By Regex Match on Content

Being a Powershell Winter Scripting Games Top Scorer for both the 2007 and 2008 Scripting Games I have to keep my skills fresh. Never know when you need to whip out an extra dirty little script to count how many T's are in a text file.

Scripting languages always give me a dirty feeling when I get done and look at my code. I'm a fan of what Code Complete describes as the Primary Imperative of Software Engineering; Managing Complexity. Solving something with a scripting language always makes we want to write something using the least amount of characters possible. Comments, descriptive variable names and consistent formatting usually go right out the window along with the ability to come back a month later and figure out what is going on in the script, let alone try and tell a co-worker what is going on.

That being said, here is a tiny powershell script to count files based on a Regex match of their content. Don't worry, I took the time to comment it a little bit and even have some pretty descriptive variable names. It originally was just one line for the specific task I needed to get done. I was looking for the number of xml files with a specific value in a set of directories.


# Create Parameters for our script.
# TODO: Make a helpful usage reply when no parameters supplied.
Param( [String]$path="./",
[String]$filter="*.txt",
[String]$match=$(throw "Regex Pattern required."),
[switch]$searchSubs)

$reg = [regex]$match;

if ( $searchSubs )
{ # Get the files matching the passed in path/filter
dir -path $path -filter $filter -recurse
# Loop through each and look for a match of the Regex.
% {
$in = gc $_.FullName; $reg.Match($in).Groups[1].Value
} group #Group the Values.
}
else
{ dir -path $path -filter $filter
% {
$in = gc $_.FullName; $reg.Match($in).Groups[1].Value
} group
}

Here is some sample usage:

./FileMatch.ps1 -path c:\somewebsite\fileUpload -filter *.xml -match 'field value="(.*?)" name="blah' -searchSubs

You can even mix up the parameters if you want. Powershell Rocks!

Now Playing: Jason Mraz - Curbside Prophet

Tuesday, September 23, 2008

What the Buddha Taught: Meditation as Concentration and Attention to Detail

As part of the wonderfully useful (I'm not being sarcastic) major in philosophy during my college years I had the pleasure of reading a book called What the Buddha Taught by Walpola Rahula. Of course, being a philosophy major I was especially susceptible to the kind of books that stir up what some might call "Deep Thoughts", also "Navel Gazing".

Interestingly, I found out later after a course in Elementary Logic, taught by Dr. Cassandra Pinnick, that there was more to this whole philosophy thing than sensational ideas about religion and boring lectures about the business ethics of companies who are, IMHO, just trying to help factories by selling glue in Guatemala (see H.B. Fuller Glue Sniffing). I mean seriously why would it be my companies fault if some retard kid in Guatemala uses my product in an illegal and reasonably unforeseeable way.



Anyway, the point of this post is to bring a little bit of clarity to your life by way of one of the most misunderstood concepts in modern religion, Meditation (specifically the Buddhist concept of Meditation). I know what you are thinking, "There's not enough room in my cubicle to cross my legs" and besides that, "The weird guy Wesley who sits in the cubicle across the aisle doesn't even like it when I play my new Enya CD more than a whisper; there is no way he will listen to me 'Hummmm' to myself for 15 minutes while I get in the 'Zone'".

As are most actual Buddhist followers, you are probably mistaken about the definition of Meditation. Here is Meditation as described by Walpola Rahula,

"It is unfortunate that hardly any other section of the Buddha's teaching is so much misunderstood as 'meditation', both by Buddhists and non-Buddhists. The moment the word 'meditation' is mentioned, one thinks of an escape from the daily activities of life; assuming a particular posture, like a statue in some cave or cell in a monastery, in some remote place cut off from society; and musing on, or being absorbed in, some kind of mystic or mysterious thought or trance. True Buddhist 'meditation' does not mean this kind of escape at all."
Of the various acts that can involve meditation (Nearly every task can, from eating to reading to coding) the one that has been brought to my mind recently is the act of concentrating fully on a given concept to gain insight. We have a sort of open-ended question that we ask during interviews, "Tell me everything you can about what happens from the time a user enters an address in a web browser to the time the page is displayed."

To me, this is an excellent concept to Meditate on. You see Meditation is really better described as 'Mental Development'; and all exercises/disciplines that cultivate that 'Mental Development' are forms of Meditation. I'm sure you have certain situations where you are forced to sit around with nothing to do; maybe you have a long ride to work in the morning, a weekly 3 hour conference call where you only participate for 5 minutes (right in the middle) or a monthly company meeting where they talk about keeping the damn kitchen counters clean for an hour (I mean seriously, we got it, keep the counters clean, check that one off the list, lets move on for the love of....). Why not try and think deeply about some concept related to your work during that time.

As programmers, we're lucky. There are abstractions all around us that we never really think deeply about. I know I can spend at least 30 minutes thinking about what is really happening when you join two strings together in a simple C# statement like;



var blah = "Miss Piggy loves " + "Kermit";


(Pseudo)Dynamic-typing, operator overloading, memory allocation, character pointers, null terminated strings, character encoding, registers and ALU's have been neatly and nicely stowed away so as to not require too much mental heavy lifting. Don't get me wrong, it makes us extremely productive (Think about having to know internal combustion engines inside and out just to be able to drive to work, not productive).

I think you'll find that concentrating on something specific with as much detail as possible, like the two strings or the HTTP request/response life cycle, will give you a sort of 'enlightenment' when it comes to how you write code, drive to work, cook a meal or even shave your face.

Now Playing: Jimmy Eat World - Futures