Wednesday, January 31, 2007

Another reason I dislike Microsoft

http://ajax.asp.net

Hooray, welcome to the Ajax world ASP.NET. It's been around long enough, someone bright in Redmond actually started the movement back in the mid 90's. But, Microsoft, could you not kill the term by branding your Ajax components as AjaxThisOrThat when it's really just a wrapper for DHTML functionality? It appears to me that you're trying to capitalize on the current wave by simply naming DHTML controls as Ajaxed controls. Which is simply wrong. Then again, I suppose that's no surprise considering your failed attempt at changing the meanings of things anyway.

Sadly, for the ASP.NET developers who may be new to it, they'll now be dumbed down (once again?) to the real concepts and essentials of what Ajax _really_ is and how/why it works.

Oh, and nice job on making it only work with web services and kudos to making configuration a breeze.

Monday, January 29, 2007

Quote model, has_many and a couple hours of grief

I have two models, Quote and QuoteLineItem using the has_many and belongs_to respectively. I was having issues with AR dumping out insert statements like

INSERT INTO quote_line_items (`created_on`, `quote_id`, `price`, `modified_on`, `product_id`, `quantity`, `modified_by_person_id`) VALUES(#<Quote:0x36551f0>,
#<Quote:0x364dba8>, #<Quote:0x3645728>, #<Quote:0x363efa4>, #<Quote:0x362ef3c>, #<Quote:0x3636728>, #<Quote:0x3624618>))


This drove me nuts so I jumped into rdebug to figure out the issue. Turns out there is an ActiveRecord method name collision when using

belongs_to :quote


so you have to provide an alternative, something like

belongs_to :related_quote, :class_name => "Quote"


Wish I knew that when I was creating this migration....

UPDATE:
http://dev.rubyonrails.org/ticket/4248

Tuesday, January 23, 2007

Spotlight and indexed content

UPDATE: Check it out: http://www.arcadianvisions.com/downloads/RubyImporter.html

Became apparent to me today as I was searching for some files that Spotlight only indexes content for files based on their extension (and plugin, if installed). I was able to confirm this with the following code:

echo "hello you hoser" > something.java
mdls something.java

There's a bunch of data there associated specifically to the .java extension. Find that file based on its contents:

mdfind "you hoser" |grep java

Aha, there's the file.
Trying this again with, say, a .rb extension:

echo "take off you nob" > somethingelse.rb
mdfind "take off you" | grep something

No results. mdls shows that there are some attributes associated with the .rb extension, but somehow the content isn't indexed.

XCode provides a project template called "Metadata Importer" so you can write your own to deal with custom extensions. Apple's doc explains the process.

Friday, January 12, 2007

quicksilver shortcut for locking the screen in OSX

I copied the ScreenSaverEngine.app from System/Library/Frameworks/Screensaver.framework/Versions/A/Resources/ScreenSaverEngine.app
to a cataloged QuickSilver directory. From there I just bound a key through the Triggers. Now I can lock the machine with ctl-option-l.

Monday, January 08, 2007

Suse 10.2 64-bit and VMWare Server

Need a 64-bit server so we can run our VMWare machines on it and utilize the 8+ gig of RAM. Originally tried CentOS but because VMWare Server is compiled against 32-bit libraries, it would be a nasty amount of work to install the needed libraries one-by-one (ldd spit out at least 20 libraries we needed). After digging around online it turns out that VMWare "officially" supports Suse but not much else. Time was of the essence and we bagged Gentoo for that reason.

The 10.1 install was pleasant, but the user experience was very unpleasant. I didn't actually install it, but a coworker did and it was only a matter of days until he migrated to Ubuntu. We were hoping that some of the usability issues were resolved in 10.2, happy to report that is the case. We installed the base system, developer libraries, kernel development and the 32-bit libraries during the initial package selection. After that, once the system was up and running, vmware installed without issue.

To use vnc (via ssh) we enabled Remote Login in Login Window Preferences (not sure why that's a System Application but not in the Control Center). The command to enable port forwarding for local vncviewer execution is "ssh -g -L localhost:5901:machine:5901 user@machine -X", then "vncviewer localhost::5901" will connect right up through that ssh tunnel (also, ssh with the -g enables anyone to use your tunnel).

Wednesday, December 13, 2006

Javascript dialog libraries

We explored various available libraries for managing dialogs within the application. We wanted an easy-to-implement solution that was intuitive to the user and didn't bog down the browser when rendering. We looked into the following solutions:


  • Yahoo UI: YUI is feature-rich, but you pay for it. In order to render dialogs there were (IIRC) 5 javascript files to include. It also appeared to be slower than the other solutions and was a serious amount of code for just opening a URL as a dialog. Wasn't too hard to ditch this after looking at the more simple solutions.
  • Lightbox gone wild: We liked this solution, but was pretty confined in terms of usage. You basically create links with a lightbox-specific class and then the initialization code for the page activates those links to function as lightboxes. No doubt this is easy, but it posed a problem with dynamic pages. We had some page that were returning links via AJAX, which would then require us to manually call the lightbox initialize() in order for those new links to behave properly. Wasn't worth the effort for the little (though nifty) functionality that lightbox provided.
  • jt_appdialogs: This was a very simple solution, but seemed slow (moving around the dialog) and not very friendly to fetching URLs (designed for rendering divs already in the page).
  • submodal: Another rather simple solution, but limited in functionality. Couldn't move the dialog around, though that's supposed to be doable. We also had issues in getting the right sizes.
  • prototype window class: Of all the solutions, this was the easiest to implement, provides a very intuitive user experience, is well-documented and simple to use.

Wednesday, December 06, 2006

testing issues with threaded ActiveRecord commits

I need to create a more generalized test in order to better exhibit the problems I experienced when spinning up a bunch of threads that all accessed a synchronized block of code that invoked ActiveRecord::Base#save & ActiveRecord::Base#destroy with use_transactional_fixtures = true. Below is the investigation and conversation with Jamis:


(12:27:33) russ: Jamis, can I plead with you yet again for more assistance? Name your price.
(12:31:34) jamisbuck: haha :) what's up?
(12:32:06) russ: I'm having some deadlocking issues with some thread-safe code I'm _attempting_ to write, and I've narrowed my issue to what I'm doing with ActiveRecord
(12:32:13) russ: here's the test:
(12:32:18) russ:
def test_provider_is_threadsafe
Thread.abort_on_exception = true

@ids = []
threads = []

#obtain three threads, each getting 10 ids
begin
3.times do

thread = Thread.new do
10.times do
sleep(0.2)
id = IdServiceHelper.instance.next_id

if (@ids.include?(id))
fail("Duplicate ID!")
else
@ids << id
end

end
end
threads << thread

end
threads.each {|thread| thread.join}

rescue Exception => ex
fail("Exception raised! " + ex.message + ex.backtrace.join("\n"))
end
end
(12:32:39) russ: and the culprit code is this:
(12:32:45) russ:
def next_id

next_id = -1

synchronize do
#get the next seed
orig_seed = Seed.new
orig_seed.save
seed_val = orig_seed.id

#destroy the used seed
orig_seed.destroy

next_id = @@provider_class.id_for_seed(seed_val)
end

return next_id
end
(12:33:04) russ: however, when I run the tests I get deadlock errors
(12:33:10) russ: and I've spent several hours trying different variations
(12:33:19) jamisbuck: what does the 'synchronize' method look like?
(12:33:39) russ: mixing in MonitorMixin
(12:33:54) russ: if I remove the .save and .destroy on the Seed models then my deadlocks disappear
(12:33:58) russ: but of course that fails the test
(12:34:14) jamisbuck: deadlocks from where?
(12:34:15) jamisbuck: AR?
(12:34:33) russ: that's my issue, not sure exactly
(12:34:39) jamisbuck: can you show me the error?
(12:34:41) russ: Loaded suite test/unit/id/id_service_helper_test
Started
.deadlock 0xb7d73748: sleep:J(0xb73e2204) (main) - test/unit/id/id_service_helper_test.rb:57
deadlock 0xb73e1a0c: sleep:- - /usr/lib/ruby/1.8/thread.rb:100
deadlock 0xb73e209c: sleep:- - /usr/lib/ruby/1.8/monitor.rb:266
deadlock 0xb73e2204: sleep:- - /usr/lib/ruby/1.8/monitor.rb:266

(12:34:46) jamisbuck: ok, not AR
(12:35:03) jamisbuck: what's your OS?
(12:35:05) jamisbuck: and ruby version?
(12:35:06) russ: Gentoo
(12:35:13) russ: 1.8.4
(12:35:47) russ: so even if I remove the synchronization block, which I have done, I get the same errors
(12:35:47) jamisbuck: where is MonitorMixin defined?
(12:35:55) jamisbuck: is that in the stdlib?
(12:35:57) russ: think so
(12:36:12) jamisbuck: ok, I see it
(12:36:21) jamisbuck: to be honest, I've never used monitor mixin
(12:36:24) jamisbuck: I always just do
(12:36:26) jamisbuck: require 'thread'
(12:36:29) jamisbuck: mutex = Mutex.new
(12:36:34) jamisbuck: mutex.synchronize { ... }
(12:36:37) russ: done that too
(12:36:38) russ: same results
(12:36:39) russ: :(
(12:36:54) russ: perhaps I should approach this differently
(12:37:03) jamisbuck: it's almost like Seed#save or Seed#destroy are trying to do something thread-wise
(12:37:11) russ: right, my thoughts also
(12:37:17) russ: I already have ActiveRecord::Base.allow_concurrency = true
(12:37:22) russ: which I thought would solve my problem
(12:37:29) russ: (since there is an underlying "freeze")
(12:37:33) jamisbuck: well
(12:37:37) jamisbuck: that only allows multiple connections
(12:37:42) jamisbuck: one per thread
(12:37:44) russ: gotcha
(12:37:46) jamisbuck: AR is not thread-safe
(12:37:48) jamisbuck: by itself
(12:37:58) jamisbuck: but still
(12:38:03) jamisbuck: save/destroy shouldn't be problematic
(12:38:17) russ: k, so if I approach this differently, the problem being that I want to fetch a new Seed, get the id and then destroy it
(12:38:36) russ: and lock anything else from getting the same value
(12:38:38) russ: any other ideas?
(12:38:42) jamisbuck: is your ruby version built with phtread support?
(12:38:50) russ: good question, I'll check
(12:39:23) russ: there is a USE flag for -threads
(12:39:31) russ: not sure if I have it enabled or not
(12:39:38) jamisbuck: k, well, you don't want it, regardless
(12:39:42) russ: k
(12:39:49) jamisbuck: try looking at what the ruby binary is linked against
(12:39:51) jamisbuck: ldd
(12:40:10) russ: ldd /usr/bin/ruby
linux-gate.so.1 => (0xffffe000)
libruby18.so.1.8 => /usr/lib/libruby18.so.1.8 (0xb7e3b000)
libdl.so.2 => /lib/libdl.so.2 (0xb7e21000)
libcrypt.so.1 => /lib/libcrypt.so.1 (0xb7df3000)
libm.so.6 => /lib/tls/libm.so.6 (0xb7dd0000)
libc.so.6 => /lib/tls/libc.so.6 (0xb7cb6000)
/lib/ld-linux.so.2 (0xb7f05000)
(12:40:17) jamisbuck: k, looks good
(12:40:35) jamisbuck: I really have no idea on this
(12:40:49) russ: then maybe the issue is that freeze I saw
(12:40:51) jamisbuck: this is outside my area of expertise
(12:41:11) russ: well you've broadened my horizons
(12:41:15) jamisbuck: :)
(12:41:18) russ: I'll keep digging in
(12:41:22) jamisbuck: k, good luck
(12:41:31) russ: you let me know if you have an Amazon list
(12:41:39) jamisbuck: :) I don't, but thanks anyway
(12:41:43) russ: your time is valuable and I appreciate the info
(12:41:53) jamisbuck: fwiw, ruby threads are awful..if at all possible, you should consider using fork instead
(12:41:59) jamisbuck: not always possible, but definitely preferable
(12:42:04) russ: that's good to know
(12:42:06) russ: I'll explore that also
(12:42:12) russ: have a good one
(12:42:15) jamisbuck: you too


I changed my code to try a more sql-native approach with the following:

#version 2

connection = ActiveRecord::Base.connection

orig_seed_val = Seed.find(:first).id
connection.begin_db_transaction

seed_val = orig_seed_val+1
connection.delete("delete from seeds where id=#{orig_seed_val};");
connection.commit_db_transaction
Seed.connection.execute("insert into seeds values(#{seed_val});");

next_id = @@provider_class.id_for_seed(seed_val)

Using this method I was then getting a native MySQL error regarding a lock timeout. This was curious and lead to the following:

(14:05:01) russ: wanna hear the gruesome details?
(14:05:20) jamisbuck: let's hear it
(14:05:38) russ: the locking was at the MySQL level
(14:05:48) russ: I tried to bypass AR
(14:05:53) russ: and execute straight sql
(14:06:03) russ: only to get a Lock timeout from mysql
(14:06:12) russ: investigated by "show innodb status"
(14:06:20) russ: and it gave me the locks/threads
(14:06:25) russ: followed that to my log
(14:06:30) russ: and whattayaknow
(14:06:40) jamisbuck: really! the exception you posted didn't look like one from the database, so I discarded that hypothesis
(14:06:48) russ: well, here's the culprit: self.use_transactional_fixtures = true
(14:07:24) jamisbuck: ah, ok
(14:07:26) jamisbuck: very wierd
(14:07:27) russ: the top level transaction had the lock!
(14:07:28) jamisbuck: what mysql version?
(14:07:57) russ: Gentoo Linux mysql-4.1.20
(14:08:05) jamisbuck: wierd! good catch
(14:08:13) russ: anyhow, changing back and then using AR
(14:08:15) russ: everything is good again
(14:08:21) jamisbuck: awesome, glad to hear it
(14:08:27) russ: so I lose, for that specific test, the benefits of transactional fixtures
(14:08:30) russ: oh well it's a toss up
(14:08:34) jamisbuck: yah
(14:08:43) jamisbuck: if your test uses transactions, you can't use transactional fixtures
(14:08:46) russ: so I suppose the theory learned is:
(14:09:03) russ: you can't write your own thread-safe code using AR in a test with self.use_transactional_fixtures=true
(14:09:19) jamisbuck: well, not even thread-safe
(14:09:21) jamisbuck: transactional
(14:09:23) russ: right
(14:09:27) russ: anyhow, back to work
(14:09:30) jamisbuck: cool beans
(14:09:32) jamisbuck: good find

Tuesday, December 05, 2006

deadlocks and ActiveRecord

According to this ActiveRecord is thread-safe. Turns out that I have some code for multithreaded identifier generation and since the seed is from the db, I must have thread-safe db interaction through ActiveRecord. My tests kept puking with deadlocks and I narrowed it down to the save/destroy operations on the model. Found this post which contained my answer:

ActiveRecord::Base.allow_concurrency = true

The kicker here is that this is never mentioned in the API docs...

Wednesday, November 29, 2006

self-signing certs in iis 6

Easiest way to do this is to download the IIS 6 Resource Kit Tools. Then find the site's id that will be assigned the cert. Search for the site's name in %SystemRoot%\System32\Inetsrv\MetaBase.xml, the id is the number appended in the Location attribute. For example:

<IIsWebServer Location="/LM/W3SVC/445577612" AuthFlags="0"
LogPluginClsid="{FF160663-DE82-11CF-BC0A-00AA006111E0}" SecureBindings=":443:"
ServerAutoStart="FALSE" ServerBindings=":80: 192.168.88.62:80:" ServerComment="testsite" />

The id here is 445577612.

Then, the command to assign the self-signed cert is:

C:\Program Files\IIS Resources\SelfSSL>selfssl.exe /N:CN=SERV2003DEV /K:1024 /V:700 /S:445577612 /P:443

Where CN is the server's name, K is the key length, V is the number of days the cert is valid, S is the site id, P is the port.

I did this on Windows 2003 Server, so no idea if it works in XP.

Tuesday, November 28, 2006

loading a cert into IIS 6 w/o a pending request

Thank you TechNet:
http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/53dfdb5e-6106-4d99-85bb-da199bc27c7e.mspx?mfr=true

Basically all that is needed is:

certutil -addstore my certnew.cer

And then it'll appear in the "Assign an Existing Certificate" wizard selection and be available for selection.

Wednesday, November 15, 2006

ActiveRecord in .Net

I'm using ActiveRecord in .Net for a school project. And it's making db interaction somewhat bearable. Coming from a Hibernate/ActiveRecord background, this is a breath of fresh air. Never been a fan of the data-mapper/set and stored proc that MS is so up on. Thanks to the Castle (http://castleproject.org/) guys for putting this together, it's very simple to get up and running and I found it _far_ easier to understand their tutorial than any of the NHibernate ones. Their blog app is a piece of cake to understand and runs out of the box (granted you have have a "test" db created).

The biggest issue I had was connecting to SQLServer Express 2005. Here's the connection string I ended up using:

Server=127.0.0.1,1433;Database=patstracks;Integrated Security=SSPI


ActiveRecord really makes it easy to decorate POCOs using attributes:

[ActiveRecord("[Client]")]

public class Client : ActiveRecordBase{
...
[PrimaryKey]

public int Id

{

get { return id; }

set { id = value; }



}
...
public static Client[] FindByNameLike(string name)

{

return (Client[])Client.FindAll(typeof(Client), new Order[] {Order.Asc("Name") }, new ICriterion[] { Expression.Like("Name", name+"%")});



}
...
}

Wednesday, November 01, 2006

in place phone editor via Ajax

UPDATE: I went about this the wrong way. Should've just overridden the necessary methods. I'll do it and replace this when I'm done.

Morphed the InPlaceEditor and made it more friendly for handling phone number entry:


// script.aculo.us controls.js v1.6.4, Wed Sep 06 11:30:58 CEST 2006

// Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// (c) 2005 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
// (c) 2005 Jon Tirsen (http://www.tirsen.com)
// Contributors:
// Richard Livsey
// Rahul Bhargava
// Rob Wills
//
// See scriptaculous.js for full license.
/*
*Only tested via load_text url
*Parses for extension on '$'
*Returns input as phone_value and ext_value
*/
Ajax.InPlacePhoneEditor = Class.create();
Ajax.InPlacePhoneEditor.defaultHighlightColor = "#FFFF99";
Ajax.InPlacePhoneEditor.prototype = {
initialize: function(element, url, options) {
this.url = url;
this.element = $(element);

this.options = Object.extend({
okButton: true,
okText: "ok",
cancelLink: true,
cancelText: "cancel",
savingText: "Saving...",
clickToEditText: "Click to edit",
okText: "ok",
rows: 1,
onComplete: function(transport, element) {
new Effect.Highlight(element, {startcolor: this.options.highlightcolor});
},
onFailure: function(transport) {
alert("Error communicating with the server: " + transport.responseText.stripTags());
},
callback: function(form) {
return Form.serialize(form);
},
handleLineBreaks: true,
loadingText: 'Loading...',
savingClassName: 'inplaceeditor-saving',
loadingClassName: 'inplaceeditor-loading',
formClassName: 'inplaceeditor-form',
highlightcolor: Ajax.InPlaceEditor.defaultHighlightColor,
highlightendcolor: "#FFFFFF",
externalControl: null,
submitOnBlur: false,
ajaxOptions: {},
evalScripts: false
}, options || {});

if(!this.options.formId && this.element.id) {
this.options.formId = this.element.id + "-inplaceeditor";
if ($(this.options.formId)) {
// there's already a form with that name, don't specify an id
this.options.formId = null;
}
}

if (this.options.externalControl) {
this.options.externalControl = $(this.options.externalControl);
}

this.originalBackground = Element.getStyle(this.element, 'background-color');
if (!this.originalBackground) {
this.originalBackground = "transparent";
}

this.element.title = this.options.clickToEditText;

this.onclickListener = this.enterEditMode.bindAsEventListener(this);
this.mouseoverListener = this.enterHover.bindAsEventListener(this);
this.mouseoutListener = this.leaveHover.bindAsEventListener(this);
Event.observe(this.element, 'click', this.onclickListener);
Event.observe(this.element, 'mouseover', this.mouseoverListener);
Event.observe(this.element, 'mouseout', this.mouseoutListener);
if (this.options.externalControl) {
Event.observe(this.options.externalControl, 'click', this.onclickListener);
Event.observe(this.options.externalControl, 'mouseover', this.mouseoverListener);
Event.observe(this.options.externalControl, 'mouseout', this.mouseoutListener);
}
},
enterEditMode: function(evt) {
if (this.saving) return;
if (this.editing) return;
this.editing = true;
this.onEnterEditMode();
if (this.options.externalControl) {
Element.hide(this.options.externalControl);
}
Element.hide(this.element);
this.createForm();
this.element.parentNode.insertBefore(this.form, this.element);
if (!this.options.loadTextURL){
Field.scrollFreeActivate(this.editField);
}
// stop the event to avoid a page refresh in Safari
if (evt) {
Event.stop(evt);
}
return false;
},
createForm: function() {
this.form = document.createElement("form");
this.form.id = this.options.formId;
Element.addClassName(this.form, this.options.formClassName)
this.form.onsubmit = this.onSubmit.bind(this);

this.createEditField();

if (this.options.textarea) {
var br = document.createElement("br");
this.form.appendChild(br);
}

if (this.options.okButton) {
okButton = document.createElement("input");
okButton.type = "submit";
okButton.value = this.options.okText;
okButton.className = 'editor_ok_button';
this.form.appendChild(okButton);
}

if (this.options.cancelLink) {
cancelLink = document.createElement("a");
cancelLink.href = "#";
cancelLink.appendChild(document.createTextNode(this.options.cancelText));
cancelLink.onclick = this.onclickCancel.bind(this);
cancelLink.className = 'editor_cancel';
this.form.appendChild(cancelLink);
}
},
hasHTMLLineBreaks: function(string) {
if (!this.options.handleLineBreaks) return false;
return string.match(/<br/i) || string.match(/<p>/i);
},
convertHTMLLineBreaks: function(string) {
return string.replace(/<br>/gi, "\n").replace(/<br\/>/gi, "\n").replace(/<\/p>/gi, "\n").replace(/<p>/gi, "");
},
createEditField: function() {
var text;
if(this.options.loadTextURL) {
text = this.options.loadingText;
} else {
text = this.getText();
}

var obj = this;

if (this.options.rows == 1 && !this.hasHTMLLineBreaks(text)) {
this.options.textarea = false;
var textField = document.createElement("input");
textField.obj = this;
textField.type = "text";
textField.name = "phone_value";
textField.value = text;
textField.style.backgroundColor = this.options.highlightcolor;
textField.className = 'editor_field';

var size = 20;
if (size != 0) textField.size = size;
if (this.options.submitOnBlur)
textField.onblur = this.onSubmit.bind(this);
textField.maxLength = size;
this.editField_phone = textField;

var textField = document.createElement("input");
textField.obj = this;
textField.type = "text";
textField.name = "ext_value";
textField.value = text;
textField.style.backgroundColor = this.options.highlightcolor;
textField.className = 'editor_field';
var size = 6;
if (size != 0) textField.size = size;
if (this.options.submitOnBlur)
textField.onblur = this.onSubmit.bind(this);
textField.maxLength = size;
this.editField_ext = textField;
}

if(this.options.loadTextURL) {
this.loadExternalText();
}


this.form.appendChild(this.editField_phone);
this.form.appendChild(document.createTextNode(" ext."));
this.form.appendChild(this.editField_ext);
},
getText: function() {
return this.element.innerHTML;
},
loadExternalText: function() {
Element.addClassName(this.form, this.options.loadingClassName);
this.editField_phone.disabled = true;
this.editField_ext.disabled = true;

new Ajax.Request(
this.options.loadTextURL,
Object.extend({
asynchronous: true,
onComplete: this.onLoadedExternalText.bind(this)
}, this.options.ajaxOptions)
);
},
onLoadedExternalText: function(transport) {
Element.removeClassName(this.form, this.options.loadingClassName);
this.editField_phone.disabled = false;
this.editField_ext.disabled = false;

var load_values = transport.responseText.stripTags().split("$");
if((load_values.length == 1) || (load_values.length == 2)){
this.editField_phone.value = load_values[0];
if(load_values.length == 2 ){
this.editField_ext.value = load_values[1]
}
}
Field.scrollFreeActivate(this.editField_phone);
Field.scrollFreeActivate(this.editField_ext);
},
onclickCancel: function() {
this.onComplete();
this.leaveEditMode();
return false;
},
onFailure: function(transport) {
this.options.onFailure(transport);
if (this.oldInnerHTML) {
this.element.innerHTML = this.oldInnerHTML;
this.oldInnerHTML = null;
}
return false;
},
onSubmit: function() {
// onLoading resets these so we need to save them away for the Ajax call
var form = this.form;
var value = this.editField_phone.value + "$" + this.editField_ext.value;

// do this first, sometimes the ajax call returns before we get a chance to switch on Saving...
// which means this will actually switch on Saving... *after* we've left edit mode causing Saving...
// to be displayed indefinitely
this.onLoading();

if (this.options.evalScripts) {
new Ajax.Request(
this.url, Object.extend({
parameters: this.options.callback(form, value),
onComplete: this.onComplete.bind(this),
onFailure: this.onFailure.bind(this),
asynchronous:true,
evalScripts:true
}, this.options.ajaxOptions));
} else {
new Ajax.Updater(
{ success: this.element,
// don't update on failure (this could be an option)
failure: null },
this.url, Object.extend({
parameters: this.options.callback(form, value),
onComplete: this.onComplete.bind(this),
onFailure: this.onFailure.bind(this)
}, this.options.ajaxOptions));
}
// stop the event to avoid a page refresh in Safari
if (arguments.length > 1) {
Event.stop(arguments[0]);
}
return false;
},
onLoading: function() {
this.saving = true;
this.removeForm();
this.leaveHover();
this.showSaving();
},
showSaving: function() {
this.oldInnerHTML = this.element.innerHTML;
this.element.innerHTML = this.options.savingText;
Element.addClassName(this.element, this.options.savingClassName);
this.element.style.backgroundColor = this.originalBackground;
Element.show(this.element);
},
removeForm: function() {
if(this.form) {
if (this.form.parentNode) Element.remove(this.form);
this.form = null;
}
},
enterHover: function() {
if (this.saving) return;
this.element.style.backgroundColor = this.options.highlightcolor;
if (this.effect) {
this.effect.cancel();
}
Element.addClassName(this.element, this.options.hoverClassName)
},
leaveHover: function() {
if (this.options.backgroundColor) {
this.element.style.backgroundColor = this.oldBackground;
}
Element.removeClassName(this.element, this.options.hoverClassName)
if (this.saving) return;
this.effect = new Effect.Highlight(this.element, {
startcolor: this.options.highlightcolor,
endcolor: this.options.highlightendcolor,
restorecolor: this.originalBackground
});
},
leaveEditMode: function() {
Element.removeClassName(this.element, this.options.savingClassName);
this.removeForm();
this.leaveHover();
this.element.style.backgroundColor = this.originalBackground;
Element.show(this.element);
if (this.options.externalControl) {
Element.show(this.options.externalControl);
}
this.editing = false;
this.saving = false;
this.oldInnerHTML = null;
this.onLeaveEditMode();
},
onComplete: function(transport) {
this.leaveEditMode();
this.options.onComplete.bind(this)(transport, this.element);
},
onEnterEditMode: function() {},
onLeaveEditMode: function() {},
dispose: function() {
if (this.oldInnerHTML) {
this.element.innerHTML = this.oldInnerHTML;
}
this.leaveEditMode();
Event.stopObserving(this.element, 'click', this.onclickListener);
Event.stopObserving(this.element, 'mouseover', this.mouseoverListener);
Event.stopObserving(this.element, 'mouseout', this.mouseoutListener);
if (this.options.externalControl) {
Event.stopObserving(this.options.externalControl, 'click', this.onclickListener);
Event.stopObserving(this.options.externalControl, 'mouseover', this.mouseoverListener);
Event.stopObserving(this.options.externalControl, 'mouseout', this.mouseoutListener);
}
}
};


Ajax.InPlacePhoneEditor.prototype.__initialize = Ajax.InPlaceEditor.prototype.initialize;
Ajax.InPlacePhoneEditor.prototype.__getText = Ajax.InPlaceEditor.prototype.getText;
Ajax.InPlacePhoneEditor.prototype.__onComplete = Ajax.InPlaceEditor.prototype.onComplete;
Ajax.InPlacePhoneEditor.prototype = Object.extend(Ajax.InPlaceEditor.prototype, {

initialize: function(element, url, options){
this.__initialize(element,url,options)
this.setOptions(options);
this._checkEmpty();
},

setOptions: function(options){
this.options = Object.extend(Object.extend(this.options,{
emptyText: 'click to edit...',
emptyClassName: 'inplaceeditor-empty'
}),options||{});
},

_checkEmpty: function(){
if( this.element.innerHTML.length == 0 ){
this.element.appendChild(
Builder.node('span',{className:this.options.emptyClassName},this.options.emptyText));
}
},

getText: function(){
document.getElementsByClassName(this.options.emptyClassName,this.element).each(function(child){
this.element.removeChild(child);
}.bind(this));
return this.__getText();
},

onComplete: function(transport){
this._checkEmpty();
this.__onComplete(transport);
}
});



Thursday, October 26, 2006

iterating an Enumerable just to create another array...

via ActiveSupport (thanks Jamis!):

values.map(&:name)

or the standard way

values.collect{|val| val.name}

Wednesday, October 25, 2006

subversion and gse-locate.el

Updated this chunk in gse-locate.el:

(defvar gse-locate-regexp-list
(list "\\.elc"
"\\.class"
"/CVS"
"/target/classes"
"#"
"~"
".cvsignore"
"/\.svn/"
)
"A list of regular expressions that match \"uninteresting\" filenames.
These will be stripped from the locate list before it is displayed.")

pretty indenting HTML chunks in Emacs

After reading this and installing xmml and psgml, I can now indent a wildly formatted chunk of HTML with indent-region (in sgml-mode) and my buffer is then much more readable and formatted nicely. xmml modifies the faces in sgml-mode for much better readability and color identification.

Tuesday, October 17, 2006

Dependency Inversion conversation with Jamis Buck

This conversation represents the sort of headache/transition in getting out of the strict OO mindset and contract-based programming that Ruby allows you to intuitively avoid:

(14:45:35) russ: if you have a minute, gotta design question for you. I have an authentication component that I'd like to turn into a service so it's interchangeable ala Hivemind. Would you recommend copland for doing that? At this point I only have two implementations of the service, but it makes sense to have more in the future...
(14:45:59) jamisbuck: for ruby, I'd avoid DI implementations as a general rule
(14:46:03) jamisbuck: ruby is flexible enough that you don't need them
(14:46:11) russ: the alternative I could think of would be to create some sort of abstract base class and then extend as needed...though not sure how that would fit into Ruby's methodology
(14:46:32) russ: I'm still stuck in j2ee thinking
(14:46:40) jamisbuck: :) it took me two years to come around :)
(14:46:49) russ: so recommendations for my issue?
(14:47:02) jamisbuck: well, you could use a factory class
(14:47:10) russ: two different classes, rely on some static class and put the logic in there to call the appropriately underlying?
(14:47:11) jamisbuck: Foo.authentication_service
(14:47:18) jamisbuck: sure
(14:47:26) jamisbuck: without knowing all the details that sounds fine
(14:47:30) jamisbuck: there may be an even simpler way to do it
(14:47:39) russ: my problem is contracts: interfaces/abstract base classes
(14:47:52) russ: how to move away from that yet make the Ruby code solid
(14:47:54) jamisbuck: careful not to overthink the problem
(14:48:01) jamisbuck: ruby encourages pragmatic solutions
(14:48:20) jamisbuck: I know that when I was coming out of Javaland, I would frequently overlook the simple solutions because they were so simple :)
(14:48:27) jamisbuck: that's not to say every problem has a simple solution
(14:48:40) russ: indeed
(14:48:49) russ: as usual, your feedback is highly valuable
(14:48:52) russ: thanks Jamis!
(14:48:53) russ: have a good one
(14:48:56) jamisbuck: :) you too!

Thursday, October 12, 2006

middle-click selected text into Emacs

Since my conversion 18 months ago, I've been delaying my quest to find the solution for middle-clicking and getting my text from terminal into Emacs. After some chat in Freenode (thanks to twb)and looking in Google Groups, here's the solution I slapped into my .emacs:


(global-set-key (kbd "") (lambda () (interactive) (insert (x-get-selection 'PRIMARY 'COMPOUND_TEXT))))


UPDATED:
The problem was this line:

(setq x-select-enable-clipboard t)


changed it to:

(setq x-select-enable-clipboard nil)

and now I can paste in from mrxvt, xterm, etc.

Wednesday, October 04, 2006

maven2 junit jvmargs

In the original maven you could put the following line in your project.properties to manage jvm args at testing time:

maven.junit.jvmargs=-server -Dconfiguration.resourceType=properties ... -Xrunjdwp:transport=dt_socket,address=8787,server=y -Xmx512m


In maven2, the easiset way is:

<project>
...
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>
-server -Dconfiguration.resourceType=properties ... -Xrunjdwp:transport=dt_socket,address=8787,server=y -Xmx512m
</argLine>
</configuration>
</plugin>
</plugins>
</build>
...
</project>

one of the reasons I like maven2

http://www.javaworld.com/javaworld/jw-12-2005/jw-1205-maven-p2.html

Suppose you want to use Hibernate in your project. You would simply add a new dependency to the dependencies section in pom.xml, as follows:


hibernate
hibernate
3.0.3
compile


And that's it! You don't have to hunt around to know in which other JARs (and in which versions) you need to run Hibernate 3.0.3; Maven will do it for you!


That is sweet, and relieves great pain in larger projects with many tendrils to OSS jars.

Adding a custom attribute to the user class in Active Directory, then fetching it via Ruby

(credit: http://www.lacoude.com/docs/public/Attributes.aspx#_ftn8)

First, install adminpak.msi from windows\system32 and then add the following registry key:

Key: HKLM\SYSTEM\CurrentControlSet\Services\NTDS\Parameters
Value: "Schema Update Allowed" = 0x1


Then run schmmgmt.msc. Right click on "Attributes" and "Create Attribute" as the "imsid" attribute, specifiying the x500 oid as created from oidgen.exe. Index it, activate it, and allow it to be shown in advanced view.

Lastly, go to the properties of the "user" class, select the "Attributes" tab. Add an "optional" attribute by finding the "imsid" attribute.

Now, using ADAM-adsiedit.msc, the Administrator can connect to the AD tree and update users' attributes with the appropriate imsids:

Right-click on ADAM ADSI Edit, select "Connect to..."
select "Distinguished name or naming context"
enter "cn=users,dc=devdomain,dc=it,dc=vital" (adjust dc values as necessary)
click "Ok"
expand the tree, find the CN of the user to edit
right-click on user, select "Properties"
find the "imsid" attribute, edit, apply

Done.

Here's the ultra-basic Ruby code that will lookup and print the imsid attribute:

require 'ldap'

host = "192.168.88.20"
port = 389
username = "servuser"
login = "servuser@devdomain.it.vital"
password = "mypassword"
found_imsid = "not_found"
dn = "cn=users,dc=devdomain,dc=it,dc=vital"


connection = LDAP::Conn.new(host,port)
connection.set_option(LDAP::LDAP_OPT_PROTOCOL_VERSION,3)
connection.bind(login, password)

result = connection.search2( dn, LDAP::LDAP_SCOPE_SUBTREE, "cn=#{username}", ["imsid"])

if(result.size == 1)
found_imsid = result.first["imsid"][0]
end

p found_imsid