Feature Request

July 28, 2014

You know that your product is missing a critical feature, if a quick search (case in point: “Firefox search bookmark folder name”) brings up forum entries dating back at least 5 years:

"firefox search bookmark folder name"

“firefox search bookmark folder name”


Calling xsd.exe in VS 2013 Build Event

July 24, 2014

While working on an XML project, I wanted to call xsd.exe on an .xsd file during the build process, and found this solution on SO, which works for VS 2010.

For VS 2013, the solution did not work anymore, especially on systems that had no prior version of VS installed, since xsd.exe hides in a different location.

A comment to the answer illustrated how to query the registry correctly on x64 systems.

So my modified pre-build event looks like this:

call "$(ProjectDir)GenerateFromVSPrompt.cmd"
  "$(ProjectDir)"
  "$([MSBuild]::GetRegistryValueFromView(
    'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SDKs\Windows\v8.1A',
    'InstallationFolder', null, RegistryView.Registry64, RegistryView.Registry32)
    )bin\NETFX 4.5.1 Tools\xsd.exe"

all in 1 line.

If you use TFS as source control, you know that generated files need to be checked out before they can be overwritten.

I already wrote about TFS and code generation, and used the vcvarsall.bat then.

However, since we just need the path to tf.exe, and use the same VS version, we can just open a VS Command Prompt, run

where tf

and get the answer

C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\TF.exe

for VS 2013.

So our batch file GenerateFromVSPrompt.cmd looks like this:

set tf="C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\TF.exe"
%tf% checkout %1MyXsdClasses.cs
call %1XSDBuilder.cmd %1 %2
%tf% checkin /comment:"build event" /noprompt %1MyXsdClasses.cs
exit 0

In case tf.exe cannot check in the file because it did not change during code generation, it will return with exit code 1 which in turn will cause the build process to issue a build error and break. So we use exit 0 to clear the error condition

Finally, my version of XSDBuilder.cmd is based on an SO answer, but stripped down to only what is necessary, since I only have 2 XSD files, AND they need to be processed together:

pushd %1
%2 MyXsd1.xsd MyXsd2.xsd /c /n:My.Project.Xsd
popd

and, as I write, I really should merge both .cmd files into one … ;)

The build event is now executed correctly from VS, the VS Command Prompt, and on the build server.


Diamonds and Alcohol

June 17, 2014

“Your stats are booming!”, sayeth Teh WordPress.

But really, 160 spam comments about (mostly) diamonds and alcoholism within 24 hours is not what I expected.


Stumbling Upon the “Not Pre-Compiled” Error Message

May 12, 2014

I maintain an ASP.Net application, and I recently had to add a couple of new features. Development started with .Net 1.1, then 2.0, then 4.0. Since we were already on .Net 4, the new features are implemented in MVC3.

Everything worked fine until I wanted to deploy the ASP.Net-plus-MVC application.

I hit Publish, zipped the result, and unzip everything into its usual directory.

But…

The file ‘/somepage.aspx’ has not been pre-compiled, and cannot be requested.

or

Die Datei /somepage.aspx wurde nicht vorkompiliert und kann nicht angefordert werden.

I asked the internetz, and they suggested checking referenced assemblies. So I installed the MVC3 setup (on IIS8), just in case. But that did not resolve my problem.

While browsing thru tons of useless (and sometimes wrong) tips and tricks, I found this answer on SO:

I got this error when I upgraded a site from 2.0 to 4.0. The error was caused by a file PrecompiledApp.config in the site’s root directory. Once I deleted that file, the site started working.

Then it struck me: I had deployed the previous version of the web application using my build process which also compiles (and merges) .aspx files.

I have not yet found the time to adapt this build process to also support MVC projects (or test it whether it already does!), so I deployed what Publish produces. And this is not pre-compiled pages.

So when I overwrote the old version with the new version, the file PrecompiledApp.config remained.

After deleting the file, the web application started up again.


Calling a User Defined TSQL Function using NHibernate Linq

April 26, 2014

NHibernate Linq supports calling UDFs, but the implementation is not straight-forward.

I previously wrote about adding support for .Net string comparison functions in NHibernate Linq. This strategy uses existing .Net methods (such as methods of the System.String class) and maps them onto Linq tree operations which in turn are translated into SQL by the NHibernate database driver.

This time, we want to access a user defined TSQL function which cannot be interpreted as a “method” of a “data type” because it contains generic parameters, such as integers or date values, and is not specific to a single table, such as this example on SO.

Nevertheless my solution is based on that example.

The function I want to access is called dbo.Display_Record and is used to decide whether a record can be displayed in the UI based on a given date range.

CREATE FUNCTION [dbo].[Display_Record]
  (@ValidFrom DATETIME, @ValidUntil DATETIME)
RETURNS INT AS
BEGIN
  RETURN 0 (false) or 1 (true)
END

Note that the return type of the function should not be boolean, due to the interoperation of NH and SQL Server (see bug report here) – use integer values instead.

First, we need a declaration and dummy implementation in C#

    public static class dbo
    {
        public static int DisplayRecord(DateTime? from, DateTime? until)
        {
            return 0;
        }
    }

Next, an Hql (the SQL-like language NH uses internally) generator registry must be registered for the method call “dbo.DisplayRecord”:

    public class DisplayRecordLinqToHqlGeneratorsRegistry
        : DefaultLinqToHqlGeneratorsRegistry
    {
        public DisplayRecordLinqToHqlGeneratorsRegistry()
            : base()
        {
            RegisterGenerator(ReflectionHelper.GetMethodDefinition(
                () => dbo.DisplayRecord(null, null)), 
                new DisplayRecordMethodsHqlGenerator());
        }
    }

And an Hql generator

    public class DisplayRecordMethodsHqlGenerator
        : BaseHqlGeneratorForMethod
    {
        public DisplayRecordMethodsHqlGenerator()
        {
            SupportedMethods = new[] {
                ReflectionHelper.GetMethodDefinition(
                  () => dbo.DisplayRecord(null, null))
            };
        }

        public override HqlTreeNode BuildHql(MethodInfo method, Expression targetObject, 
            ReadOnlyCollection<Expression> arguments, 
            HqlTreeBuilder treeBuilder, IHqlExpressionVisitor visitor)
        {
            return treeBuilder.MethodCall("dbo.Display_Record",
                visitor.Visit(arguments[0]).AsExpression(),
                visitor.Visit(arguments[1]).AsExpression());
        }
    }

arguments[0] and arguments[1] are the arguments passed to our .Net function, and need to be added to the Linq tree.

Finally, our generator registry needs to be registered using Mapping By Code configuration:

            configuration.LinqToHqlGeneratorsRegistry
                <DisplayRecordLinqToHqlGeneratorsRegistry>();

Now we can write NH Linq queries such as

var records = session.Query<MyTable>
    .Where(record => dbo.DisplayRecord(record.ValidFrom, record.ValidUntil);

and the WHERE condition correctly references our UDF function.


Querying Facebook Like Count and Public Page Properties

April 18, 2014

There are various way to query the Like count of Facebook pages.

If you just want to want the live stats of a given Facebook page, Quintly provides a live statistics page. Upon entering the FB page name (www.facebook.com/[page-name] becomeswww.quintly.com/facebook-live-statistics/[page-name]), the page displays a live chart updating every couple of seconds.

But you can also query Facebook directly using the FQL API or the Graph API.

Here’s a sample URL for the FQL API

https://api.facebook.com/method/fql.query?query=select
  %20url,share_count,like_count,comment_count,total_count
  %20from%20link_stat
  %20where%20url=%27[my-fb-url]%27

(enter this into the navigation bar. [my-fb-url] is the complete URL starting with “https://

The result is an XML document in the form

<fql_query_response list="true">
  <link_stat>
    <url>https://www.facebook.com/[page-name]</url>
    <share_count>[value]</share_count>
    <like_count>[value]</like_count>
    <comment_count>[value]</comment_count>
    <total_count>[value]</total_count>
  </link_stat>
</fql_query_response>

and like_count or total_count will be the values you are looking for.

The Graph has a simpler approach, using simply

http://graph.facebook.com/?id=https://www.facebook.com/%5Bpage-name%5D

Here the result is given as JSON value, and the relevant JSON property is “likes”:

{
   "id": "74865038590",
..."likes": 194804,
...
}

If you want to query repeatedly, here’s a simple PowerShell solution using FQL:

$wc = New-Object system.Net.WebClient;
$response = $wc.downloadString("https://api.facebook.com/method/fql.query?query=
    select%20%20url,share_count,like_count,comment_count,total_count
    %20from%20link_stat%20where%20url=%27https://www.facebook.com/[page-name]%27")
$xml = [xml] $response
$xml.fql_query_response.link_stat

 


jQuery Autocomplete Inconsistencies

April 17, 2014

I guess I found an inconsistency in jQuery’s autocomplete() widget, which does not cause a selected value to be reset when clearing the input field.

Steps to reproduce (checked with 1.8.3 and 1.11.0):

  • Type the beginning of a string that is provided by the autocomplete source
  • Tab away from the input
  • “autocompletechange” fires, but the value is not valid, so the input field value is reset
  • Type the beginning of string (as above)
  • Select an entry using cursor keys
  • “select” fires (and sets the corresponding key value for the selected text value in a callback function)
  • Double-click the input to select the full text of the input field
  • Delete selected text (backspace or right-click Cut)
  • Neither “autocompletechange” nor “select” fires
  • Tab away from input field
  • Neither “autocompletechange” nor “select” fires

From the console.log:

blur ” 5:81
mouseup ” 5:90
keyup ‘r’ 5:87
keyup ‘re’ 5:87
keyup ‘rei’ 5:87
keyup ‘re’ 5:87
change ‘re’ 5:84
autocompletechange null 5:78
Nothing selected, input was re common.js:114
blur ” 5:81
mouseup ” 5:90
keyup ‘re’ 5:87
keyup ‘re’ 5:87
keyup ‘rei’ 5:87
keyup ‘6749’ [this is the key value!] 5:87
Selected: [some text] (6749) common.js:114
keyup ‘[some text] 5:87
keyup ‘[some text] 5:87
keyup ‘[some text] 5:87
keyup ” 5:87
change ” 5:84
blur ”

The value displayed in single quotes is the .value property of the input field, “rei” being the string that corresponds to the beginning of a valid value in the source.

The only workaround that comes to mind is to use the keyup and mouseup events to check whether the input’s value property is empty, and then reset the key field accordingly.


Follow

Get every new post delivered to your Inbox.

Join 66 other followers