All sorts of nitty-gritty technical things.

Displaying latest wordpress post on ‘random’ Web Page

Our client’s brief was to display their latest blog post on their main web page in a truncated form, their main web page is not part or their blog.  After a little searching I came across a wordpress plugin called Get-a-Post which seemed to promise just what we required.

 

It will retrieve a post, and sets the post’s data up correctly so that wordpress functions like the_title() and the_content() which must normally be called from within the wordpress loop can be called by php code that is outside of the wordpress loop, this is important to us as we want to display the data on a web page which is not part of the actual wordpress blog – from a ‘random’ page.

 

To install the plugin, just download it, and copy get-a-post.php to the blog’s wp-content/plugins/ directory.  Then goto the wordpress admin/plugins screen and activate it.

 

Once the plugin has been activated, its function get_a_post() can be called from any php script, if called with no parameters the latest post will be made active – perfect!  Before calling it make sure to include/require ‘wp-config.php’.  Here is an example script that gets the latest post’s title and content and packages it up into a div and some spans:

 

<?php require_once(“./wp-config.php”); ?>

<?php get_a_post(); ?>
<div class=”last_post_div”>
<span class=”last_post_title”><?php the_title()?></span> – <span class=”last_post_content”>
<?php echo get_the_content(); ?>
</span>
</div>

Get full Worpress Content from a Post with ‘More’ block

The wordpress php function get_the_content(), when called from within the wordpress ‘loop’ will usually return the current post’s content – ‘very handy’ I hear you cry!  Indeed, but all is not as simple as it may seem.  If there is a <!–More–> block in the post it will not return the full text but instead will return some of the text with a link like ‘read more…’ inserted (what is displayed can be controled by an argument to the function). This is fine _unless_ you actually want to get the post’s full contents!!

 

Finding the answer to this seemingly simple question nearly drove me mad, but I eventually found a solution, there is a global flag called $more, setting this to 1 before calling get_the_content() or the_content() etc. will result in the <!–more–> blocks not being processed and all of the post’s text will be returned!

 

global $more;
$more = 1;
$content = get_the_content();        

Implicit Cast of Lambda Expression to Custom Class in C# 3.0?

We hit a little speed bump in our work with parameter-less lambdas – we wanted to be able to assign them to objects of a custom class via an implicit cast, this is very important to our cunning plan…

 

To illustrate this consider the following class that just encapsulates a 0-arity delegate Func<T>:

    public class RuleProp<T>
    {
        private Func<T> _lambda = null;
        public RuleProp(Func<T> l)
        {
            _lambda = l;
        }
        public static implicit operator RuleProp<T>(Func<T> l)
        {
            return new RuleProp<T>(l);
        }
        public RuleProp()
        {
        }
    }

Now, because we have specified an implicit cast for: Func<T> -> RuleProp<T>, it would seem  that we should be able to do the following:

var rp = new RuleProp<string>();
rp = () => "hello"; // Not OK, can't convert lambda to delegate 

But this gives us a compiler error, can’t convert lambda to Fun<T> as it’s not a delegate!!  Looking at the C# specification it seems that if more than one implicit conversion is required, the C# compiler will only do one.  In this case 2 conversions are required:

 

Lambda Expression -> Func<T> -> RuleProp<T>

 

And so the compiler can’t handle it.  If we provide an explicit cast to Func<T> it compiles OK:

 

rp = (Func<string>)(() => "hello");  // Cast works..

 

But this is really ugly as the type must be provided each time.  A workaround was suggested in this article:

 

http://www.interact-sw.co.uk/iangblog/2008/03/17/lambda-inference

 

We provide an ‘adaptor’ function which encourages a cast from Lambda -> Func<T>, and the implicit cast from Func<T> to RuleProp<T> will handle the rest, we can use it like this:

 

rp = Adaptor(() => "hello");  // Now OK!

This is much nicer than the explicit cast as no type needs to be specified!  Here is the function, it just take,s and directly returns a delegate – resulting in just the conversion that we need!

 

public static Func<T> Adaptor<T>(Func<T> f)
{
 return f;
}

 

So although it is not as nice as directly assigning a lambda to RuleProp<T> it’s a grand workaround and will do nicely for the time being – thanks to all at the C# MSDN forum for their help!

Programatically Converting a Literal into an equivalent Lambda Expression in c#3.0

As part of a project that we are working on at the moment  we need a way of converting a literal or constant into a lambda expression which when evaluated will yield the original literal value (in c#).  This must work in the same way for multiple types.

 

For example given the literal string “hello” we need to programmatically create the lambda

 

() => “hello”

 

and for the boolean true we want to create:

 

() => true

 

etc.

 

This can be achieved by creating an appropriate expression tree and then compiling it into a lambda expression, and as we want this to work for different types we wrap all of this into a generic function like the following:

 

        static public Func<T> ToLambda<T>(T val)
        {
            ConstantExpression body = Expression.Constant(val);
            LambdaExpression exp = Expression.Lambda<Func<T>>(body, null);

 

            return (Func<T>)exp.Compile();
        }

 

The function takes the value in question as type T and returns a parameter-less delegate of return type T.  It uses the passed value to create a ConstantExpression, and then uses it to create a LambdaExpression, as the required lambda has no paramters it passes ‘null’ into the constructor’s second parameter.  Now all that is left is to compile the LambdaExpression, this creates and returns the required delegate which is then returned.

 

The following code shows the lambda generator in action:

 

        static public void TestLiteralToLambda()
        {
            // Create the Lambda from literal
            var boolLambda = ToLambda(true);
            // Evaluate the lambda..
            bool boolVal = boolLambda();
            // and, log out some info
            Console.WriteLine(“Lambda evaluates to – {0}”, boolVal);

 

            var stringLambda = ToLambda(“Rainy day in Dublin”);
            string stringVal = stringLambda();
            Console.WriteLine(“Lambda evaluates to – {0}”, stringVal);

 

            var doubleLambda = ToLambda(3.14159);
            double doubleVal = doubleLambda();
            Console.WriteLine(“Lambda evaluates to – {0}”, doubleVal);          ?
        }

 

So far, so good.  Although this might seem a little strange and vaguely useless, what it allows us to do is to treat literals and lambdas of the same type in exactly the same way.

 

Specifically what we want to be able to do is to define ‘super properties’ on objects whose values when queried are either regular values (as normal) or are the result of evaluating a rule, this rule being provided as a lambda expression.  When the property’s value is set the programmer either provides a value (literal or constant) or a rule (lambda expression).

 

Further details on the exact makeup of these ‘super properties’ elude us at the moment, more later…

VMware ESXi hypervisor is now freee, gratis, and for nothing!

Interesting thing, VMware have just announced that they will be offering their bare-metal (OS independent) server virtualisation system – ESXi hypervisor, for free.  It used to cost about 500$.

 

It can be downloaded from here, but as usual in these type of situations you have go to to the bother of registering first.  Still, on balance it will probably be worth bothering, and we are certainly looking forward to giving it a twirl!

Deploying Microsoft Report Viewer with ASP on a Hosted Site

The Microsoft Report Viewer is a handy way of producing reports without having to enter the Crystal Reports Quagmire, however deploying it within an ASP application to a Hosted environment can be quite involved as it may not be installed on your host system and it will usually not be possible to run the installer.

 

Instead doing the following worked for us:

 

Copy the following dlls to your project’s bin directory:

 

Microsoft.ReportViewer.Common.dll

Microsoft.ReportViewer.WebForms.dll

Microsoft.ReportViewer.WinForms.dll

Microsoft.ReportViewer.ProcessingObjectModel.dll

 

 

The first three will be easy to find on your development system – do a search, the last might only exist in you development system’s GAC, to get easy access to this use the subst command as follows to map it to a virtual drive:

 

Subst b: %windir%\assembly

 

This will map it to b:

 

Once the dlls have been copied into the bin folder, delete the existing GAC reference from your project to ‘Microsoft.ReportViewer.WebForms’, and add it again, this time by browsing to ‘Microsoft.ReportViewer.WebForms.dll’ in your bin folder.

 

Now when you publish… your app to your hosted site, the report viewer should work OK.

XPath with Adobe ActionScript 3

While working on a custom XML data-driven content management system in ActionScript 3, we wanted to have our XML content meta-data reference the actual XML content data by means of XPath expressions – hence we needed some half decent XPath support within AS3.

 

AS3 has quite good XML support, however its support for XPath expressions and queries is not much to write home about at all!  So instead, we have been using memorphic’s open source XPath implementation with much success.  It is easy to install & use, and it does a good job at implementing the majority of the XPath standard.

 

To use it, first download it and extract the src\memorphic folder to somewhere on your path.  Then import the XPath support to your AS3 code as follows:

 

 import memorphic.xpath.parser.*;
 import memorphic.xpath.XPathQuery;

 

To execute a query just declare an XPathQuery object and call the exec() method which returns an ‘XMLList’ of matches:

 

// Get a list of the 'News' Items..
var myQuery:XPathQuery =
new XPathQuery("/Content/ContentData/ContentItemList[@name='news']");
 
// execute the statement on the XML object and get the result
var result:XMLList = myQuery.exec(_xml);

 

Quite refreshingly straightforward really.

 

One thing to look out for, and which caused a lot of head-scratching for a while is that memorphic executes the XPath expression against a _copy_ of the provided XML tree, and the returned nodes belong to that tree and not the original – hence if you later modify any of these nodes, it is the copy that is modified and not the original XML tree, this was not really spelled out in any of the documentation.

 

For us, it was very important that this was not the case, so we got around the problem by just modifying the query code as follows:

 

within the definition of the function execRoot() in the file:

 

memorphic\xpath\model\QueryRoot.as

 

we changed:

 

contextNode.appendChild(xmlRoot.copy());

to:

contextNode.appendChild(xmlRoot);

With no ill effects (yet!).

Evaluating Trac for light-weight Issue Tracking

We are evaluating Trac for a client who wants a lightweight web-based issue tracking system for one of their projects.  Trac is an open source system.  We are using the Trac hosting service provided by svnrepository.com, who as their name suggests also host subversion (which we also use).

 

By default Trac integrates with subversion and indeed their tag line is – “Integrated SCM and project management”, which is a bit of a misnomer as it certainly does not provide anything near a functional web interface to subversion. But, happily, we are mostly interested in its issue tracking functionality so that’s not a problem!

 

Trac manages ‘tickets’ which represent  bugs or feature enhancement requests etc. Tickets can be added, edited and viewed etc.  It also models a road-map, onto which milestones can be added.  Tickets can be associated with milestones, product versions or components.  It has a Wiki aspect too, but we’re not really bothered about that.  It seems that it might do nicely as a light-weight issue tracking system, it certainly appears to take care of most of the core required bits, and it has a certain elegance and efficiency that is often missing in some of its over engineered and complex alternatives. 

 

It is not without its quirks however – especially during setup, but hopefully these quirks won’t prove to be too problematic so as to rule out its use.  Some of its admin functions still need to be accessed by command-line or by editing the Trac.ini file.  For example although you can use the web interface to add a ticket, you have to use the admin command to delete it.

 

One of its most problematic quirks though is its use of Basic Authentication for login authorisation which can lead to all sorts of very confusing login/logout situations, for example, you can’t easily logout and then login as another user…

 

By default the anonymous user has all sorts of permissions, so make sure to remove them by issuing an admin command like:

 

trac-admin <your-path> permission remove anonymous ‘*’

 

Also to arrange things so that you can pick the ‘owning’ user from a combo-box on the new ticket form (rather than having to type the user name out), edit Trac.ini and in the [Ticket] section, set

 

restrict_owner = true

 

Anyway, now that it’s all setup we will evaluate it on a real project and let you know how we got on!

Reading and Writing Excel Files from ASP

A project that we’re currently working on requires that we read from and write to Excel files from our ASP application. As the application will be hosted in an environment that will not have Office installed (as most will not) we can’t use automation, and anyway it seems that using this kind of automation from ASP is not recommended for all sorts of reasons (among other possible problems, it can not be guaranteed that Excel won’t at some stage look for some user interaction and pop up some ‘random’ window).

We needed another method of working with the Excel data from ASP. I tried using the MS ADO Excel drivers with very mixed results, these drivers seem to have been hobbled together with the express aim of annoying and hindering anybody that uses them, and I really can’t recommend their use unless you’re just reading from an excel chart with very consistent data types. Their abilty to write to Excel files is very very limited.

Looking at the commercial offerings, most seemed very much on the pricey side ~1,500USD, although when purchasing from Ireland the current Dollar/Euro exchange rate certainly helps! However I am now evaluating Syncfusions XLsIO component which seems to do the job quite nicely, although it does seem quite slow when reading medium to large worksheets. It is a much more reasonable ~500USD. It has a very similar API to Excel’s native API.

Anyway here are some links to pages that I found useful while on my journey of discovery:

ADO Read EXCEL files

http://codesnipers.com/?q=net-and-excel-importing
http://support.microsoft.com/default.aspx?scid=kb;EN-US;316934
http://www.aspose.com/default.aspx

Write Excel File

http://davidhayden.com/blog/dave/archive/2006/05/26/2973.aspx
http://www.pcreview.co.uk/forums/thread-1176677.php
http://www.devnewsgroups.net/group/microsoft.public.dotnet.framework/topic995.aspx
http://www.beansoftware.com/NET-Tutorials/Excel-ADO.NET-Database.aspx [Create sheet]
http://www.sql-server-helper.com/tips/read-import-excel-file-p03.aspx [Importing to SQL Server]
http://www.thescarms.com/dotnet/Schema.aspx [ Read Schema ]