Joel asked: Can your language do this?

And he gave this example to illustrate his point:

function Cook( i1, i2, f )
{
    alert("get the " + i1);
    f(i1);
    f(i2);
}

Cook( "lobster",
    "water",
    function(x) { alert("put " + x + " in pot"); } );
Cook( "chicken",
    "coconut",
    function(x) { alert("boom boom the " + x); } );

Which outputs something like:

get the lobster
put lobster in pot
put water in pot

get the chicken
boom boom chicken
boom boom coconut.

Simple, yeh?

Now how would you go about doing this in C#?

I can't find a way to do it without defining a delegate first. Albeit, a generic delegate... but it's still not quite as 'elegant'.



private delegate void D<T>(T x);


Set up your cook function -- almost the same (except we use generic types, to mimic javascript's non-static typing.


private void Cook<T1>(T1 i1, T1 i2, D<T1>  f)

{

    MessageBox.Show("get the " + i1);

    f(i1);

    f(i2);

}


And then rather than passing in anonymous functions, we can pass in anonymous delegates...


Cook("lobster",

   "water",

   delegate(string x) { MessageBox.Show("put " + x + " in pot"); });

 

Cook("chicken",

    "coconut",

    delegate(string x) { MessageBox.Show("boom boom the " + x); });


Your turn. ;-)

 

Babysteps in WATIR

That nutty kid Scott Hanselman is always talking about technologies I don't understand.

In the last year or so he's mentioned 'Watir' (pronounced 'Water') a bunch of times, and I've mostly ignored it.

His most recent mention of Watir gave some fairly easy steps for getting started with it. So I did.

This post is shamelessly inspired by his post. I'm going to walk quickly, but thoroughly over the first few steps of using Watir.

So here's the 3 minute guide to watir (includes a cheatsheet).

[yeh, it continues...]

What is it?

Watir is a tool you can use to automate internet explorer. It's name is an acronym for:

'Web Application Testing In Ruby'.

You pronounce it 'Water'. I don't know why. But you do.

Watir can be used to:

  • test your web applications
  • screen scrape a web site
  • impress your friends
  • create a spider, bot or spamatron. (please not a spamatron).
  • automate a repetitive web-based task
  • give you a practical starting point with ruby

Watir is very easy to tinker with.

You first need to:

  1. Install Ruby (using the one click installer for windows (27 Meg, sorry!))

    [Don't have windows? Want to download something smaller? then install ruby from here.]

  2. Install Watir using the one click installer. (It's the first executable file listed on that page. Approx. 800 KB.)

    [Here's a link straight to the file: watir-1.4.1.exe.]

Installed both of those? Ruby, then Watir? Good for you!

And we're coding already!

Now open the windows shell (cmd.exe), and type 'irb' to launch the interactive ruby shell.

(if this fails, then ruby may not have updated your PATH environment variable correctly. It happened to me. it could happen to you.)

C:\>irb <-- start the interactive ruby shell, 'irb'
irb(main):001:0> require 'watir' <-- tell irb you'll be using the 'watir' library
=> true
irb(main):002:0> ie = Watir::IE.new <-- open an IE browser, in a var called 'ie'
=> #<Watir::IE:0x2bad438 @url_list=[], @typingspeed=0.08, @form=nil, @ie=#<WIN32
OLE:0x2bad3d8>, @logger=#<Watir::DefaultLogger:0x2bad378 @progname=nil, @logdev=
#<Logger::LogDevice:0x2bad318 @filename=nil, @dev=#<IO:0x27ce7d0>, @shift_size=n
il, @shift_age=nil>, @level=2, @datetime_format="%d-%b-%Y %H:%M:%S">, @error_che
ckers=[#<Proc:0x029198e8@./watir.rb:1135>], @defaultSleepTime=0.1, @activeObject
HighLightColor="yellow", @enable_spinner=false>
irb(main):003:0> ie.goto("http://google.com") <-- tell 'ie' to browse to google
=> 2.797
irb(main):004:0> ie.text_field(:name, "q").set("Yukihiro Matsumoto")

                ^^^^-- put the text 'Yukihiro Matsumoto' in the textbox named 'q'
=> true
irb(main):005:0> ie.button(:name, "btnG").click <-- click the button called 'btnG'
=> nil
irb(main):006:0>

Alternatively, you can type those commands into a file with a '.rb' extension.

(I've grouped the commands together (below) so you can copy and paste them:

require 'watir'
include Watir
ie = Watir::IE.new
ie.goto("http://google.com")
ie.text_field(:name, "q").set("Yukihiro Matsumoto")
ie.button(:name, "btnG").click

Paste them into notepad and then save the file with a '.rb' extension.

Run it from the command line by typing '[filename].rb' (where, um, '[filename]' is the name you chose for the file, got it?)

You should see internet explorer open up, the text 'Yukihiro Matsumoto' typed into the search box (which will turn yellow), and then the Search button turn yellow as it is clicked -- showing you the results of the search.

Amazing stuff, and much quicker than just running the search yourself.

When you really get into it, you'll want to do a lot more with Watir than I've shown you here. But hopefully now you've got the tools to get you started.

A decent guide to using watir is provided here: watir user guide and of course, if you wish to automatically record a series of ie actions as a watir script -- use the new and improved tool from Scott Hanselman and Rutger Smit, called Watir Recorder++

One odd thing is that a lot of the cheat sheets in the ruby world are published as MS Word documents. So i've written a very short cheatsheet, just for using watir. It tells you how to reference each of the main types of controls.

Here is my cheatsheet for Watir.

 

What is JSON: the 3 minute JSON Tutorial

JSON and the GLDN FLECE

If you are anything like me (and I fear that you are) then this is your experience with JSON so far:

  1. Two months ago you'd never heard of JSON
  2. One month ago you'd heard the term but paid no attention
  3. One week ago you'd heard it mentioned a few times and started to think, right... some more crap to learn
  4. Today you woke up with an alarm bell ringing in the back of your mind that said WHAT THE BLOODY HELL IS THIS JSON THING AND WHY IS IT EVERYWHERE ALL OF A BLOODY SUDDEN!

Well I had a slow bus ride home tonight (friday is always slow) and i took a pile of "JSON" tutorials with me. So now I can gently lead you through some BabySteps in JSON.

here we go...

What does JSON stand for?

JavaScript Object Notation.

[A ridiculous name. It should be called Lightweight Ecmascript Object Notation, or 'LEON' for short. ;-)]

And what does that mean?

JSON is a syntax for passing around objects that contain name/value pairs, arrays and other objects.

Here's a tiny scrap of JSON:

{"skillz": {
	"web":[
		{"name": "html", 
		 "years": "5"
		},
		{"name": "css", 
		 "years": "3"
		}],
	"database":[
		{"name": "sql", 
		 "years": "7"
		}]
}}

You got that? So you'd recognise some JSON if you saw it now? Basically:

Squiggles, Squares, Colons and Commas

  1. Squiggly brackets act as 'containers'
  2. Square brackets holds arrays
  3. Names and values are separated by a colon.
  4. Array elements are separated by commas

Think 'Extremely Malnourishd XML'

(Or if you're as old as me, think "hierarchical '.INI' files.")

(Or if you're a smug lisp weenie, think "S-expressions", and just be smug.)

JSON is like XML because:

  1. They are both 'self-describing' meaning that values are named, and thus 'human readable'
  2. Both are hierarchical. (i.e. You can have values within values.)
  3. Both can be parsed and used by lots of programming languages
  4. Both can be passed around using AJAX (i.e. httpWebRequest)

JSON is UNlike XML because:

  1. XML uses angle brackets, with a tag name at the start and end of an element: JSON uses squiggly brackets with the name only at the beginning of the element.
  2. JSON is less verbose so it's definitely quicker for humans to write, and probably quicker for us to read.
  3. JSON can be parsed trivially using the eval() procedure in JavaScript
  4. JSON includes arrays {where each element doesn't have a name of its own}
  5. In XML you can use any name you want for an element, in JSON you can't use reserved words from javascript

But Why? What's good about it?

When you're writing ajax stuff, if you use JSON, then you avoid hand-writing xml. This is quicker.

Again, when you're writing ajax stuff, which looks easier? the XML approach or the JSON approach:

The XML approach:

  1. bring back an XML document
  2. loop through it, extracting values from it
  3. do something with those values, etc,

versus

The JSON approach:

  1. bring back a JSON string.
  2. 'eval' the JSON

So this is Object-Oriented huh?

Nah, not strictly.

JSON is about as object oriented as VB6. It provides a nice encapsulation technique, that you can use for separating values and functions out, but it doesn't provide anything inheritence, polymorphism, interfaces, or OO goodness like that.

It is certainly a step in the right direction though, making javascript easier to maintain, share and reuse.

Thomas Frank wrote a nifty little javascript library called classyJSON for adding inheritance and scoping capabilities to JSON code.

And it's just for the client-side right?

Yes and no. On the server-side you can easily serialize/deserialize your objects to/from JSON. For .net programmers you can use libraries like Json.net to do this automatically for you (using reflection i assume), or you can generate your own custom code to perform it even faster on a case by case basis.

Three minutes is nearly up....

As near as a I can tell, JSON was invented by a guy called Douglas Crockford. Read his website if you want, he's pretty funny.

Now Go And Read Someone Who Knows

(Retrieved from Delicious using JSON!)

That's all.

I've only tinkered with this stuff for a few minutes -- so I've probably said some completely wrong things. If so, please leave a comment, telling me what an idiot i am. I'll be happy to correct any specific mistakes. Best of luck!

(Side note: If you replace { and } with "<" and "/>", and you replace ":" with "/"... you'd have something very similar to gaXml. Funny old world.)

(Other side note: Jason and Ajax were both mythical greek heroes. Prediction: other forthcoming technology jargon will include: Heracles, Perseus, Deucalion, Theseus and Bellerophon.)

(To generate JSON, use a data manipulation tool like NimbleText)

 

Why You Need a Domestic Robot

You need a robot for picking things up and putting them down.

When purchasing an item from a grocery store, for example, you pick it up and put it down seven times (code sample below).

This is ridiculous!

[continues with code examples]

The Grocery Algorithm

to the tune of... <pick your own tune>
drive to grocery store get trolley enter store for each item on the list: find it pick it up put it in the trolly. find the checkout line that looks shortest (note: it's not the quickest) while people are in front of you: do nothing. for each item in the trolley: pick it up put it on the conveyor belt. [Now we'll switch over to look at the cashier program] greet customer. for each item on the conveyor belt pick it up scan it no bag on bag holder? pick up an empty bag put it on the bag holder put the item in a bag. bag full? pick up the bag put it down the end of the counter. tell customer the price take money put it in the till give change. [switch over to look at the customer program again] for each bag on the counter: pick it up put it in the trolley push trolley to car. open boot. (i.e. 'trunk') for each bag in the trolley: pick it up put it in boot (i.e. 'trunk') push trolley out of the way. drive home open boot. do while bags left in boot: while i have the strength to carry one more bag: pick up a bag. no bags left in car? close boot (i.e. 'trunk') walk up stairs walk to kitchen counter while bag/bags in my hands: put it on kitchen counter bags left in car? so walk downstairs for each bag on the kitchen counter while items remain in bag pick up item put item away

Okay -- this continual picking up and putting down stuff just seems so ridiculous. And it's not out of laziness that i hate it -- activity doesn't frighten me. I like exercise and all that freaky stuff. But i don't like being programmed by my needs.

I read somewhere that while everyone wants a domestic home robot, we tend to value it at around 20 bucks each. But the upfront cost of development would run into the tens of millions. Personally, I think i'd chip in about fifty dollars if a robot could do the grocery shopping for me, forever. Without complaining or needing servicing.

All it's got to perfect is the art of picking things up. And putting them away. Is that too much to ask?

 

3 Examples from the Future of CSS

More html news from Gaks[1]...

Following on from the W3C announcement of a 'Tags' attribute, I'll show you how this tags information can be utilized using CSS 2.0, today, and CSS 3.1, in the future.

First, a simple example, using just plain old CSS 2.0 attribute selectors, available today in firefox.

Consider the following chunk of style information:

<STYLE type="text/css">
p[tags] { background : lightgreen }
</STYLE>

It basically says "All p elements that have a Tags attribute should be shown in green." (You can use this today in firefox.)

[continues with code examples]

Hence the following html:

<p tags='example text css2 tutorial'>an example paragraph</a>

will render like this:

an example paragraph

Another example

This is also available in CSS2, and can be used today in firefox. [I've uninstalled IE7 and can't test it here]. The following style information:

<STYLE type="text/css">
a[tags~='warning'] { background : red }
</STYLE>

Basically says "all a elements with a 'tags' attribute containing the value 'warning' should have red background."

The little squiggle before the equals sign (i.e. "~=") is because tags could hold a lot of different space-delimited values: and we only need one of them to match. We don't need the entire attribute value to match.

If we apply the above style to the following snippet of html:

<a href='linksomewhere' tags='warning'>don't follow this link</a>

will render like this:

don't follow this link

Basically, the rule is applied to the anchor element, because the value of its tag matched.

You can do some pretty cool things with this. If your browser supports it.

[All elements with an 'rss' or 'atom' tag could have a cute little feed icon beside them. Those with a 'microsoft' tag could have that oh so amusing "bill gates as locutus of borg" icon from slashdot circa 2001. And so on.]

Back to the future: A third example

Now, using the "attribute value" selector from CSS 3.1:

<STYLE type="text/css">
a[Tags]@ { display: inline; padding: 10 }
</STYLE>

The following html

<a href='linksomewhere' tags='warning'>don't follow this link</a>

will render like this:

warningdon't follow this link

which is semantically equivalent to injecting a span element at the front of the link, like this:

<a href='linksomewhere'><span style='padding: 10'>warning</span>don't follow this link</a>

The "@" in the above selector means, 'select the value of the attribute itself (rather than selecting the element it belongs to)'

So if we want to reveal the href of every link we can say:

<STYLE type="text/css">
a[href]@ { display: inline; padding: 10 }
</STYLE>

And thus a link to google, written like this:

<a href='http://www.google.com'>googleLink</a>

Would display like this:

http://www.google.comgoogleLink

[Okay -- I couldn't convince Gaks to forward me any further details of the CSS 3.1 spec, so you'll have to hassle Hixie, Tantek or Glaz directly if you want to know the future. Too bad ;-<]

 

W3C to Support 'Web 2.0' concept of 'tags'

Strange news from my strange friend Gaks[1].

He's forwarded me a fragment of the w3c's proposed new attribute: 'tags' which is defined for almost every html element.

A 'tags' attribute acts as a flexible meta-data repository, and here's how you use it:

Say you want to link to a document, and you want to 'tag' that document as being 'funny', 'rude', 'useful' and pertaining to a few key topics such as 'html', 'xml' and 'css' (and why shouldn't it?) then your anchor element could include a 'tags' attribute like this:

<a href='https://secretgeek.net/gaxml.asp' tags='funny rude useful html xml css'>What does XML look like on other planets?</a>

Gaks tells me that this is particularly useful when used in conjunction with the whatg's Web Forms 3.0 specification of a tagCloud control. I have yet to find out how one of those works.

Gaks further says that the best new attribute in html is 'time', defined for anchor elements, which lets you specify not just where a link points, but when. Relative-time values can be used for fetching tomorrow's newspaper headlines today, and so on, which causes hell for rss aggregators etc.

[You might need to know that Gaksloope ('Gaks') is a subterranean coding cult-hero from an alternative-reality cubicle fourteen minutes into the future].

 

<Strike>G-MAIL is dead!</Strike>

gmail is dead... google mail emerges

[Update: i was wrong. it seems that rumours of gmail's departure are misplaced. this may have been some exotic gmail server handling my mail today.]

it seems that the marketing gods at google have spoken. Gmail is no longer 'Gmail'

The logo in the top left now says 'Google Mail' instead.

I'm sure there's a lesson in there somewhere, about marketing and brand-identification and other stuff. But I just don't think it looks as nice as the gmail logo.

 

Web 2.0: Something's Missing

To some (small) extent, you can think of web 2.0 as the sudden realization that:

'hey! with Ajax we can build the entire Office suite online!'

There's lots of contenders to replace and extend many apps/features of the Office Suite:

  • Word -- writely and a hundred others...
  • Outlook -- gmail and a hundred others...
  • Excel -- numsum and a hundred others...
  • Calendars -- kiko and a million others...
  • Powerpoint -- s5 and a few others...
  • IM -- meebo and a few others...
  • One-note -- webnote and millions more...
  • even Visio! -- gliffy and probably some others...

But there's one glaring ommission. One of the most influential parts of Office seems to have evaded web 2.0 completely. (and no, I don't mean clippy)

(continues...)

What's missing is the modern-day internet-native replacement for...

MS Access!

Yes, that's right. Scourge of the development world that is, there's no denying that MS Access (and its contempories like FileMaker Pro) provided an incredible ability for non-experts to instantly turn their business cases into working applications.

Here's a simple definition of Access, that we can use to try and envisage a Web 2.0 replacement for it:

Access is a self-contained two-tier application (forms and database) that lets non-developers quickly build and deploy their own self-contained two-tier applications.

So I think a Web 2.0 version of access would be:

[Access for Web 2.0] would be a self-contained web-application (web-forms and database) that lets non-developers quickly build and deploy their own self-contained two-tier web-applications.

Your thinking game for today:

envisage a self-contained web application (web-forms and database) that lets non-developers quickly build and deploy their own self-contained two-tier web-applications

Limitations to be overcome:

To help with your ideas, maybe it should overcome the following limitations of Access:

  • Low tolerance for simultaneous users
  • Database can be suddenly corrupted
  • Difficulty of integrating source/version control
  • Inability to script the creation of access db's through DDL
  • End users eventually learn to recognise an Access application and they seize up and start crying rather than touching it. As do developers.
 

Babysteps in PowerShell part deux: Variables! Real Proper Variables!

Alright, I've been tinkering with PowerShell for a few evenings now, and the latest thing I've started to unravel is how variables work.

Variables are prefixed with a dollar sign. [This is probably an idea they got from the world's simplest code generator ;-) ].

And they seems to use implicit typing [aka 'Duck Typing']

Now watch as we get the basics sorted out, and prepare to move on to trickier things...

(continues...)

First we'll declare the variable 'Oswald', by assigning something to it:

PS C:\> $Oswald = "explorer"
OK let's see if that worked...
PS C:\> echo $Oswald  <-- echo is an alias for 'Write-Output'... 'print' is another alias for it
explorer   <-- Oswald's value is 'explorer'. Nice
Okay, now let's check what type of variable we've got:
PS C:\> $Oswald.gettype()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object

Okay, now let's use the variable as a parameter:
PS C:\> get-process $Oswald

Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
-------  ------    -----      ----- -----   ------     -- -----------
    375      12    17584      26304    90    21.91   3068 explorer
		

Okay. Groovy stuff. But there's more to come...

Now for the Wicked Stuff!

Once Upon A PowerShell i went looking for a cmdLet to display a list of all the current drives.

I found one, 'Get-PSDrive' which does exactly that... but i was gobsmacked at what else it revealed!

'Power shell drives' are not just your boring old 'C:' etc -- they can be all sorts of hierarchical structures, such a registry keys, environment variables, functions(!) and more.

(I bet you can create your own powershell drives. [yep 'New-PSDrive', aka 'mount'] Now imagine one for navigating a relational database... hey there's a fun and magical challenge!)

PS C:\> cd Variable:  <-- 'cd' is an alias for 'Set-Location'
The way cool thing is that 'Variable' is a power shell drive, that 
shows you all the variables you have access to. A bit like exploring the 'locals' window 
while debugging in visual studio. Only they're not just local.

Let's look for all variables starting with 'O'... 
PS Variable:\> dir o* <-- 'dir' is an alias for 'Get-ChildItem'... 
                          ('ls' also does the trick)

Name                           Value
----                           -----
Oswald                         explorer <-- Here's Oswald!

PS Variable:\>

And there ends my learnings for tonight.

I'm thinkin powerSHELL is more like powerSHEAVEN!

(ah... power-puns.)

 

syntax, lang = 'sweet', 'ruby'

check this syntactical sugar from ruby:

@title, @mood, @fulltext = title, mood, fulltext

(Example from _why's amazing online Ruby tutorial: 'Try Ruby in your browser')

Love it!

any chance that 'multiple assignments' can be added to C#? How about VB.Net.Next, hey paul?

Here's an explanation of the above syntax, taken from the Ruby spec:

" Multiple assignment form performs multiple assignment from expressions or an array. Each left hand side expression must be assignable. If single right hand side expression given, the value of the expression converted into an array, then each element in array assigned one by one to the left hand side expressions. If number of elements in the array is greater than left hand sides, they are just ignored. If left hand sides are longer than the array, nil will be added to the locations."