Tag Archives: .NET

Uncategorized

TestAPI!

Developers should know from experience that in projects of any substantial size (pretty much anything big enough to deliver to a customer or client), there will be a need for little utility programs or libraries and classes to handle routine tasks.  When those moments occur, typically what’s called for is something simple and easy to get up and running, because it’s not very much value-add to whatever it is you’re building.

Take parsing command line arguments for example.  It adds very little of value to the end product, but it’s the kind of thing that winds up being necessary.  It’s a cost of doing business with the computer.  A developer has to decide how to handle addressing the need: start from scratch and handle command line arguments manually — writing JIT code that will very likely become hard to update later on, buy a vendor product?

Most developers are inclined to do the former.  I know I am – developing is what we do!  What’s one more minor thing to build in order to address needs?  The problem with this approach is more systemic than just the downside up ending up with old, crufty code that wasn’t designed well enough to be maintainable later on.  Every developer winds up with their own hand-rolled mini-library for handling the mundane – sometimes more than one!  That represents a lot of duplicated effort and inferior quality.

Of course, what I’ve just done is summarize a large portion of the motivation for open-source software .  More specifically though, I recently discovered TestApi.  It’s just quietly hanging out there on codeplex (written by Microsoft devs on the clock), but it addresses a handful of these mundane infrastructure things that gets in the way of us building software with real value.

I just wish I had known about it a long time ago.

Uncategorized

New Concurrency Support in .NET 4

I’ve been reading about some of the new support for parallelism and concurrency in version 4 of the .NET Framework, and came across a really good paper on parallel design patterns by Steven Toub (most or all of which seems to also be covered in the Parallel Programming with Microsoft .NET book).  There are some really convenient additions to the framework in .NET 4 that help make parallelism easier and less error-prone.  The point of this post is to illuminate a good example of how this is so.

About a year ago, I was working on a class library that was supposed to do some filtering on streams – something along the lines of Boost.Iostreams which gives you the ability to create pluggable, customized “sources” and “sinks” (producers and consumers) and filters set up in a stream pipeline.  One simple application of such a pipeline (and apparently Toub’s favorite) is that of compressing and encrypting some data.

Input is read from the source stream, passed through the filters, and written to the output stream.

I found Toub’s MSDN Magazine article describing how one could parallelize this, and incorporated the sample into my class library.  The basic idea is that you set up a blocking queue of chunks of data, and then use that queue (or queues) to connect the inputs and outputs of the streams and filters, and just let it fly.  The queue serves as the synchronization mechanism, fulfilling the producer role required by the input side of each piece, and fulfilling the consumer role required by the output side of each piece.  Below is the sample code.

read more »

Uncategorized

Lambdas in data-binding expressions

For a recent project, I wrote a templated web part (similar to the Smart Part) to do a search on a custom list and display the results (all using AJAX updates made available by the UpdatePanel), and I found myself unable to accomplish what I needed to accomplish in data-binding expressions inline in the user control loaded by my web part. I needed to be able to do multiple steps to condition the bound data before rendering it (for example, splitting a single field into multiple distinct fields that should be rendered differently).

For example, one of the bound fields I needed to render was a string formatted like this:

"http://www.website.com/page.aspx, Name of the Website"

I needed to render this as a link. Obviously, it won’t directly render properly. It needed to be split, so it could be rendered something like this:

Name of the Website

For this simple example, you can do it all inline without lambdas by taking advantage of the ability to pass an array as a params parameter:

String.Format("{1}",
             1

However, for a more complex case in which the bound data needs conditioning that can’t be done inline, typically you would do your conditioning and rendering in server side code2.

The problem with that is that you then have to write a bunch of methods that kind of pollute your other classes, and your logic is divided (some in the user control, some in a class). Enter lambdas.

Data-binding expressions are somewhat restrctive in that they can only evaluate DataBinder.Eval and DataBinder.Bind. DataBinder is the context of the expression. However, you can create a new context by writing an inline lambda, like this:

() =>
{
  string url =3.  Somehow, we have to cause this method to be invoked.

My suggestion is to write a server-side method for invoking the lambda.

public delegate string DbExprDelegate();

public static string DbExpr(DbExprDelegate lambda)
{
  var obj = lambda.Invoke();
  return obj;
}

To get the type system to go along, you have to define a delegate type for the lambda. In my case, I knew I would be taking no arguments and returning no strings. For more complex cases you may be able to make good use of generics and type inference to write a more useful generalization. Since lambdas are implicitly convertible to compatible delegates, you can then use the static method DbExpr in your data binding expression to invoke the lambda. I defined DbExpr in my web part class, but I could have put it just it just about anywhere because my user control has no reference to the web part object that loads it, which requires my DbExpr to be static. In other contexts where data binding expressions are used, you may have references to instance objects in your context and may not need to make your DbExpr static.

Finally, we now have the plumbing we need to make the data binding expression work:

<%@ Assembly Name="MyAssembly, etc, etc." %>
<%@ Import Assembly="MyAssembly" Namespace="MyNamespace" %>
 
<%#
MyWebPartControl.DbExpr(() =>
  {
    string url = ((SPListItem)Container.DataItem)["WebPage"].ToString();
    string toks[] = url.Split(new string[] {", "},
                              StringSplitOptions.RemoveEmptyEntries);
    return String.Format("{1}", toks[0], toks[1]);
  })
%>

  1. SPListItem)Container.DataItem)["WebPage"] .ToString().Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries []
  2. Of course, the term “server-side” here doesn’t imply that inline expressions are executed on the client – they aren’t. It’s just a way to distinguish between code organized into class libraries and inline expressions embedded into ASP.NET files, like user controls. []
  3. SPListItem)Container.DataItem)["WebPage"].ToString(); string toks[] = url.Split(new string[] {", "}, StringSplitOptions.RemoveEmptyEntries); return String.Format("{1}", toks[0], toks[1]); }

Now you can see more clearly what it is you’re doing, and as an added bonus, you can actually set breakpoints on each individual statement and inspect local variables (an option that’s unavailable with chained expressions).

There’s a problem, though. The result of this expression is a lambda, not a string. When the page is hit and the server tries to compile this, it may fail. Even if it didn’t, the rendered result would not be desirable ((the lambda’s .ToString() method would be called, and the result would be what the end-user would seee []