Wednesday, March 05, 2008

Just Do It Yourself

{

I go back and forth on the very thing Larry calls "Lead-Developer Compression Ratios." Two things happen over the long haul that affect my thinking: first, even though it's time consuming communicating needs to a junior developer, it seems to pay off when it comes to fine tuning and bug fixing - it's not something you have to worry about since it's delegated. "Finished" in my world means it's been through a few cycles of testing, cycles that take a lot of time.  The second thing though is when something is delegated and I think is done fairly well only to find at the aforementioned testing/bug fix cycle is horribly broken and either has to be hacked into a technical debt ridden working order or needs to be done again - from scratch.  It seems to come down to the complexity of the tasks - if it's simple you can take the time, if it's complex just do it yourself.

}

Monday, March 03, 2008

Twining: Iron Python DSL for DB Update IV

{

long entry because it was written at an airport, just back from celebrating 3 years with my beautiful wife in Monterey, CA...

A few interesting things, but first just a summary of what can be done with what's new in red:

#connection strings
cn = "Data Source=.\\sqlexpress;Initial Catalog=DB_SOURCE;Integrated Security=SSPI;"
cn2 = "Data Source=.\\sqlexpress;Initial Catalog=DB_DESTINATION;Integrated Security=SSPI;"

#back up the database to a file
database(cn).backupto("C:\\temp\\loungin.bak")

#copy/export basic
database(cn).table("MY_TABLE").copyto.csv("c:\\spam.csv")
database(cn).table("MY_TABLE").copyto.xmlFieldsAsAttributes("c:\\spam.xml")
database(cn).table("MY_TABLE").copyto.xmlFieldsAsElements("c:\\spam.xml")

#pick your delimiter
database(cn).table("Photos").copyto.delimited("\t", "c:\\spam.tsv")

#copy to database
database(cn).table("MY_TABLE").copyto.database(cn2)

#all copy operations can leverage transform dictionary
mytrans = {"FIELD1":"upper","FIELD2": lambda x: x.upper(),"FIELD3": lambda x: x[::-1]}

database(cn).table("MY_TABLE").transform(mytrans).copyto.xmlFieldsAsAttributes("c:\\spam.xml")
database(cn).table("MY_TABLE").transform(mytrans).copyto.xmlFieldsAsElements("c:\\spam.xml")
database(cn).table("MY_TABLE").transform(mytrans).copyto.delimited("\t", "c:\\spam.tsv")
database(cn).table("MY_TABLE").transform(mytrans).copyto.database(cn2)

... and so on, see above

Some internal changes:
1. Error Handling, quite lazy for now simply stores a combination of a friendly message along with full text of the exception thrown:

class errorhandle:
    def print_error(self, text, error):
        """ Handle an exception by just printing a friendly message and then the error's guts"""
        print text
        print error

try:
    sqlhelper().run_sql(registrar.databaseRegister, sqlBackup)
except Exception, inst:
    errorhandle().print_error("Error occured during backup", inst)

2. Some Pythonic prettiness (via Catherine):

#if registrar.transforms.has_key(field): -- es muy fao!
if field in registrar.transforms:       

I do like the more idiomatic form myself.  This a perfect example of where, as a .NET developer I look around for methods and miss a beautiful idiom.

3. Right under my nose, back to idiom, were a few simple pythonic forms that took away a lot of the line noise and clutter I was producing during my initial rabid sketches of the idea. Doing multiple assignment out of a SqlDataReader is something I only thought of now, though it makes such perfect sense:

column_name, column_type, column_length, column_identity = \
    r["name"], r["typename"], str(r["max_length"]), r["is_identity"]

4. Returning tuples rather than lists.  Tuples are more effecient and as effective.  A question that's begun burgeoning now is whether excessive use of tuples is lazy when a specific type is more clear.  For example, when I read column data from a table, I need to know two things: the column name and whether it's an identity (autonumbering). Right now I'm doing the following lazy gesture:

colTypeInfo.append((column_name, column_identity)) #(column_name, column_identity) is the tuple added to the list.

But if I start to add other useful bits of info, like the datatype of the underlying column, I wonder if a class would be better since you could have something like:

colTypeInfo.append(ColumnData(column_name, column_identity, column_type)) #Where ColumnData is a type somewhere

Right now the tuple approach works fine and a class feels like overkill. For now, I'm just afraid of it bloating as needs present themselves...

5. Speaking of identity columns, I added better support for them in tables being copied.  I also now use brackets for column names since certain people like to use reserved words for columns (or don't have a choice).

6. I mentioned in a comment that I tried to reconcile feedback from both Catherine and Michael "Fuzzyman" Foord.  When I match columns for transformations I allow any TypeError to be suppressed, but also store it in a "warnings" list that I'll incorporate into the completed process.

def checkAndTransform(self, field, value):
    """ Perform transformation on fields based on either:
        a) keyword entries ("upper", "lower", etc... )
        b) lambda expressions
    """
    if field in registrar.transforms:       
        if callable(registrar.transforms[field]):
            try:
                value = registrar.transforms[field](value)
            except TypeError:
                registrar.warnings.append("Your transform failed on field %s" % field)
        elif registrar.transforms[field] == "upper": #more of this kind of stuff _maybe later.
            value = value.upper()
    return value   

As always you can have a look at the entire thing here.  It's been great getting guidance, any comment is welcome and will be studied.

What is on the list?
1. I've been using a cheap, unstudied approach to delimited files. I'll need to look at the "official" way of escaping entries.
2. Importing data
3. A few more variants of operating on databases, like "create."

}

Tuesday, February 26, 2008

Twining: Iron Python DSL for DB Update III

{

My thoughts as exhibited in a little Python script now have a name: Twining. 

Unplanned illness slowed me down over the weekend, but the beauty of lambda expressions make transformations a breeze. I'll let the code document what I added.

cn = "Data Source=.\\sqlexpress;Initial Catalog=MVCBaby;Integrated Security=SSPI;"
mytrans = {"Field1":"upper","Field1": lambda x: x.upper(),"Field3": lambda x: x[::-1]}
database(cn).table("Photos").transform(mytrans).copyto.csv("c:\\foo.csv")

As you can see, "mytrans" is a dictionary containing a matching of column names to both a keyword string, "upper", and also lambda expressions that model functions to operate on the constituent data (the [::-1] idiom reverses a string).  I'd add a few keywords for simple things people often do to data but the beauty of lambda expressions is that it keeps my code lazy and empowers whoever is using the script to make their own judgement about what to do with data.


Here's what goes on behind the scenes - the copyto class has a checkAndTransform method that matches up a field value with it's "transform":


	def checkAndTransform(self, field, value):
if registrar.transforms.has_key(field):
if repr(type(registrar.transforms[field])) == "<type 'function'>":
value = registrar.transforms[field](value)
if registrar.transforms[field] == "upper":
value = value.upper()
return value


I'm not Pythonic enough yet to know if I need to call repr and do a string comparison when testing if a type is a function, but it works just fine.


So a few thoughts:


1. What are the usual changes we make to data when exporting or importing?
2. Is it stupid to have shortcut strings or should I just fall back on writing lambdas?
3. Is there a better way of testing for a function than
repr(type(registrar.transforms[field])) == "<type 'function'>"


The to-do list from my previous post is still intact, I'll be working through it in the near future.  Have a look at the complete script and if you have thoughts or opinions, please let me know. A big goal here is not only to make something useful, but to learn Python (and be Pythonic, the two don't necessarily coincide).


Here's a full list of what can be done at this point:


mytrans = {"Field1":"upper","Field2": lambda x: x.upper(),"Field3": lambda x: x[::-1]}

database(cn).table("MyTable").transform(mytrans).copyto.csv("c:\\foo.csv") #with transform
database(cn).table("MyTable").copyto.csv("c:\\foo.csv") #without transform
database(cn).table("MyTable").copyto.database(cn2)
database(cn).table("MyTable").copyto.xmlFieldsAsAttributes("c:\\here.xml")
database(cn).table("MyTable").copyto.xmlFieldsAsElements("c:\\there.xml")
database(cn).backupto("C:\\temp\\my_backup.bak")



}

Thursday, February 21, 2008

Iron Python DSL for DB Update II

{

Attepting releasing early & often - here are a few new features to the ideas I'm putting together for the Database specific DSL.  I'll summarize all that's possible with it now with the new stuff highlighted in red.

#some connection strings
cn = "Data Source=.\\sqlexpress;Initial Catalog=MVCBaby;Integrated Security=SSPI;"
cn2 = "Data Source=.\\sqlexpress;Initial Catalog=Irvine;Integrated Security=SSPI;"

#some things to do
database(cn).table("MyTable").copyto.csv("c:\\foo.csv")
database(cn).table("MyTable").copyto.database(cn2)
database(cn).table("MyTable").copyto.xmlFieldsAsAttributes("c:\\spam\\eggs.xml")
database(cn).table("MyTable").copyto.xmlFieldsAsElements("c:\\spam\\eggs.xml")
database(cn).backupto("C:\\spam\\eggs.bak")

The overall idea is to build a language centric, developer oriented implementation of what is done in a tool like SSIS or its predecessor DTS - I'm using SQL Server for a start but there's no reason this can't include other database platforms. It's quite exciting that even without knowing much Python I can get that much done in the language.  I'll spend time refactoring and reorganizing the script I've started with, but please feel free to download and modify it. Please post any improvements or ideas for how I can improve the Python and added any other features to the dsl. (Point on using __getattr__ well taken).

My todo list?
1. Aforementioned "transforms" for data in migration
2. Exception handling :^)
3. Copying tables is a rough sketch but needs a lot of work
4. Export formats besides CSV and XML: arbitrary delimiters and fixed field length
5. __getattr__ :^)

}

Tuesday, February 19, 2008

Iron Python DSL for ETL

{

Hanselman wrote about "fluent" interfaces recently which confirmed something I'd been thinking for a while. What if rather than massive tools we just had a language to express ourselves when we wanted to move data around?  What if we could say something like:

database("connection string").table("table").copyto.csv("C:\\spam\\eggs.csv")
or
database("connetion string").table("table").copyto.database("connection string 2")

In the spirit of releasing early and often, here's an implementation of the above language for sql server with Python. I'll be extending the flexibility quite a bit, and my Python skills are still those of a learner, but here it is for comment.  Before I post the whole script, here are a few goals:
1. XML data:
database("connection string").table("table").copyto.xml("C:\\spam\\eggs.xml")
2. Transforms:
transformDictionary = {'column1':'upper', 'column2':'some regex'} #these could become a fluent interface of their own.
database("connection string').table("table").withTransform(transformDictionary).copyto.csv("C:\\spam\\eggs.csv")

So here's that rather unrefined code download the latest implementation. 

Below was just some scratchwork from a Friday afternoon when I started sketching:

# BORRE DATABASE OBJECT
# 02/08/2008 - David Seruyange - @FRIDAY BURNOUT
import clr
clr.AddReference("System.Data")
from System import *
from System.Data import *
from System.Data.SqlClient import *
from System.IO import *

class registrar:
tableRegister = ""
databaseRegister = ""

class database:
"Model of a database somewhere"
def __init__(self, connectString):
"Initialize the rectangle"
self.connect = connectString
registrar.databaseRegister = connectString
self.copyto = copyto()

def table(self, t):
registrar.tableRegister = t
return self

class copyto:
"Model of a copy of some object"
def csv(self, path):
""" Save the result to a CSV file """
cn = SqlConnection(registrar.databaseRegister)
cn.Open()
cmd = SqlCommand("select * from " + registrar.tableRegister, cn)
r = cmd.ExecuteReader()
fileOut = open(path, 'w')
while r.Read():
sOut = ""
for i in range(r.FieldCount):
sOut += str(r[i]) + ","
sOut += "\n"
fileOut.write(sOut)
cn.Close()
fileOut.close()

def database(self, connect):
(ddl, colInfo) = buildDDL(registrar.tableRegister)
cnTarget = SqlConnection(connect)
cnTarget.Open()
cmdBuildTargetTable = SqlCommand(ddl, cnTarget)
cmdBuildTargetTable.ExecuteNonQuery() #builds the target table
cnSource = SqlConnection(registrar.databaseRegister)
cnSource.Open()
cmdSourceIter = SqlCommand("select * from " + registrar.tableRegister, cnSource)
sourceReader = cmdSourceIter.ExecuteReader()
insertCode = ""
while(sourceReader.Read()):
insertTemplate = "INSERT INTO " + registrar.tableRegister + " VALUES("
for i in range(sourceReader.FieldCount):
insertTemplate += "'" + str(sourceReader[i]) + "',"
insertCode += insertTemplate[:-1] + ")\n"
cmdExecuteInsert = SqlCommand(insertCode, cnTarget)
cmdExecuteInsert.ExecuteNonQuery()
# "save: %s\n table: %s\n to path: %s" % (registrar.databaseRegister, registrar.tableRegister, connect)

def buildDDL(tName):
query = """
select
c.[name], c.max_length, c.[precision], c.scale,
ty.[name] as typename
from
sys.columns c
join sys.tables t on c.object_id = t.object_id
join sys.types ty on c.system_type_id = ty.system_type_id
where
t.[name] = '__table__'
"""
query = query.replace('__table__', tName)
cn = SqlConnection(registrar.databaseRegister)
cn.Open()
cmd = SqlCommand(query, cn)
r = cmd.ExecuteReader()

ddl = """
CREATE TABLE __xyz__(
__columns__)
"""

columnsDefinition = ""
colTypeInfo = []
while r.Read():
#todo: support for other column types such as numeric or decimal
columnTemplate = " COLUMN_NAME DATATYPE LENGTH NULL,"
columnTemplate = columnTemplate.replace('COLUMN_NAME', str(r[0]))
columnTemplate = columnTemplate.replace('DATATYPE', str(r[4]))
colTypeInfo.append(str(r[4]))
if str(r[4]) == "varchar":
columnTemplate = columnTemplate.replace('LENGTH', "(" + str(r[1]) + ")")
elif str(r[4]) == "char":
columnTemplate = columnTemplate.replace('LENGTH', "(" + str(r[1]) + ")")
else:
columnTemplate = columnTemplate.replace('LENGTH', "")
columnsDefinition += columnTemplate + "\n"

r.Close()
cn.Close()
ddl = ddl.replace('__xyz__', tName).replace('__columns__', columnsDefinition).replace(",\n)", "\n\t)")
return [ddl, colTypeInfo]


cn = "Data Source=.\\sqlexpress;Initial Catalog=MVCBaby;Integrated Security=SSPI;"
cn2 = "Data Source=.\\sqlexpress;Initial Catalog=Irvine;Integrated Security=SSPI;"
# jepp
#database(cn).table("Photos").copyto.csv("c:\\foo.csv")
#print "---"
database(cn).table("Photos").copyto.database(cn2)

}

Monday, February 18, 2008

Release Early & Often

{

Paul Buchheit (who we can thank for Gmail) comments on a post by Marc Andreessen:

For web based products at least, there's another very powerful technique: release early and iterate. The sooner you can start testing your ideas, the sooner you can start fixing them.

I wrote the first version of Gmail in one day. It was not very impressive. All I did was stuff my own email into the Google Groups (Usenet) indexing engine. I sent it out to a few people for feedback, and they said that it was somewhat useful, but it would be better if it searched over their email instead of mine. That was version two. After I released that people started wanting the ability to respond to email as well. That was version three. That process went on for a couple of years inside of Google before we released to the world.

Interesting and it goes along with something Guy Kawasaki was saying in a recent podcast I commented on hearing.  So the next question comes down to technique - when you're working on something by yourself, how do you schedule builds?  I'm thinking I may start to take deliberate "coding vacations" - days I take off* from work in order to push through releases on my various little software projects.  Hm... other thoughts?

*My employer offers "comp days" so it's not at the expense of my day job.

}

Saturday, February 16, 2008

Check File Existence, Javascript (Prototype)

{

If you're like me, you spend a lot of time using System.IO and can easily check for the existence of a file on the filesystem with a File.Exists(@"C:\spam\eggs.file")

It's a little surprising that I hadn't run into it before but a few weeks ago I needed that same functionality with javascript. I found a few things online and what works best is using AJAX to make a request and check the HTTP status for whether or not the request failed.  My approach was to use Prototype and something like this:

function checkForFile(imgName, displayHolder){
new Ajax.Request('Repo/' + imgName + '.jpg',
{
method:'get',
onSuccess: function(transport){
var response = transport.status || "no response text";
if(parseInt(response) == 200){
displayHolder.src = 'Repo/' + imgName + '.jpg';
displayHolder.style.display='block';
}
},
onFailure: function(){
displayHolder.src = 'Repo/NoImage.gif';
displayHolder.style.display='block';
}
});
}

Works like a charm.


}

Mantras

{

Some good things to repeat to yourself from Dormando. I've a long way to go on so many of these and was geeky enough to give myself a scorecard.

I'll spare you that (after just deleting a lot of babble that would only be interesting to me) but there are two areas that I can do with some serious improvement:

1. Relentless automation
It's shameful how often I'm doing things I could easily automate (repeated FTP sessions?)
2. Monitoring
I wonder how out of line it would be to programmatically enable "breadcrumbs" for user's activity?  Finding out what they really used and what they insisted upon for nothing.

}

Saturday, February 09, 2008

Spitting Code Like Lam

{

I started changing my Visual Studio settings after seeing Hanselman's post and thought I'd be able to spit fire like John Lam once I'd downloaded his settings (it's gotta be the shoes!). The contrast was a bit much (though working in low light helped) and after a night's worth of being like JLam I wanted to go back to (dare I admit?) VS default settings. That didn't work out too well (even using the "default settings" option in VS, go figure) so I opted for Brad Wilson's settings which I've grown to like.

When the IDE "hot or not" thing first cropped up I changed settings but what makes me boring, preferring the default, is that I'm on a lot of machines at different times; my laptop, desktop, remote on a couple of servers, and when I help others.

}

Monday, February 04, 2008

Grabbing SQL 2005 Blobs with IronPython

{

On Saturday I needed to grab some blob data and create files out of it. The following was some Python I used, inspired very much by this code.

The biggest point of interest is the strongly typed array, which in IronPython is simple once you know how: using Array.CreateInstance.

 

 

#GET IMAGES FROM IMAGE BINARY FIELD
# 02/02/2008 - David - @THE COMMAND CENTRE

import clr
clr.AddReference("System.Data")
from System import *
from System.Data import *
from System.Data.SqlClient import *
from System.IO import *

CONNECT = "Data Source=(local)\sqlexpress;Initial Catalog=DATABASE;Integrated Security=SSPI"

sql = "select ID_FIELD, BLOB_FIELD from product_set"
cn = SqlConnection(CONNECT)
cn.Open()
cmd = SqlCommand(sql, cn)
reader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
buffSize = 100
buff = Array.CreateInstance(Byte, buffSize)
recCounter = 0
while reader.Read():
print "Creating " + str(reader[0])
fs = FileStream(str(reader[0]) + str(recCounter) + "_diagram.png", FileMode.OpenOrCreate, FileAccess.Write)
bw = BinaryWriter(fs)
if(reader[1] != DBNull.Value):
posit = 0
b = reader.GetBytes(1, posit, buff, 0, buffSize)
while(b == buffSize):
bw.Write(buff)
bw.Flush()
posit = posit + buffSize
b = reader.GetBytes(1, posit, buff, 0, buffSize)
bw.Write(buff, 0, b)
bw.Flush()
bw.Close()
fs.Close()
recCounter = recCounter + 1

reader.Close()


I'd like to clean it up a bit, but I've written about 5,000,000 things that I "intend" to clean up before posting and they're never posted.


}

What Comes First; Rocks

{

Oliver Steele has a new essay entitled Adding the Easy Piece; or, The Metaphor of the Rock.  Insightful as usual, and I love the visualizations.

Personally, I'm experiencing the effects of pushing a rather large rock around a room.

}

Wednesday, January 30, 2008

Scott McCloud's Four Tribes - Developer Edition

{

Last year I was fortunate to catch Scott McCloud here in Sioux Falls. It's doubtful that he'd ever find his way here under normal circumstances but he was doing a 50 state tour in support of his book, "Making Comics."  I believe a dual aim was to provide his two young daughters, who travelled and presented with him, an experience of a lifetime. 

I was particularly struck with a classification he had for comic (and indeed all types) artists.  He placed them into four quadrants:

Here is a quote of an explanation of how the classifications work:

Those who value draftsmanship the most, and who are the most invested in the idea of mastery, beauty, and craft find themselves on the opposite side of the fence from those whose strongest values are raw honesty, authenticity, and a kind of rebellion against the status quo. That dichotomy comes between what I call the classicists and the iconoclasts. The children of Hal Foster versus the children of R. Crumb.

That’s the truth and beauty diagonal that separates two of the four tribes. The other two corners are the formalists and the animists, who represent the distinction between form and content. The formalists like to experiment and take the medium apart, figure out how it works and put it back together, and try new things; while the animists really just like to tell a compelling story, and want the form to vanish, to become transparent, so that you don’t know you’re reading a comic at all.

I wonder how well these notions apply to the practice of programming.  I can easily see the classicist: mastery, beauty, and craft - the person who uses things like recursion excessively for the computer science elegance they bestow.  Opposite them, I see the iconoclast -  the hacks that make things work and could care less about the principles or structure of a thing and instead devote themselves to the beauty of experience.

I think the animists and formalists can be distinguished as well by the metric of language/tool preference.  The obsessives of language would seem to tend toward formalism and understanding every moving part.  An animist may be the type of person who excels at making a tool do legwork with no particular interest in exactly what that tool is baking under the covers. 

Of course we all will have elements of each but I like to think of myself patterned after Scott McCloud. The formalist who might write the same software over and over in different languages just to see how expression and power vary at the lowest levels.

Interesting food for thought.

}

Tuesday, January 29, 2008

Java Programmers on Windows Forms team?

{

Randomly: worked with the CheckedListBox tonight. It's interesting to run into "getter/setter" type methods in the .NET universe.  One would assume a collection that specifically supported setting constituent objects as "selected" or "checked" but instead there are methods like: GetItemCheckedState and SetItemCheckedState.

It would be interesting to have the Windows Forms equivalent to the annotated base class library reference. Perhaps tomorrow I'll try to peak at the source code.

}

Disturbing News

{

"I am going to tell you something that will disturb you. You might laugh, but it will be a cold uncertain laugh that will haunt you as you read on, because somewhere deep down you'll know it to be true. You might brush it off, get on with your day, yet sometime later, a week or a year, it will seep back in and unsettle you to the core. From that moment on you will be changed. You will think different, act different and will fundamentally be different. So take a moment to prepare yourself now, breath deeply, clear your mind and open up to the possibility that building software is hard."

Interesting thoughts from The Wayward Weblog. 

 

}

Thursday, January 24, 2008

Not An Engineer

{

Ravi Mohan makes the provocative, if not new claim (with follow up) that programmers are not engineers. I take the majority of his quibble to be the title some flaunt: "software engineer."

I've never felt able to use "engineer" for myself, but I don't perceive this badly. My official title is "software architect" though most of my day is not spent on architecture.

It's a bit postmodern of me but does anyone's title mean much?  Short of very specialized work, one must have multiple skillsets for the different roles they are cast in on a daily basis.

I have to do the following, fairly regularly:
1. Write Code
2. Write Specs
3. Customer Service
4. Testing
5. Write Proposals
6. Mentor
7. Marketing

I'm owning up to a lot of stuff, particulary #7, that I would never admit to for the sake of saying that most jobs these days require multiple intelligences.

Think Santiago Calatrava: engineer, architect, artist. And he deals with clients, too.

}

Temporary Switch Back: C# to VB.NET

{

I did the switch back for a project that a VBA enlightened client requested but I kept finding myself asking how to syntactically do what I usually do in C# (especially inheritance-wise) in VB.NET.  Terry Smith has a handy online book that has a comparison so that you can easily figure out what the VB.NET syntax is for what you know how to do in C#. I'm not sure when it was written; no word on Generics but that's an easy enough syntax to duplicate with (Of T) rather than angle brackets.  What throws me off in addition to the inheritance verbosity are a lot of the array related casting operations that seem intuitive now in C# like:

Dim dropRows As Row() = e.Data.GetData(GetType(Row()))

Of course with the latest developments in VB.NET, I may end up using the language enough to make all of this easy to recall from memory. 

As much as I want to join the Red Sox fans in cheering for VB, there are still many things that annoy me about the language.  Line continuation characters are at the top of the list, and case insensitivity closely following. Yes, I strongly dislike case insensitivity in a programming language.

}

Tuesday, January 22, 2008

Up In The (Ruby) Club

{

A while back I had a phone call from a woman with an eastern European accent wondering if I would be willing to take a survey.  I'm usually an instant no to queries like this but she knew my Achilles heel:

"Participants get $50 Amazon Gift Certificate"

So a few days ago my inbox chimed with an email with the gift certificate in tow. I didn't hesitate with my purchase of David Flanagan's Ruby book. 

As an aside, it seems that Flanagan got some flack from a Gilles Bowkett on not being a bona fide Ruby person. If Flanagan isn't cultured enough to do Ruby, I'm in trouble...

... but I've been in trouble most of my short puff anyway.

On a serious note: the "up in the club" attitude of some (okay, mostly Rails) Ruby people is what is driving a backlash against Rails and Ruby in general.

}

Friday, January 18, 2008

Nutrition

{

I just looked at Oliver Steele's programmer's food pyramid and did a self evaluation of sorts. I know that I err too much on the reading of "blogs" versus reading long prose about programming.  That's something to change this year.

As well I use libraries a lot without digging into anything once my problem solving is done.  I think there's a form of mental stamina in digging deeper into a problem once you've apparently solved it - my instinct is to simply move on and try to tackle what's next.  Now that the .NET Framework code is available, that and other libraries should occupy my reading time.

While I don't struggle with the inclination to write code, I've long since thought it's better to try to write different types of applications and build some breadth.  Especially after my umpteenth web based CRUD app, I'm now interested in blending Windows Forms and Web stuff in the small variety of utilities that I compulsively write.

}

Wednesday, January 16, 2008

What's It Worth?

{

In the wake of all the plastic surgery and body augmentation going on around, a developer like myself can feel a little out of place - out of century to be more exact. 

And yet, whether he's joking or not, I'm half tempted by Wesner's admission to "performance enhancers."

But the thing I know with certainty is that being productive will only beget the desire to be more productive. Instead of learning and implementing 4 technologies, it will be 8.  I'll pile more home projects and "meware" until I'm aching for another 5 or 6 hours a day.

In a world that has the audacity to produce ridiculously smart people who are subject to feeling that yet others are "smarter" I may as well hold.

But it's tempting... maybe until I know F# and then I'll hold...

}

Saturday, January 12, 2008

13.75 hours, CodeMash

{

I earned the reputation as "the guy from South Dakota" at CodeMash; many people were amazed that I took it upon myself to drive just under 14 hours both there and back for the conference.

What would they have done if I told them I also:
a) took time off from work
b) paid for it out of pocket
c) drove my own car

But I think it's not *that* strange. Staying at work would have meant the same old stuff I do every day all year and instead I got to see some of the best Einstein's presenting on Python, DSLs, Dojo, REST, and IIS7. I made some friends as well and on top of that got to kick it with Scott Hanselman.  All for the cost of a long drive with an audio book.

I had posted on sessions I wanted to see, here's a little rundown of memorable sessions I actually attended:

1. Neal Ford's keynote "Software Engineering & Polyglot Programming"

Neal's one of those sedate cognoscenti who don't appear to have an emotional angle on platforms, just a sense of design and engineering that they wish to communicate.  In his talk he urged developers towards the notion of language as a tool, and that dynamic languages take us places that our old friends in the static realm cannot.  He made a reference to Jack Reeve's essay which I've written about before, and said a few times the following phrase which I thought was apt:
"Testing is the engineering rigor of software development."

If I could have asked Neal, I'd have wanted some comment on something I posted some time back - Oliver Steele's blog post on The IDE Divide in which he divides developers into the Language Mavens and Tool Mavens.  I think Neal's perspective was very much that of a language versus tool maven.

2. Catherine Devlin's "Crash, Smash, Kaboom Course in Python"
Great talk on Python fundamentals while illustrating a universe simulator library (forget the name).  I've been trying to pick up Python for some time and much of what I got was from watching Catherine's use of the language in her demos.  The one bummer: I was using a Python distribution from my iBook (Mac OSX) that didn't include the Python modules she was demonstrating with. Even more of a bummer: in my hotel room a different laptop was running Ubuntu with just the modules needed to follow along with her in code.

3. Kevin Dangoor on Dojo
I may have made Kevin feel uncomfortable with how happy I was to see this talk (he did a great job) but I've felt quite alone over the last two-ish years working with javascript libraries.  I used jQuery heavily for my tool "proper" after which I used Prototype/Scriptaculous for a few other projects.  I then switched to YUI for nRegex so I'd been around the block with my frameworks with only Dojo missing.  Dojo seems to go beyond these other frameworks just on its ambition alone and I'm wondering if that can translate into a happy mix with the heavyweight stuff I have to do at work with ASP.NET. 

4. Dustin Campbell on F#
Dustin gave a deft introduction to the F# language which had to be the biggest thoughtbludgeon I got during the conference.  I've listed F# as my "someday language" and it will remain so since Ruby will occupy my time along with Python in learning mode over the next year or so. Nevertheless, it was good to see a demonstration of the language and some of the implications thereof.

5. Kevin Dangoor on Gears and Dojo (DojoX Offline)
The second session I sat in on with Kevin, this dealing with Dojo's offline capabilities in large part courtesy of Google Gears.  It was as good as the first Dojo session and left my mind popping with ideas for leveraging that functionality. 
Soon - I'd say around the release of Silverlight 2.0 - people like me are going to face a fork in the road of using browser plugins and thick (they use the word "rich") vendor technologies, or using javascript and existing web technologies like CSS on a new level.  All the Dojo stuff represents, to me, what Microsoft and Adobe (no need to even mention JavaFX, oops I just did) are not tuning to as they ramp up Silverlight and Flex.  Not that it's in their interests: the stuff of web standards isn't really the profit center that proprietary technologies are.

6. Neal Ford on DSLs with Dynamic Languages
Neal was impressive this second time with some practical talk and examples of DSLs.  He started first with Groovy, which left me disappointed since I don't anticipate using it, but to show the "best" world he switched to Ruby.  I am really looking forward to IronRuby's release, but at present I think much of what he discussed can be implemented in Python. 

7. Dave Donaldson on RESTful Web Services
I've been familiar with the REST buzzword for some time but as a term thrown out in competition with standard web services (the WS-* stuff).  Dave did a good job of unpacking the essence of REST and showing demonstrations of usage.  It's interesting to see just how much backlash there is against WS-* and the manufactured complexity therein.  The only thing I disagreed with was Dave belittling Dave expressed reservations about the Astoria project teetering into the over-engineered realm of WS-* but I am hopeful it will retain its original intent - I really, really like the idea of Astoria (born of the same backlash to WS-*? I'm just talking here...).

8. Scott Hanselman on Mashups with IIS7
He has the gift and he knows it: first with a humorous prologue and then with a good presentation on IIS7 and using its underpinnings with a mix of PHP. Inspired by Bill Staples article on IIS7 and PHP, but with the detail and demonstrations with which Scott's earned his following.

I went to a few other sessions too, but these were the ones which, as the Brits say, "tickled my fancy."  I was disappointed to miss out on Jay Wren's intro to Castle as well as Bruce Eckel's thoughts on Python. I guess there's next year...

... and I do anticipate returning to CodeMash although I'm quite sure I'll fly rather than driving. :^)

}

Wednesday, January 02, 2008

Enemies and Organization

{

I usually try not to be an echo chamber, especially when posts show up on Coding Horror or Steve Yegge's blog. But what's interesting is a rebuttle to a notion that Yegge started, namely that size is an enemy in code base.

Franz Bouma has an interesting post to follow up that is worth a counter balance of views.

Conventions:

I commented once about LoC in one of our projects, not so much with an interest in maintainability, but as a comparison with how much code was being "generated" on my behalf by the IDE.  The project has grown since that post which had the codebase at around 30,000 lines of code.  This is nowhere near the 500,000 line mark but one design decision made early on that has always helped in navigating around was the heavy use of conventions.  Because we followed a pattern for where we put things, it's easy to find which project a piece of code is in as well as which part of the code one needs to dive into to make a modification. 

Abstraction:

One thing I'm noticing about the open source projects I look at is how layers of abstraction can lead to the kind of indirection that's hard to follow.  I speak only of ideals but it seems like too much abstraction can lead to the kind of confusing codebases that people online are reacting to. That logic may be the Mort in me going against the grain; it seems like many think that indirection and abstraction may add flexibility, but that flexibility will be a trade off for how easily a person, especially not the original author, finds their way.

}

Sunday, December 30, 2007

xPathFinder

{

The short version:
I'm releasing xPathFinder, a tool I wrote for doing XPATH expressions against xml files on the file system. You can get information about it as a tool by going to the website. Here are some screenshots:

 

The long version:
Not too long ago I ran into a problem that I thought would be common but didn't seem to have a canned solution. We use a webservice to store some data in a database but we also store the xml files transmitted on the file system as a defensive maneuver in case the database is unavailable or the xml is invalid. After a while I was dealing with a lot of xml files - far too many to search one at a time and needing more structured lookup than a desktop search tool offered. This is the raison d'etre of this tool. Of course it could have been a quick script in -insert language of choice- but this was something I needed to do repeatedly and have more facility with than console output. I'm also planning to make it simple enough for our client to use. It was a goal of mine to get it up before the end of the year so I'm happily posting this a day early.

One more footnote to this tool - stylistically I've done quite a bit of blending between Windows Forms and Web by leveraging the WebBrowser control heavily for things I thought would be easier to quickly generate html for as well as the feedback mechanism which allows users to report bugs or request features. It's so tightly coupled that while it will work without an internet connection, it's a much more limited experience. I really like this model and will probably start doing more blending like this for new work.

You can get more detail from the website or just ask directly by submitting feedback.

Future plans?

1. XPATH functionality works for most xml documents, but namespace heavy documents with prefixes seem to throw a curve ball.
2. What I'm posting was actually a fast prototype I intended to use to make this tool in WPF from - I'm not sure that the WPF step is still necessary but I may release an updated version since this is a fairly straight forward utility.
3. I'd like to make it open source. Not sure of what steps to follow, but CodePlex is probably the best starting point. I always promise myself I'll clean up my code before doing something like that but maybe I should just bite the bullet since I think the idea is sound enough.

}

Tuesday, December 11, 2007

Installing ASP.NET 3.5 MVC Preview

{

Code Climber has this great list of what you need to download and the order in which you must install it. I just completed my installation and have begun to poke around.

}

Thursday, December 06, 2007

Someday Language: F#

{

There's a lot to learn these days (whenever isn't there a lot?) and one thing I will do for 2008 is make a list of technologies I'd like to dive into with some sense of priorities. 

Among the ASP.NET MVC, Powershell 2.0, and Iron Python (for starters) I've been interested in F#. First as a topic on Hanselminutes but I lurk on Harry Pierson's blog and he's been posting about it quite a bit.  Here are some links:

1. F# Overview on hubFS
2. From DevHawk:

Someday it is.

}

Mads Samples

{

Mads Kristensen has a listing of his code samples. One thing I like about Mads' samples is that they are all very straightforward without unnecessary layers of abstraction.

}

Wednesday, December 05, 2007

The FogBugz Salesman

{

Once or twice people have confused what I'm doing with sales. Some time back I met with a prospective client and kept having to explain that I actually do write code and would probably be a lead developer on any work they gave us. The reaction I had for even the mere perception that I was "sales" was a little surprising to myself although with some reflection I realized it was because I conflated most of what I disliked about salesmen into an image I couldn't deal with for myself:

  • Style over substance
  • Shallow understanding
  • Pandering for a quick buck

But once in my life I was a happy salesman. Some time back I pushed the company I worked for into adopting FogBugz and really building a large part of our lifecycle around it. I did so enthusiastically after reading Joel's early essays on bug tracking and seeing how well it applied to our situation.

I've seen other bug tracking software since but still think the FogBugz experience was best.  It seems simple, but because of how much thought has gone into the product, I gather a lot of work has gone into keeping it stripped from unnecessary features.

To be clear, I don't work as a bona fide "in house" developer. But as a consulting company, I spend a lot of time playing that role or working with people in it.  It's therefore conflicting when I read his understanding of what it means to work in house. Phil Haack had it right in the middle of 2005 when he wrote of the irony of this disdain towards the people that would be excited to use his software in the first place.

I wonder what kind of conditioning it is - maybe that I've liked musical artists who are fairly open about loathing their fanbase - but I still miss the simplicity and elegance of FogBugz. 

What's sad these days is that as much as I'd like to slip on the poorly fitting suit and do my sales routine, we get Sharepoint for free (okay, not free but let's just say Microsoft does an excellent job making it seem so) and it's the environment in which we track what I'd gotten my previous company to use FogBugz for so effectively.  I'm not a big Sharepoint fan (that's an understatement) so I'd even be tempted to go The Powers That Be and ask for FogBugz if I couldn't predict the answer right away.

Tomorrow I'll be unflustered but I've got a few comments on what it's like to be in house:

1. In a small enough company, it's great to have decision making power.  I've used technologies like Ajax and Perl where a larger environment would have involved committee meetings with some manager shooting me down for doing things differently. You don't have to be a renegade to do this, just document what you do well and communicate with anyone you're working with that may have to look at it on your behalf.

2. In consulting it helps a lot to condition your client.  First build confidence with a track record of success, after which the client is usually willing to listen to you when you'd like to do things "right" or improve a piece of software even if it's getting by functionally.  After a while, depending on the client, they will usually just trust your judgement and stay away from technical arguments unless there's some disproportionate cost.

3. Software is never finished.  This is true even for what is developed in house.  As a result the process of continual improvement still exists.  It takes a tremendous amount of discipline to try to develop things right when there's a small budget or a tight deadline but I always think of those moments I've spent late at night hacking the ugliest workarounds because of a bad initial effort. Most of the time finishing when it's "good enough" is about the taste and craftsmanship of the person who writes the software; whether they tried to think of the future or not.

4. From working in both a "software company" and a "consulting company" I understand that software development is always a process of coming to terms with friction - all the unexpected realities and circumstances of real life and real users. Different places will have different kinds of friction; where an in house developer may have to deal with the kind of discipline it takes to write unit tests on a deadline a programmer at a software company may have the dilemma of trying to be all things to all people.

}

Tuesday, December 04, 2007

Comment Spam Begone

{

I maintain a few personal websites, one of the closest to my heart is phoDak, a photoblog.  I wrote the site using ASP.NET about two years ago and intended it to be a low key, personal area to post pictures.  I had absolutely no validation on comments and my "what will be" attitude worked for a long time until about a week ago when I saw a comment spam link to porn right off the most recent picture.  No longer avoidable, I looked into a few ways to block unwanted comments and came up with a hybrid approach:

1. Use a photo/word as validation for a human user, just like Jeff Atwood's blog.
2. I heard about Akismet from Phil Haack who mentioned it in passing on a Dot Net Rocks episode. I found a free library and wrote about 10 lines of code:

AkismetManager akismetManager = 
new AkismetManager("my key", "my site");
string ip =
Request.ServerVariables["REMOTE_ADDR"].ToString();
if(akismetManager.IsValidKey()){
AkismetItem item =
new AkismetItem(ip, Request.UserAgent.ToString());
item.AuthorName =
CommentOwnerTextbox.Text;
item.AuthorUrl =
CommentURLTextbox.Text;
item.Content =
CommentTextbox.Text;
if(akismetManager.IsSpam(item)){
akismetManager.SubmitSpam(item);
return;
}
}

Q.E.D., really. Somewhat Mort-ish for me to lean solely on the library but it works beautifully: my spam comments since implementation remain at absolute zero.


}

CodeMash: I'll be there!

{

On a whim I've signed up to be at CodeMash 2008.  After learning about the conference when Hanselman posted he'd keynote, I mapped out that Sandusky, OH (Whiskey, Tango, Foxtrot!) is none too far (an audio book's worth of distance).

I'm really looking forward to the opportunity to walk among Elvis and Einstein, hopefully gleaning some direction along the way. The session list is impressive, I'm thinking it will be hard to choose a particular direction.

I've been studying Python of late, so I'm really looking forward to Bruce Eckel's Why I Love Python. Another interestingly titled Python presentation Crash, Smash, Kaboom Course in Python will be run by MIT alum Catherine Devlin.  Finally on the Python front, I'll try to squeeze into the Getting Started with Django session.

On the "indy" .NET programming, I'm interested in the Introducing Castle session from Jay R. Wren. Because Hanselman is going to be there I can't imagine no mention of ASP.NET MVC stuff, so hopefully it will somehow be mentioned at least comparatively.

Jesse Liberty is going to present on Silverlight, so that's something I won't miss either. There are other Microsoft technology presentations I should see but it would be hard to sit in on a Sharepoint session when I could be learning Python design patterns.

The other area of interest I'll have is the Dojo stuff, two sessions in particular: Overview of the Dojo JavaScript Toolkit and Working Offline with Dojo+Google Gears, both by Kevin Dangoor.

Well, it should be interesting from start to finish, I'll be working on my note taking skills so that I can share what I do learn.

 

CodeMash – I&apos;ll be there!

}

Monday, December 03, 2007

Tis the Season

{

Don't get me wrong, I love Christmas too, but I really like the Advent Calendars that wind up the year. 

24 ways
Drew McLellan and his crew have been putting together web development tricks to round out the year for the last few years.

Perl Advent Calendar
None too late and looking like it was designed by a Perl programmer.

Two advent calendars I'd love to see:
1. Microsoft .NET
2. [Iron] Python

}

Thursday, November 08, 2007

Firefox 3 Coming

{

LifeHacker has a first look at the forthcoming Firefox 3. It's interesting to see lots of improvements to the storage and management of places visited online - I'm sure this will provide inspiration for the Internet Explorer team at Microsoft to implement cool new features too.

A feature I asked for (and got a skeptical response) was the ability to do what Firefox seems to aim for but in a Google-ish way. That is to say that it would be nice to have a browser history management/search capability that precluded real effort in organization. In simpler terms, the whole "search, don't sort" experience one has with Gmail, except with browsing history and favorites.

}

Tuesday, November 06, 2007

Web Shell: Prototype & IronPython

{

I've been experimenting with IronPython of late trying to get the gestalt of Python as a language.  It occurred to me that something I had been thinking about for a while as a web project would make sense as an Iron Python project so I dabbled a bit.

The idea I had was a command line type application that approximated commands going to a windows shell and sent the results back to the user.  It's a part of a larger suspicion that I've had: that command lines are crisp, efficient user interfaces that are easy to lose sight of because it's not a natural way of thinking on the web.

The screen shots tell you the basic story: you open your browser to nothing but an underlined textbox after which you type your command and press the enter key. 

The client code is pretty straight forward - I've become disillusioned with YUI and moved back to using Prototype:

function runCommand(cmd){
    var request = new Ajax.Request(
        'eruServer.aspx',
        {
            parameters:'cmd=' + cmd,
            onComplete: handleResult
        }   
    );
}

function handleResult(response){
    $('loaderImage').style.visibility = 'hidden';
    var cmdResult = response.responseText;
    $('stdoutDiv').innerHTML = '<pre>' + cmdResult + '</pre>';
}

So that's all pretty simple, on the server processing the request is equally simple in IronPython.

from System.Diagnostics import *
from System.IO import *

def Page_Load(sender, e):
    cmd = Request.cmd
    p = Process()
    p.StartInfo.FileName = "cmd.exe"
    p.StartInfo.UseShellExecute = 0
    p.StartInfo.CreateNoWindow = 1
    p.StartInfo.RedirectStandardInput = 1
    p.StartInfo.RedirectStandardOutput = 1
    p.Start()
    myOut = p.StandardInput
    myIn = p.StandardOutput   
    myOut.WriteLine(cmd)    
    p.StandardInput.Flush()
    p.StandardInput.Close()
    output = myIn.ReadToEnd()
    p.StandardOutput.Close()    
    p.Dispose()
    Response.Write(Server.HtmlEncode(output))

The web project is fairly small - go ahead and download it here. If you have any improvement, let me know - I'm not sure how to start this as an "open source" affair but it would be a great solution as a light weight tool for remotely operating on a server.

Oh yeah, security: I was thinking of simple NTFS permissions on the files along with Windows Security on the website.  Should do the trick...

}

Monday, November 05, 2007

Innovative Thinking

{

 

There are some great videos at the Business Innovation Factory -

Jason Freid (37 Signals) -
I've been watching these guys for a long time. Although I'm a little resistant to some of the accolades associated with them, the 37 Signals crew thinks clearly and has a clear identity with which they seem overwhelmingly successful.
My favorite comment is Jason saying that they (37 Signals) want to be "enemies of mediocrity."

Richard Saul Wurman -
I first learned about Wurman from TechTV's "Big Thinker" series - although he is trained as an architect his career spans the sort of multidisciplinary mix that makes him special. He originated the TED conferences which have become quite popular of late. He's got an interesting new project called 19:20:21, be sure to check out the information graphics.

Clay Christensen -
One of the most interesting thinkers in the theory of business at present.  I wonder if Clay is more an economist than what one would consider a conventional "business" person. His gifts as a teacher shine through in this particular presentation.

 

}

Sunday, October 21, 2007

Leveraging CSS opacity for help

{

A few projects ago a control was created (who exactly did it I'm not sure) for displaying dialog "popups" without new browser windows.  The technique was fairly straightforward: an IFRAME with an opacity filter and a div with the popup values. 

I wasn't a huge fan of the infamous "popup" which managed to come up in project after project, but the idea of using opacity on an IFRAME for an overlay of helpful information struck me about a week ago. 

The nRegex interface, which is quite straightforward to me, still seems to pose some confusion to new users and so I thought I'd use it might be suitable for a virgin implementation of the idea.  It's a little crude* but the idea should come across: use the 'How to use Nregex' button to display the overlay and it seeks to explain the various pieces of the interface.

The implementation is quite simple. There's an IFRAME with the following attributes:

frameBorder="0"
scrolling="no"
style="z-index:1000;position:absolute;
top:0;left:0;width:2000px;height:2000px;
FILTER:alpha(opacity=80);-moz-opacity:.80;opacity:.80;
display:none;"
src="infoFrame.htm"

Within the frame, a button hides the IFRAME calling a javascript function from the parent window. 

The easiest way to implement this is to use the skeleton of the interface in the *original* design.  I'm interested in comments on this approach - would it be feasible as a way to document an interface's functionality?

}

Wednesday, October 17, 2007

Podcasts I: Think Big

{

I remember my first conference well: I was 24, it was February of the year 2000 and I was in San Francisco.  I'd bartered my way there: I turned down a raise from my employer and instead asked for a "personal budget" for professional development. In a bookstore I'd seen an ad in the Visual Basic Programmer's Journal and thought it was an opportunity to develop skills and visit my favorite city at the time.

One keynote that week was delivered by the futurist Paul Saffo. He spoke about observing trends and thinking past the day to day problem solving we experienced in our lives as programmers.  I remember his anecdotal story: an engineer working in telecom had purchased land on hilltops knowing there would be a demand for communication towers on top.

It's been nearly a decade but with Saffo in mind I still try to get out of the "technical" and think on a higher order.  With that in mind here are a few podcasts from last week I enjoyed:

1. Scott Berkun - The Myths of Innovation

Scott was a developer and manager at Microsoft but broke away to write and mentor. Key takeaway on innovation: breakthroughs are less about epiphany and more about consistent effort and dedication. Scott's blog is here.

2. Guy Kawasaki - The Art of Innovation

I've been wary of Guy to this point; marketing guy, and Apple obsessed. I like Apple too but not enough to start to ignore the outside world. But not only did I laugh and get entertained, I learned a few things. Guy recommends companies (and I'll extend that to people too) need a mantra, not a mission statement.  He also has great ideas about releasing early and often.  Good stuff.
Guy blogs here.

3. Ned Gulley - MATLAB Programming Contest

John Udell interviews Ned on an interesting collaborative contest Mathworks puts on.  I always like hearing a John Udell interview since he probes with more than the passive interest than most people in conversation.  Someday when I'm not bleeding a lack of time I'll check in on the problems although I think my math skills are suspect (and rusty) enough to render it more fascination than practical utility.
Ned's "starchamber" is here. (I learned the meaning of that word from the Merriam-Webster Word of the Day podcast by the way)

}

Monday, October 15, 2007

NYT presents OPEN

{

A new boast puts perspective on the original New York Times tagline: "All the News That's Fit to Print." 

Now we have "All the Code That's Fit to printf()".

On a serious note, OPEN is a new blog written by and for developers. I'll subscribe for the moment even if all the code I'm interested in is usually in a language that doesn't support printf natively.

Courtesy of Aaron.

}

Saturday, October 06, 2007

C# 3.0 Screencast

{

I hope I can call him a friend - I was fortunate enough to sit a class with him and then ran into him at TechEd - but Tim Rayburn has an excellent screencast overview of C# 3.0 new language features.  For 46 minutes of your time, you'll not only be up to speed, but hopefully a little excited at the future.

 The first few items have more to do with improving the syntactial approach to things we're already familiar with:

1. Automatic Properties

public string Foo{get;set;}

2. Implicitly Typed Variables

var o = new SpecificType();

3. Object Initializers

class Test{

public string Foo{get;set;}

public string Bar{get;set}

}

var p = new Test(){Foo = "shaz", Bar = "bot"};

4. Collection Initializers

List<string> myList = new List<string>(){"foo", 'bar"};

List<Test> myList2 = new List<Test>(){

new Test(){Foo="foo", Bar="bar"},

new Test(){Foo = "blam", Bar="biff"}

}

The remaining items are better explained rather than just shown - I suggest you pay closer attention to the screencast:

5.  LINQ & Anonymous Types

6. Lambda Expressions

7. Extension Methods

(This was, as Tim assumed, my favorite piece)

Although Partial Methods were noted on the list, time seemed to run out on Tim. Stay tuned; it appears he is planning to continue doing screencasts.

}

Monday, September 24, 2007

The Shining Armor is Rusty (on Rails)

{

Derek Sivers writes about switching back to PHP from Ruby on Rails after attempting to rewrite cdbaby. Raganwald references an intersting series from Chad Fowler on "Rewrites" and why they are so difficult.

}

Saturday, September 22, 2007

Beautiful Code

{

Although it seems to be a little disagreement over the existence of beautiful code, a refactor I did today was pleasant to my eye.

Starting with:

string result;
if (parameterLessCommands.Contains(commandName))
{
    result = RunArglessCommand(user, commandName);
}
else {
    string commandArg = RetrievePairCommandArg(commandData);
    result = RunArgCommand(user, commandName, commandArg);
}
return result;

Ending with:

return
(parameterLessCommands.Contains(commandName)) ?
            RunArglessCommand(user, commandName) :
            RunArgCommand(user, commandName,
RetrievePairCommandArg(commandName));
   

I'll take it. ()?: is your friend!

}

Tuesday, September 18, 2007

Meeting Time

{

I've always wanted to work for Microsoft. My first chance was right out of college when a professor of mine passed my resume to his friend up there.  I had some embarrasing crap about how I'd always wanted to work for "the company." It was all true but I can imagine the HR person directing anything that sappy to the trash. Instantly.

But it's just as well - Steve McConnell has an interesting comment about how much time at Microsoft may be spent in meetings - for developers:

When I was at Microsoft in 1990-91 I probably spent less than 5 hours a week in meetings. In contrast, I had a former Microsoft employee tell me earlier this year that on the team he was on he was booked in meetings from 10:00-4:00 5 days a week. Lots of managers at other companies have told me that they're in meetings all day every day and get most of their "real work" done during evenings and weekends, so obviously there's a big difference between Microsoft 1990 and Microsoft 2007, and among different companies.

}

Tuesday, September 11, 2007

Pivot, UDF, FizzBuzz!

{

As I hit "publish" from my previous post on pivot tables, a thought struck me on another most excellent use for them. No, really - for the next job interview:

SELECT
    CASE
        WHEN I % 5 = 0 AND I % 3 = 0 THEN 'FizzBuzz'
        WHEN I % 3 = 0 THEN 'Fizz'
        WHEN I % 5 = 0 THEN 'Buzz'
        ELSE CONVERT(VARCHAR(2), I)
    END
FROM dbo.fnPivot(100)

}

Pivot Tables with UDFs

{

I taught a T-SQL Programming class this week and in the process looked over some old books on the subject. One in particular I've enjoyed was the Transact-SQL Cookbook from O'Reilly - I have yet to find as novel an approach to SQL, coming from the ideas of set theory rather than tutorials on querying. I'm biased too, my best friend in highschool was Slovenian and one of the authors, Aleš Špetič, hails from that fine country.

A cool idea from the very first chapter is the pivot table, a numeric range that can come in handy for many different types of operations. The book, which is probably circa Microsoft SQL Server 7, demonstrates the building of a pivot table using some hardcoded insert statements followed with a cartesian join that generates the range.

It occured to me in SQL 2000 and higher one can use a User Defined Function and get all the benefits with a little bit more flexibility. Here is a simple approach to the same concept:

CREATE FUNCTION fnPivot(@BOUND INT)
RETURNS @Pivot TABLE(I INT)
AS
BEGIN
DECLARE @I INT
SET @I = 1
WHILE @I <= @BOUND BEGIN
INSERT INTO @Pivot VALUES(@I)
SET @I = @I + 1
END
RETURN
END
GO

The approach is different but the benefits are similar. A simple one from the first chapter is building a calendar of a given range of days. I've adapted it to use the function above:

SELECT
CONVERT(CHAR(10), DATEADD(d, i, CURRENT_TIMESTAMP), 121) [date],
DATENAME(dw, DATEADD(d, i, CURRENT_TIMESTAMP)) [day]
FROM
dbo.fnPivot(7)

date day
---------- ------------------------------
2007-09-13 Thursday
2007-09-14 Friday
2007-09-15 Saturday
2007-09-16 Sunday
2007-09-17 Monday
2007-09-18 Tuesday
2007-09-19 Wednesday

}

Wednesday, September 05, 2007

Nregex Kaizen vol. I

{

Kaizen is all about small improvements that never stop coming.  With respect to Nregex, I plan to keep it moving as a project by spending small amounts of time on new features that will hopefully make it more useful.

Tonight's new feature, though it was really something I did on Saturday morning, is a bookmarklet that should make it a little easier to get into the site from elsewhere (like your favorite IDE).

A few weeks ago my boss noticed some latency issues, especially with larger documents. I've added a "manual" mode that will let you press a button or just hit your enter key to evaluate a regex, rather than it being processed as you type.  Animated gifs give a little feedback on wait time.

If you have a request for a feature, please submit it here.  If you have a handy regex you solved some problems with, please submit it too. I'm currently at work on a "library" that I hope to cover some basic regular expressions (phone, zip, ssn, and so on) with.

}

Monday, August 27, 2007

Graham, On Point

{

I was just missing the old Paul Graham, the one who would write wisdom for the type of programmer that I imagined myself to be. The most recent essay, Holding A Program In One's Head, is that treat I've been waiting for.

}

.NET 301 Redirect

{

Scott Hanselman was noting that many people who'd updated the locations of their tools on his 2007 Ultimate Developers Tools List had emailed or contacted him asking him to update his reference.

He lamented the fact that they didn't simply use HTTP 301 redirects (Moved Permanently) which tools can easily use to update referenced links.

I must confess, I was one of those people.  I just lazily made a default.asp that had one line:

Response.Redirect("http://www.nregex.com")

But 301 redirect are pretty simple whether you use .NET or lazily throw an ASP script somewhere.

'classic ASP
Response.Status="301 Moved Permanently"
Response.AddHeader "Location", "http://foo/bar.asp"

'.NET

Response.Status = "301 Moved Permanently";
Response.AddHeader("Location","http://foo/bar.asp");

Source: seoconsultants.

}

Friday, August 24, 2007

NRegex

{

I embarrassed myself today (yelling at the work desk, telling everyone I'd take them to McDonalds) but with good cause: a tool I wrote some time back made it to Scott Hanselman's 2007 Ultimate Developer/Power User Tools List. The goal of the tool was simple: to do browser based evaluation of regular expressions using the .NET engine.  Prior to writing it I would frequent Rexv.org but because the engines supported there were different, I'd usually have to do some conversion to get things to the .NET world.

There are quite a few .NET Regular Expression tools: Expresso, which is my first and favorite since I've used it longest, but also tools like Roy Osherove's The Regulator. The problem with these tools, however, was that as fat clients I wasn't always easily able to use them: I work on different machines (home, work, client sites) and also assist people quite a bit away from my desk.

There are also quite a few Regular Expression tools for the web, Rexv, which I mentioned before but also RegexPal. But these tools support either javascript or alternate implementations so patterns like (?<foo>\w+) usually return some kind of error. 

The way Nregex works is pretty straight forward: I'm using YUI for the Ajax library and working with the .NET implementation of the regular expression on the server.  A simultaneous goal of mine is to get into more of YUI because I'm always building little knick-knacks in javascript and I think it's the library to beat right now.

Of course it's a fledgling: I worked on it a few nights when I could and fixed bugs here are there when I had a moment.  Please use it and give me feedback since that will be my biggest help in making it better.

One more thing: I'm trying to collect useful regular expressions. I'd like to build a good library of expressions to help users of the tool. Use the feedback form and let me know if you've got one you've found handy. Don't worry if it's not .NET specific, I'll do the translation.

}

Sunday, August 12, 2007

What Comes First?

{

Although it's an older essay (November, 2004), The IDE Divide made for some good Sunday reading. Not only is the author, Oliver Steele, engaging but his visualizations are exceptional. I'd like to think of myself as a "language maven" - that is a person who puts the emphasis on language capabilities before tools - but I know that growing up in the Microsoft world as I did, I understand how big of a difference good tools can be.

One item I don't recall seeing in the essay was how tool mavens are responsible for their own obsolesence. It makes perfect sense to focus on language first and be flexible with tools - and to have a good text editor you can rely upon. I started using Textpad first with Java and nowadays I usually don't pass a day when I don't open something with it - either for quick inspection of a file or to write something in perl or python.

I know there are other good text editors out there but it seems like having good regex support and the ability to attach shell commands to keyboard shortcuts is most important. Syntax highlighting is a nicety too although as time passes it's not really as important to me.

}

Tuesday, August 07, 2007

!Normalize

{

Some time ago Jason Kottke posted an entry for which quite a few people bashed him about unnecessary database normalization. I've thought a lot about it since it represents some of my own internal sentiments and instincts. The two things I observe on a regular basis that I find annoying are bad naming conventions within databases and unnecessary complexity because of overzealous normalization.

It's hard to have an argument discussion on the topic with people lacking experience because the penalties for bad normalization are usually paid in the long term whereas the "effeciency" of storage with normalized data seems to be an ideal to strive for when one's perspective is short.

I was therefore heartened to see some caution from Patt Heland (courtesy of Dare Obasanjo who elaborates) on the topic. It may be a good idea to have a meeting at work and discuss some of the details given... maybe not to come to some "conclusion" or "database standard" that can apply to every situation, but more to generate good discussion and ideas.

}

Wednesday, August 01, 2007

Upsert Properly

{

For the longest time, my approach to update/insert logic has been the following:

IF EXISTS(SELECT...) BEGIN
UPDATE...
END
ELSE BEGIN
INSERT...
END

So courtesy of .NET Kicks this gem was very informative which is the same logic but with a cleaner approach. Instead of selecting records first, you attempt to do an update and check afterwards if the @@rowcount is greater than zero - if not the record doesn't exist so you can move logically to an insert.

UPDATE ...

IF @@rowcount = 0 BEGIN
INSERT...
END

Nifty, very nifty.

}

Tuesday, July 31, 2007

Fast Learning, Norvigian Thinking

{

I was looking over Justice Gray's post on becoming a better developer in 6 months and noticed that he had listed Freidl's Mastering Regular Expressions as a one week reading project. I'll preface my comments by admitting I am not the quickest read - unless I'm reading something I don't particularly care about I tend to go it slow no matter what the subject matter.

However.

Not really thinking of connecting the dots I checked in on Jeff Freidl's blog and digging around saw it took him 2.5 years to complete the first edition of the book.

It strikes me as funny that there would be such a disparity in creation and consumption. Of course I may be slow - a big part of my wanting to learn Perl was the desire to have the capacity to "think" in regular expressions - but over the last few years as I've gotten better and better I find it hard to think I could compensate the little projects and tools I've written without the pain and grit of using what I read slowly.

But then again we can all rest assured that there's no rush.

}

Sunday, July 29, 2007

Remove Duplicate Lines In Python

{

I had posted about the set operator in Python with some questions. All that changed today when I wrote a little script to remove duplicate lines from a file. The set operator takes a list and automatically gets rid of duplicate items. Very useful for situations like this:


#!/usr/bin/env python

f = open("c:\\temp\\Original.txt")
f2 = open("c:\\temp\\Unique.txt", "w")
uniquelines = set(f.read().split("\n"))
f2.write("".join([line + "\n" for line in uniquelines]))
f2.close()


}

Saturday, July 21, 2007

Shuffled Arrays

{

One of my weaknesses is that I love puzzles. And once I'm puzzle solving, I usually dwell on the problem beyond its worth. I recently saw a job ad - I'll leave this post disconnected - that had a quiz associated with it. The quiz amounts, basically, to shuffling items in an array (javascript).

My first stab was intuitive, but I wonder if it's the most optimal because it relies on a lot of discarded data. In my loop generating a random order, I essentially go through an undetermined amount of times discarding results that already exist in the randomized array. Additionally the array with random numbers is just for positioning and is probably unnecessary.
Here is the code:


function BuildArray(){
// just builds a random array to work with
var testArray = new Array();
testArray.push('Test 0');
testArray.push('Test 1');
testArray.push('Test 2');
testArray.push('Test 3');
return testArray;
}

function GetShiftOrder(testObject){
// this is what sorts things out
var upperBound = testObject.length;
var newOrder = new Array();
var shuffledArray = new Array();
builder:
while(newOrder.length < upperBound){
n = parseInt(Math.random() * upperBound);
for(i=0;i<newOrder.length;i++){
if(newOrder[i] == n){
continue builder;
}
}
newOrder.push(n);
shuffledArray.push(testObject[n]);
}
alert(newOrder + '\n' + shuffledArray);
}


I was thinking about this today and it may be more effecient to make a random number of passes at the array swapping pairs of items. A shuffling cards approach may be slightly more effecient although to have meaningful swaps there would need to be a minimum number of passes - and additional complexity with making sure pairs were swapped in random pattern.

Anyway, it was interesting and I'm always curious about more elegant solutions.

}

Thursday, July 19, 2007

CodePress

{

I'm taking a serious look at CodePress. Very, very, very cool.

}

Sunday, July 15, 2007

Sieve of Eratosthenes, Python, Set Operations

{

I pretty much broke down after TechEd. I thought I'd be patient enough to wait for Ruby but because Python is most mature I have started to learn it, whitespaces or no.

The first thing I did was check out Guido van Rossum's tutorial for programmers, which was an excellent first step. I've followed that up with some random programming - a lot of fun so far.

I was wondering about the set operations in python and how that made a difference in programming since there aren't syntactical equivalents in .NET. Incidentally at the time I was reading The Man Who Loved Only Numbers and ran across a short description of the Sieve of Eratosthenes as a way of finding primes. I thought it would be a good way to check out the set operations of Python.

I wrote the following:


from System import *

def multiples(num, thresh):
multi = []
for i in range(2,thresh):
m = num * i
if(m < thresh):
multi.append(m)
else:
break
return multi

primeThresh = 5000
print DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss")
nums = range(2,primeThresh)

for n in nums:
nums = set(nums) - set(multiples(n, primeThresh))

print nums

print DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss")


Interesting, but slow. The way I may do something like that in C# (which also works just fine in Python) would be this, which I wrote later:


from System import *

primeThresh = 5000
print DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss")
nums = range(2,primeThresh)

for n in nums:
for m in range(2,primeThresh):
try:
mult = n * m
if(mult > primeThresh):
break
nums.remove(mult)
except:
pass

print nums

print DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss")


It's a lot faster than the previous approach which makes sense - doing set algebra on large sets should take a long time... but that begs the question: are those set operations dangerous (ie. so slow as to be costly).

I'm wondering what's "pythonic" and how a jedi would write this most effeciently.

}

Saturday, July 14, 2007

Being Better

{

I probably won't be officially "tagged" but a meme is going around about what one would do in the next 6 months to become better. Hanselman, in his podcast, spoke of a few things and the responses seem to be going up around the blogs.

How will I be better? Most of the things people mentioned are things I already try to do: reading technical books, working on my software, looking at open source, training others... but one thing I want to do is to start posting code.

I write a lot of code and much of it doesn't make it here because I'm sheepish about looking foolish. But getting better is about having courage to show my work because without that, how could it get any better?

I'm going to start with my JAPH, a program that prints "Just Another Perl Hacker." It's meant to be novel and I actually like mine since it leverages some language features that don't exist in my mainstay, C#. The map operation can visit each item on an array performing some opertion - in this case I'm using a regular expression on each item and grabbing alternating characters! I haven't been writing perl for a long time so hopefully over time I can claim a better one but at least this is my own thinking at play, destined for improvement. I did post it on usenet (a first version which had some foolish mistakes) but this is after a little bit of massage:

#!/usr/bin/perl -w
# David's JAPH, volume 0.1
map(print(/(\w)\w/g," "),
qw(Jaubsctd Aenfogthhiejrk Plemrmln Hoapcqkresrt));


The original JAPHs, from Randall Schwartz, were not really about obfuscation but more about language features. The use of map, regular expressions, and $_ in the above are what make it interesting to me.

}