Maarten Balliauw {blog}

ASP.NET MVC, Microsoft Azure, PHP, web development ...

NAVIGATION - SEARCH

Microsoft Web Development Summit 2009

PHP at Microsoft Being in the US for 2 times in a month (PDC09 and Web Development Summit) is fun, tiring and rewarding. The WDS09 was an invite-only event organized by Microsoft, focusing on interaction between Microsoft and the PHP community. I must say: the event has been helpful and interesting for both parties!

  • The Heathman Hotel in Kirkland is a nice hotel!
  • Traveling towards the US is far more productive than flying back: I did PHPMEF traveling westbound, I crashed (half sleep/half awake) on the eastbound flight…
  • If you just traveled over 26 hours: do NOT go shopping immediately when you arrive home! It’s really frustrating and tiring.
  • Did a session on Windows Azure SDK for PHP, PHPExcel and PHPLinq.
  • Did an interview for the Connected Show
  • Met a lot of people I knew from Twitter and e-mail, and met a lot of new people, both Microsoft and PHP community. Nice to meet you all!
  • Event focus was on feedback between Microsoft and PHP community, overall I think the dialogue was respectful and open and helpful to both parties.

Standing at the Microsoft logo

This was actually my first time at the WDS which has been around for 5 years already. The Interop team invited me there, and I want to thank them for doing that: it was a great trip, a great event and I got the chance to meet lots of new people.

Attendees were mostly people from the PHP community, like Cal Evans, Rafael Doms, Chris Cornutt, Romain Bourdon (WAMP server anyone?), Alison “snipe” Gianotto, … Next to that, lots of Microsoft people came by during various sessions. Some of them even reserved the whole week and were attending all sessions to make sure they were in the feedback loop all the time.

We’ve seen Microsoft sessions on IIS, Web Platform Installer, Silverlight, SQL Server, Bing, Powershell (sorry, Scott Hanselman, for disturbing your presentation with a tweet :-)). Interesting sessions with some info I did not know. PHP community sessions were also available: Wordpress, Joomla, Drupal, the PHP community perspective, feedback sessions, PHPLinq, PHPExcel, interoperability bridges, … A good mix of content with knowledgeable speakers and good communication between speakers, product groups and audience. Well done!

Query the cloud with PHP (PHPLinq and Windows Azure)

PHPLinq Architecture I’m pleased to announce PHPLinq currently supports basic querying of Windows Azure Table Storage. PHPLinq is a class library for PHP, based on the idea of Microsoft’s LINQ technology. LINQ is short for language integrated query, a component in the .NET framework which enables you to perform queries on a variety of data sources like arrays, XML, SQL server, ... These queries are defined using a syntax which is very similar to SQL.

Next to PHPLinq querying arrays, XML and objects, which was already supported, PHPLinq now enables you to query Windows Azure Table Storage in the same manner as you would query a list of employees, simply by passing PHPLinq a Table Storage client and table name as storage hint in the in() method:

[code:c#]

$result = from('$employee')->in( array($storageClient, 'employees', 'AzureEmployee') )
            ->where('$employee => $employee->Name == "Maarten"')
            ->select('$employee');

[/code]

The Windows Azure Table Storage layer is provided by Microsoft’s PHP SDK for Windows Azure and leveraged by PHPLinq to enable querying “the cloud”.

kick it on DotNetKicks.com

PHPLinq 0.4.0 released on CodePlex!

PHPLinq I’m pleased to announce that PHPLinq 0.4.0 has been released on CodePlex. PHPLinq is currently one year old, and I decided to add a huge step in functionality for the 0.4.0 release. This blog post will focus on the current status of PHPLinq and what it is capable of doing for you in a PHP project.

 

What is PHPLinq?

PHPLinq is a class library for PHP, based on the idea of Microsoft’s LINQ technology. LINQ is short for language integrated query, a component in the .NET framework which enables you to perform queries on a variety of data sources like arrays, XML, SQL server, ... These queries are defined using a syntax which is very similar to SQL.

Using PHPLinq, the same functionality is created in PHP. Since regular LINQ applies to enumerators, SQL, datasets, XML, ..., I decided PHPLinq should provide the same infrastructure. Here’s an example PHPLinq query, which retrieves all names with a length less than 5 from an array of strings:

[code:c#]

// Create data source
$names = array("John", "Peter", "Joe", "Patrick", "Donald", "Eric");

$result = from('$name')->in($names)
            ->where('$name => strlen($name) < 5')
            ->select('$name');

[/code]

Notice the in()-function? This is basically a clue for PHPLinq to determine how t query data. In this case, PHPLinq will work with a string array, but is perfectly possible to hint PHPLinq with a database table, for example. I’ll show you more on that later in this post.

PHPLinq components

This functionality is achieved by the fact that each PHPLinq query is initiated by the PHPLinq_Initiator class. Each PHPLinq_ILinqProvider implementation registers itself with this initiator class, which then determines the correct provider to use. This virtually means that you can write unlimited providers, each for a different data type!

PHPLinq architecture

What can I do with PHPLinq?

Basically, PHPLinq is all about querying data. No matter if it’s an array, XML tree or a database table, PHPLinq should be able to figure out what to do witht the data, without you being required to write complex foreach loops and stuff like that.

Querying data from an array

Let’s have a look at an example. The following array will be a dataset which we’ll be working with. It is a list of Employee objects.

[code:c#]

// Employee data source
$employees = array(
    new Employee(1, 1, 5, 'Maarten', 'maarten@example.com', 24),
    new Employee(2, 1, 5, 'Paul', 'paul@example.com', 30),
    new Employee(3, 2, 5, 'Bill', 'bill.a@example.com', 29),
    new Employee(4, 3, 5, 'Bill', 'bill.g@example.com', 28),
    new Employee(5, 2, 0, 'Xavier', 'xavier@example.com', 40)
);

[/code]

I would like to have the name and e-mail address of employees named “Bill”. Here’s a PHPLinq query:

[code:c#]

$result = from('$employee')->in($employees)
            ->where('$employee => substr($employee->Name, 0, 4) == "Bill"')
            ->select('new {
                    "Name" => $employee->Name,
                    "Email" => $employee->Email
                  }');

[/code]

Wow! New things here! What’s this $employee => … thing? What’s this new { … } thing? The first is a lambda expression. This is actualy an anonymous PHP function we are creating, accepting a parameter $employee. This function returns a boolean (true/false), based on the employee’s name. The new { … } thing is an anonymous class constructor. What we are doing here is defining a new class on-the-fly, with properties Name and Email, based on data from the original $employee.

Here’s the output of the above query:

[code:c#]

Array
(
    [0] => stdClass Object
        (
            [Name] => Bill
            [Email] => bill.a@example.com
        )
    [1] => stdClass Object
        (
            [Name] => Bill
            [Email] => bill.g@example.com
        )
)

[/code]

How cool is that! Things are getting a lot cooler when we use PHPLinq together with the Zend Framework’s Zend_Db_Table

Querying data from a database

PHPLinq has a second PHPLinq_ILinqProvider built in. This provider makes use of the Zend Framework Zend_Db_Table class to provide querying capabilities. First things first: let’s create a database table.

[code:c#]

CREATE TABLE employees (
    Id                INTEGER NOT NULL PRIMARY KEY,
    DepartmentId    INTEGER,
    ManagerId        INTEGER,
    Name            VARCHAR(100),
    Email            VARCHAR(200),
    Age                INTEGER
);

[/code]

We’ll be using this table in a Zend_Db_Table class:

[code:c#]

// EmployeeTable class
class EmployeeTable extends Zend_Db_Table {
    protected $_name = 'employees'; // table name
    protected $_primary = 'Id';
}
$employeeTable = new EmployeeTable(array('db' => $db));
$employeeTable->setRowClass('Employee');

[/code]

Allright, what happened here? We’ve created a database table, and told Zend_Db_Table to look in the employees table for data, and map these to the Employee class we created before. The Zend_Db_Table employee table will be accessible trough the $employeesTable variable.

Ok, let’s issue a query:

[code:c#]

$result = from('$employee')->in($employeesTable)
            ->where('$employee => substr($employee->Name, 0, 4) == "Bill"')
            ->select('new {
                    "Name" => $employee->Name,
                    "Email" => $employee->Email
                  }');

[/code]

Here’s the output of the above query:

[code:c#]

Array
(
    [0] => stdClass Object
        (
            [Name] => Bill
            [Email] => bill.a@example.com
        )
    [1] => stdClass Object
        (
            [Name] => Bill
            [Email] => bill.g@example.com
        )
)

[/code]

Did you notice this query is actually the same as we used before? Except for the $employeesTable now being used instead of $employees this query is identical! The only thing that is different, is how PHPLinq handles the query internally. Using the array of objects, PHPLinq will simply loop the array and search for correct values. Using Zend_Db_Table, PHPLinq actually builds a SQL query which is executed directly on the database server, delegating performance and execution to the database engine.

We can have a look at the generated query by setting an option on PHPLinq, which will tell PHPLinq to pass the generated query to PHP’s print function.

[code:c#]

PHPLinq_LinqToZendDb::setQueryCallback('print');

[/code]

Let’s run the previous query again. The console will now also display the generated SQL statement:

[code:c#]

SELECT "$employee".* FROM "employees" AS "$employee" WHERE (SUBSTR('$employee'."Name",  0,  4)  =  "Bill")

[/code]

Cool! Are you kidding me?!? PHPLinq just knew that the PHP code in my where clause translates to the above SQL statement! It’s even cooler than this: PHPLinq also knows about different databases. The above example will translate to another query on a different database engine. For that, let’s look at another example. Here’s the PHPLinq query:

[code:c#]

$result = from('$employee')->in($employeeTable)
            ->where('$employee => trim($employee->Name) == "Bill"')
            ->select('$employee->Name');

[/code]

The generated SQL statement in SQLite:

[code:c#]

SELECT "$employee".* FROM "employees" AS "$employee" WHERE (TRIM('$employee'."Name")  =  "Bill")

[/code]

The generated SQL statement in Microsoft SQL Server (only knows LTRIM() and RTRIM(), not TRIM()):

[code:c#]

SELECT "$employee".* FROM "employees" AS "$employee" WHERE (LTRIM(RTRIM('$employee'."Name"))  =  "Bill")

[/code]

I don't know about you, but I think this is very useful (and COOL!)

Querying data from an XML source

Here’s another short example, just to be complete. Let's fetch all posts on my blog's RSS feed, order them by publication date (descending), and select an anonymous type containing title and author. Here's how:

[code:c#]

$rssFeed = simplexml_load_string(file_get_contents('http://blog.maartenballiauw.be/syndication.axd'));
$result = from('$item')->in($rssFeed->xpath('//channel/item'))
            ->orderByDescending('$item => strtotime((string)$item->pubDate)')
            ->take(2)
            ->select('new {
                            "Title" => (string)$item->title,
                            "Author" => (string)$item->author
                      }');

[/code]

Where to go now?

There’s lots of other features in PHPLinq which I covered partially in previous blog posts (this one and this one). For full examples, download PHPLinq from www.phplinq.net and see for yourself.

By the way, PHPExcel (another project of mine) and PHPLinq seem to be listed in Smashing Magazine's Top 50 list of extremely useful PHP tools. Thanks for this recognition!

New Entity Framework / LINQ blog!

Just a quick recommendation note: One of my colleagues, Julien Hanssens, has started blogging on his experiences with the Entity Framework and LINQ. Here are some links to get you started:

  • Entity Framework - ArgumentException on Connection
    "A common error while initialising an EntityModel from a WCF Service is the following message: ArgumentException was unhandled by user code - The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid. "
     
  • Entity Framework and Stored Procedures
    "SQL Server has a large fanbase of stored procedures enthusiasts. Including obviously DBA's, but also developers. The latter foremost considering that with storedprocs you can easily shovel responsibility at those who are responsible for maintaining data-integrity.

    Unfortunately, the ADO.NET Entity Framework in its current version has some limitations when working with stored procedures. How to cope with this?"
     
  • LINQ and Dynamic Query Expressions
    "By tradition it was always quite a challenge to create custom filtering on objects and dynamically query databases. Or to say least a lot of work. LINQ makes this type of querying in code much easier. In this article I wish to elaborate on the "how-to" and advantages of providing a dynamic and type-safe 'engine' for developers on which you can query any random property.

    We are going to demonstrate this by using an expression tree, available from the System.Linq.Expressions namespace, to easily achieve dynamic LINQ queries for usage in your code."

kick it on DotNetKicks.com

Heroes happen here - Microsoft TechDays 2008 in Belgium

Microsoft TechDays 2008

Dolmen polo Just to inform you: together with a numer of colleagues from Dolmen, I'll be attending the Microsoft TechDays 2008 in Ghent, Belgium on 12 and 13 March 2008. Want to spot me, Joris, Jeroen, Danny, ... and meet in person? Search for one of the guys in a Dolmen shirt!

Update 17/03/2008: Jeroen posted an overview of the inspiring sessions on his blog. 

PHPLinq version 0.2.0 released!

Last friday, I released PHPLinq version 0.2.0. LINQ, or Language Integrated Query, is a component inside the .NET framework which enables you to perform queries on a variety of data sources like arrays, XML, SQL server, ... These queries are defined using a syntax which is very similar to SQL.

This latest PHP version of LINQ provides almost all language constructs the "real" LINQ provides. Since regular LINQ applies to enumerators, SQL, datasets, XML, ..., I decided PHPLinq should provide the same infrastructure. Each PHPLinq query is therefore initiated by the PHPLinq_Initiator class. Each PHPLinq_ILinqProvider implementation registers itself with this initiator class, which then determines the correct provider to use. This virtually means that you can write unlimited providers, each for a different data type! Currently, an implementation on PHP arrays is included.

PHPLinq class diagram 

Being able to query PHP arrays is actually very handy! Let's say you have a mixed array containing Employee objects and some other data types. Want only Employee objects? Try this one!

[code:c#]

$result = from('$employee')->in($employees)
            ->ofType('Employee')
            ->select();

[/code]

Want to know if there's any employee age 12? Easy! The following query returns true/false:

[code:c#]

$result = from('$employee')->in($employees)->any('$employee => $employee->Age == 12');

[/code]

Let's do something a little more advanced... Let's fetch all posts on my blog's RSS feed, order them by publication date (descending), and select an anonymous type containing title and author. Here's how:

[code:c#]

$rssFeed = simplexml_load_string(file_get_contents('http://blog.maartenballiauw.be/syndication.axd'));
$result = from('$item')->in($rssFeed->xpath('//channel/item'))
            ->orderByDescending('$item => strtotime((string)$item->pubDate)')
            ->take(2)
            ->select('new {
                            "Title" => (string)$item->title,
                            "Author" => (string)$item->author
                      }');

[/code]

Download LINQ for PHP (PHPLinq) now and get familiar with it. Since I started working on PHPLinq, I also noticed LINQ implementations for other languages:

Books I recently read...

A while ago, I was contacted by the people of Packt Publishing asking me to review two of their latest books, ASP.NET Data Presentation Controls Essentials (by Joydip Kanjilal) and LINQ Quickly (by N. Satheesh Kumar). Since both books stated something about LINQ on the back-cover, and me wanting to read more on that matter, I engaged into reviewing them.

ASP.NET Data Presentation Controls Essentials

image Being an ASP.NET developer, I'm not new to ASP.NET's data bound controls. Upon receiving the book, I immediately knew this was not going to be new stuff to me, a thought which proved right. Nevertheless, the book has a value!

The author starts with a birds-eye overview of all data bound controls in ASP.NET, allowing the reader to immediately know what's possible with these controls. In the next chapters, each control is covered with some examples. Luckily, the book did not contain "full" examples yet short, to-the-point code snippets delivering a practical approach to solving a specific data binding scenario.

This leads me to agreeing with the author that "this book is not for beginners". Some snippets contain small typo's, and because a full frame around these snippets is missing, someone new to C# and ASP.NET will have some problems creating their own examples based on the book. It's also not for professionals to learn much new things, but I think anyone familiar with a C# background wanting to start data bound ASP.NET development can benefit from this no-nonsense quickstart book.

For me, this book will find a place on my book shelf along with other reference books, as it covers all data binding scenario's from ASP.NET 1.1 over ASP.NET 2.0 up to some snippets of data binding to LINQ data sources.

LINQ Quickly

image Since the release of the Microsoft .NET framework 3.5 a few months ago, I've been playing around with LINQ (Language Integrated Query) a couple of times. It is a uniform method of accessing any type of data (Collections, XML, database, ...) in a "natural" way.

The book covers all concepts of LINQ. It starts with an overview of all language elements that have been added to the .NET framework in order to enable the use of LINQ, such as anonymous types, object/collection initializers, expressions, partial methods, ... The next chapters all cover a LINQ implementation such as LINQ to Objects, LINQ to SQL, LINQ to Entities, LINQ to XML, LINQ to DataSets, ... The last chapter gives an overview of all LINQ methods and their use with a short code example that immediately clarifies the purpose of each method.

I found the LINQ to Entities chapter quite interesting, as it clearly explains how to create your class diagram using the right decorators for generating a database schema. Another useful thing are the appendices near the end of the book, covering LINQ to "anything" (there's an example on LINQ to Outlook Contacts).

To be honest, I'm quite enthousiast about this book. If you are a .NET developer and looking for a "one-night read" to-the-point book about LINQ and all related matter, this book is your friend!

LINQ for PHP (Language Integrated Query for PHP)

Perhaps you have already heard of C# 3.5's "LINQ" component. LINQ, or Language Integrated Query, is a component inside the .NET framework which enables you to perform queries on a variety of data sources like arrays, XML, SQL server, ... These queries are defined using a syntax which is very similar to SQL.

There is a problem with LINQ though... If you start using this, you don't want to access data sources differently anymore. Since I'm also a PHP developer, I thought of creating a similar concept for PHP. So here's the result of a few days coding:

PHPLinq - LINQ for PHP - Language Integrated Query

A basic example

Let's say we have an array of strings and want to select only the strings whose length is < 5. The PHPLinq way of achieving this would be the following:

[code:c#]

// Create data source
$names = array("John", "Peter", "Joe", "Patrick", "Donald", "Eric");

$result = from('$name')->in($names)
            ->where('$name => strlen($name) < 5')
            ->select('$name');

[/code]

Feels familiar to SQL? Yes indeed! No more writing a loop over this array, checking the string's length, and adding it to a temporary variable.

You may have noticed something strange... What's that $name => strlen($name) < 5 doing? This piece of code is compiled to an anonymous function or Lambda expression under the covers. This function accepts a parameter $name, and returns a boolean value based on the expression strlen($name) < 5.

An advanced example

There are lots of other examples available in the PHPLinq download, but here's an advanced one... Let's say we have an array of Employee objects. This array should be sorted by Employee name, then Employee age. We want only Employees whose name has a length of 4 characters. Next thing: we do not want an Employee instance in our result. Instead, the returning array should contain objects containing an e-mail address and a domain name.

First of all, let's define our data source:

[code:c#]

class Employee {
    public $Name;
    public $Email;
    public $Age;

    public function __construct($name, $email, $age) {
        $this->Name     = $name;
        $this->Email     = $email;
        $this->Age        = $age;
    }
}

$employees = array(
    new Employee('Maarten', 'maarten@example.com', 24),
    new Employee('Paul', 'paul@example.com', 30),
    new Employee('Bill', 'bill.a@example.com', 29),
    new Employee('Bill', 'bill.g@example.com', 28),
    new Employee('Xavier', 'xavier@example.com', 40)
);

[/code]

Now for the PHPLinq query:

[code:c#]

$result = from('$employee')->in($employees)
            ->where('$employee => strlen($employee->Name) == 4')
            ->orderBy('$employee => $employee->Name')
            ->thenByDescending('$employee => $employee->Age')
            ->select('new {
                    "EmailAddress" => $employee->Email,
                    "Domain" => substr($employee->Email, strpos($employee->Email, "@") + 1)
                  }');

[/code]

Again, you may have noticed something strange... What's this new { } thing doing? Actually, this is converted to an anonymous type under the covers. new { "name" => "test" } is evaluated to an object containing the property "name" with a value of "test".

This all sounds intuitive, interesting and very handy? Indeed! Now make sure you download a copy of PHPLinq today, try it, and provide the necessary feedback / feature requests on the CodePlex site.

Preview Word files (docx) in HTML using ASP.NET, OpenXML and LINQ to XML

Since an image (or even an example) tells more than any text will ever do, here's what I've created in the past few evening hours:

image

Live examples:

Want the source code? Download it here: WordVisualizer.zip (357.01 kb)

Want to know how?

If you want to know how I did this, let me first tell you why I created this. After searching Google for something similar, I found a Sharepoint blogger who did the same using a Sharepoint XSL transformation document called DocX2Html.xsl. Great, but this document can not be distributed without a Sharepoint license. The only option for me was to do something similar myself.

ASP.NET handlers

The main idea of this project was to be able to type in a URL ending in ".docx", which would then render a preview of the underlying Word document. Luckily, ASP.NET provides a system of creating HttpHandlers. A HttpHandler is the class instance which is called by the .NET runtime to process an incoming request for a specific extension. So let's trick ASP.NET into believing ".docx" is an extension which should be handled by a custom class...

Creating a custom handler

A custom handler can be created quite easily. Just create a new class, and make it implement the IHttpHandler interface:

[code:c#]

/// <summary>
/// Word document HTTP handler
/// </summary>

public class WordDocumentHandler : IHttpHandler
{
    #region IHttpHandler Members

    /// <summary>
    /// Is the handler reusable?
    /// </summary>

    public bool IsReusable
    {
        get { return true; }
    }

    /// <summary>
    /// Process request
    /// </summary>
    /// <param name="context">Current http context</param>

     public void ProcessRequest(HttpContext context)
    {
        // Todo...

        context.Response.Write("Hello world!");
    }

    #endregion
}

[/code]

Registering a custom handler

For ASP.NET to recognise our newly created handler, we must register it in Web.config:

image

Now if you are using IIS6, you should also register this extension to be handled by the .NET runtime:

image

In the application configuration, add the extension ".docx" and make it point to the following executable: C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll

This should be it. Fire up your browser, browse to your web site and type anything.docx. You should see "Hello world!" appearing in a nice, white page.

OpenXML

As you may already know, Word 2007 files are OpenXML packages containg WordprocessingML markup. A .docx file can be opened using the System.IO.Packaging.Package class (which is available after adding a project reference to WindowsBase.dll).

The Package class is created for accessing any OpenXML package. This includes all Office 2007 file formats, but also custom OpenXML formats which you can implement for yourself. Unfortunately, if you want to use Package to access an Office 2007 file, you'll have to implement a lot of utility functions to get the right parts from the OpenXML container.

Luckily, Microsoft released an OpenXML SDK (CTP), which I also used in order to create this Word preview handler.

LINQ to XML

As you know, the latest .NET 3.5 release brought us something new & extremely handy: LINQ (Language Integrated Query). On Doug's blog, I read about Eric White's attempts to use LINQ to XML on OpenXML.

LINQ to OpenXML

For implementing my handler, I basically used similar code to Eric's to run query's on a Word document's contents. Here's an example which fetches all paragraphs in a Word document:

[code:c#]

using (WordprocessingDocument document = WordprocessingDocument.Open("test.docx", false))
{
    // Register namespace

    XNamespace w = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";

    // Element shortcuts

    XName w_r = w + "r";
    XName w_ins = w + "ins";
    XName w_hyperlink = w + "hyperlink";

    // Load document's MainDocumentPart (document.xml) in XDocument

    XDocument xDoc = XDocument.Load(
        XmlReader.Create(
            new StreamReader(document.MainDocumentPart.GetStream())
        )
    );

    // Fetch paragraphs

    var paragraphs = from l_paragraph in xDoc
                    .Root
                    .Element(w + "body")
                    .Descendants(w + "p")
         select new
         {
             TextRuns = l_paragraph.Elements().Where(z => z.Name == w_r || z.Name == w_ins || z.Name == w_hyperlink)
         };

    // Write paragraphs

    foreach (var paragraph in paragraphs)
    {
        // Fetch runs

        var runs = from l_run in paragraph.Runs
                   select new
                   {
                       Text = l_run.Descendants(w + "t").StringConcatenate(element => (string)element)
                   };

        // Write runs

        foreach (var run in runs)
        {
            // Use run.Text to fetch a text string

            Console.Write(run.Text);
        }
    }
}

[/code]

Now if you run this code, you will notice a compilation error... This is due to the fact that I used an extension method StringConcatenate.

Extension methods

In the above example, I used an extension method named StringConcatenate. An extension method is, as the name implies, an "extension" to a known class. In the following example, find the extension for all IEnumerable<T> instances:

[code:c#]

public static class IEnumerableExtensions
{
    /// <summary>
    /// Concatenate strings
    /// </summary>
    /// <typeparam name="T">Type</typeparam>
    /// <param name="source">Source</param>
    /// <param name="func">Function delegate</param>
    /// <returns>Concatenated string</returns>

    public static string StringConcatenate<T>(this IEnumerable<T> source, Func<T, string> func)
    {
        StringBuilder sb = new StringBuilder();
        foreach (T item in source)
            sb.Append(func(item));
        return sb.ToString();
    }
}

[/code]

Lambda expressions

Another thing you may have noticed in my example code, is a lambda expression:

[code:c#]

z => z.Name == w_r || z.Name == w_ins || z.Name == w_hyperlink.

[/code]

A lambda expression is actually an anonymous method, which is called by the StringConcatenate extension method. Lambda expressions always accept a parameter, and return true/false. In this case, z is instantiated as an XNode, returning true/false depending on its Name property.

Wrapping things up...

If you read this whole blog post, you may have noticed that I extensively used C# 3.5's new language features. I combined these with OpenXML and ASP.NET to create a useful Word document preview handler. If you want the full source code, download it here: WordVisualizer.zip (357.01 kb).

kick it on DotNetKicks.com

LINQ to filesystem

The past few hours, I've been experimenting with LINQ. As a sample application, I'm trying to create a small photo album website, which shows me all images in a specific folder on my webserver.

What does LINQ have to do with that? Everyone has used a loop over all files in a folder, and I decided to try LINQ for that matter. Here's how:

[code:c#]

var rootFolder = "C:\\";
var selectedImages = from file in Directory.GetFiles(rootFolder, "*.jpg")
                             select new { Path = file,
                                          Name = new FileInfo(file).Name,
                                          CreationDate = new FileInfo(file).CreationTime,
                                          DirectoryName = new FileInfo(file).DirectoryName
                                    };

[/code]

There you go! A collection named "selectedImages", filled with anonymous class instances containg a file Path, Name, CreationDate and DirectoryName. This collection can now be bound to, for example, a GridView:

[code:c#]

this.gridView1.DataSource = selectedImages;
this.gridView1.DataBind();

[/code]

EDIT: (mental note to myself: add LINQ keywords to syntax highlighter...) - done!