Sunday, August 31, 2008

Linq brings back lisp memories

Often when I am searching for the most succinct way to write logic, I find myself using a declarative syntax:


public ExecutionOutcome GetValidationMessages()
{
IEnumerable<ExecutionOutcome> failedExecutionOutcomes = Context.ItemGroups
.Where(x=>x.IsValid==false)
.Select(x=>ExecutionOutcome.CreateFailureOutcome(
string.Format(
"...",
x.ItemGroupName
)
)
);
if(failedExecutionOutcomes.Count()>0)
{
return ExecutionOutcome.CreateFailureOutcome(failedExecutionOutcomes.Aggregate(string.Empty, (x,y) => x += y.Message + System.Environment.NewLine));
}
return ExecutionOutcome.CreateSuccessfulOutcome();
}


Thats relatively "cutting edge" the C# crew, but its language concept is about as old as the hills. Here is the ballpark equivalent in LISP, a language concieved in the late 50's.

(apply
(GetMessage '#),
(mapcar
(lambda (x)
(if (IsValid x)
nil,
(CreateExecutionFailureOutcome("..." (ItemGroupName x))),
)
),
(ItemGroups Context)
)
)

Lisp was a little on the cryptic side, but its true power was its declarative syntax. Lisp is a "functional language".

C# is a sequential language, with declarative extensions. Linq gives me the ability to jump in and out of "functional language" mode in C#. I find myself gradually turning back into a LISP programmer :)

One thing I wish I could do is take this kind of declarative power and apply it to SQL query plans, now that would impress me.

Tuesday, August 19, 2008

Sharepoint C# HTML Trick: Is this fluent programming or sleazy hack?

The challenge: writing custom sharepoint web-parts can be painful because there is no inline code markup. (and I'm NOT using the "smart part" )

How to write HTML using nothing but C#?
HTML is a tree just like any other AST.

This is the code I wanted to write:


<asp:Table Width="100%">
<asp:TableRow>
<asp:TableCell Width="100%" CssClass="headerRow">Alphabetical Search</asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableCell Width="100%">
<asp:GridView runat="server" Width="100%" />
</asp:TableCell>
</asp:TableRow>
</asp:Table>



This is the code equivalent (plus databinding) using fluent constructors using C#:


protected override void CreateChildControls()

{

var dataFeed = new List

{

"one",

"two",

"three"

};

var gridView = new GridView

{

Width = new Unit("100%"),

DataSource = dataFeed,

Visible = true

};

gridView.DataBind();

var table = new Table

{

Width = new Unit("100%"),

Rows =

{

new TableRow

{

Cells =

{

new TableCell

{

Text = "Alphabetical Search",

CssClass = "headerRow"

}

}

},

new TableRow

{

Cells =

{

new TableCell

{

Controls =

{

gridView

}

}

}

}

}

};

Controls.Add(table);

base.CreateChildControls();

}




Nothing earth shattering here, but I actually dont mind using this syntax. This is the result:







Do you like it?

Labels: , ,