Archive

Archive for the ‘Coding’ Category

NHibernate SqlAliasCriterion and Random sorting

December 30th, 2011 No comments

Wrote this custom NHibernate Criterion to be able to add custom SQL snippets with alias support when using criteria.

    public class SqlAliasCriterion : SQLCriterion
    {
        private string sql;
 
        public SqlAliasCriterion(string sql)
            : base(new SqlString(sql), new string[0], new IType[0])
        {
            this.sql = sql;
        }
 
        public override SqlString ToSqlString(ICriteria criteria, ICriteriaQuery criteriaQuery, IDictionary<string, IFilter> enabledFilters)
        {
            string replacedString = Regex.Replace(
                sql,
                @"{([a-zA-Z_]((\.)?[a-zA-Z0-9_])*)}",
                m =>
                {
                    ICriteria critter = criteria.GetCriteriaByAlias(m.Groups[1].Value);
                    if (critter != null)
                    {
                        return criteriaQuery.GetSQLAlias(critter);
                    }
 
                    return m.Groups[0].Value;
                }
            );
 
            return new SqlString(replacedString);
        }
    }

Usage example:

return Session.CreateCriteria<YourClass>("x")
        .Add(new SqlAliasCriterion("{x}.YourField = SomeNativeSQLFunc(foo)"))
        .List<YourClass>();

You can use the same trick to do ordering. (We use this for native MSSQL random ordering)

    public class OrderBySql : Order
    {
        private string sql;
 
        public OrderBySql(string sql, bool ascending)
            : base(String.Empty, ascending)
        {
            this.sql = sql;
        }
 
        public override SqlString ToSqlString(ICriteria criteria, ICriteriaQuery criteriaQuery)
        {
            string replacedString = Regex.Replace(
                sql,
                @"{([a-zA-Z_]((\.)?[a-zA-Z0-9_])*)}",
                m =>
                {
                    ICriteria critter = criteria.GetCriteriaByAlias(m.Groups[1].Value);
                    if (critter != null)
                    {
                        return criteriaQuery.GetSQLAlias(critter);
                    }
 
                    return m.Groups[0].Value;
                }
            );
 
            return new SqlString(replacedString + (this.ascending ? " ASC" : " DESC"));
        }
    }

Example with random sorting (MSSQL):

criteria.addOrder(
    new OrderBySql("NEWID()")
);
Categories: C# Tags: , , ,

HTML5 Sample Gallery

December 21st, 2011 No comments

Came across this excellent presentation which covers (all?) new features of HTML5. Have a look at the html5rocks site.

Categories: Coding Tags:

C# CacheHelper

December 19th, 2011 No comments

Just a simple class I put together for easy cache handling.

public class CacheHelper
{
    private static readonly ILog logger = LogManager.GetLogger(typeof(CacheHelper));
 
    public static T CachedResult<T>(string key, Func<T> valueRetrieval, double timeout = 5)
    {
        T result = (T)HttpContext.Current.Cache[key];
        if (result == null)
        {
            logger.InfoFormat("Cached item with key: {0} not found in Cache, fetching value", key);
 
            result = valueRetrieval.Invoke();
 
            HttpContext.Current.Cache.Insert(key, result, null, DateTime.Now.AddMinutes(timeout), Cache.NoSlidingExpiration);
        }
        else
        {
            logger.DebugFormat("Cached item with key: {0} retrieved from Cache", key);
        }
 
        return result;
    }
}

Usage example:

RssFeed rssFeed = CacheHelper.CachedResult<RssFeed>(url, () => TwitterApplication.GetPublicTimelineFeed(url));
Categories: C# Tags: , ,

Knockout JS

December 15th, 2011 No comments

A friend of mine showed me the Knockout JavaScript Framework today. Seems quite promising. I love the idea of data-binding.
When putting together a new view I most often want to start from static html and add unobtrusive javascript from there to add dynamic functionality. I hope this new framework will stack well with jQuery.

Categories: Coding Tags:

MSSQL Restore locked database

October 18th, 2011 No comments

Below is a short snippet that will allow you to restore your database by putting it in single user mode.
After restoring (if without errors) it will be in multi user mode again. If it is not you can still run the ‘alter database DATABASE_NAME set multi_user’ command to put it back in original mode.

USE master;
 
ALTER DATABASE [DATABASE_NAME] SET single_user WITH ROLLBACK immediate;
 
restore DATABASE [DATABASE_NAME] FROM disk = 'C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\Backup\YOUR_AWESOME_BACKUP.bak';
Categories: SQL Tags: , ,

MSSQL Changing login for user

October 18th, 2011 No comments

Sometimes when you move a database to another server it is necessary to change the login for a user to match the new environment. You can use the alter user command to do this. Do something like the following:

ALTER USER [THE_USER_NAME] WITH NAME = NEW_USER_NAME, LOGIN = [MACHINENAME\NEW_USER_NAME];

Not really complicated, but handy when you need it. 🙂

Categories: SQL Tags: , ,

Visual Studio, Attach debugger to w3wp process through macro

October 12th, 2011 No comments

Here is a short macro that will attach the debugger to the first w3wp.exe process it can find in the process list. (Script assumes a w3wp.exe process is running. Expect error messages if it doesn’t ;))

Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports System.Diagnostics
 
Public Module Famvdploeg
    'Attach the debugger to a w3wp.exe process
    Sub AttachDebugger()
        Try
            'Get your hostname
            Dim hostname As String = System.Net.Dns.GetHostName
            'Load the debugger interface
            Dim debugger As EnvDTE80.Debugger2 = DTE.Debugger
            'Get a local transport, (this is the "Default")
            Dim trans As EnvDTE80.Transport = debugger.Transports.Item("Default")
 
            'Attach to the first w3wp.exe command which we find
            Dim dbgeng(3) As EnvDTE80.Engine
            dbgeng(0) = trans.Engines.Item("T-SQL")
            dbgeng(1) = trans.Engines.Item("T-SQL")
            dbgeng(2) = trans.Engines.Item("Managed")
            Dim process As EnvDTE80.Process2 = debugger.GetProcesses(trans, hostname).Item("w3wp.exe")
            process.Attach2(dbgeng)
        Catch ex As System.Exception
            MsgBox(ex.Message)
        End Try
 
    End Sub
End Module

C# XML to Expando

October 9th, 2011 No comments

Made up this extension method for XDocuments to be able to return an Expando object on which the properties of the XML can be navigated. This is still a little bit rough. I found out there is a ElasticObject that probably works a lot better. But this is just a little ‘proof of concept’.
Note that attributes in the XML are not bound in the Expando object.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Dynamic;
using System.Xml.Linq;
 
namespace Famvdploeg.Com
{
    public static class XDocumentExtensions
    {
        public static dynamic ToExpandoObject(this XDocument document)
        {
            return ParseNode(document.Root);
        }
 
        private static dynamic ParseNode(XElement item)
        {
            dynamic expando = new ExpandoObject();
            var props = expando as IDictionary<string, object>;
 
            /* Properties of current node. Single and Lists are created here dynamic */
            IEnumerable<IGrouping<string, XElement>> groupedProperties = item.Elements().Where(element => !element.HasElements).GroupBy(x => x.Name.ToString());
 
            foreach (IGrouping<string, XElement> propertyGroup in groupedProperties)
            {
                int nrElements = propertyGroup.Count();
                if (nrElements == 1)
                {
                    props[propertyGroup.Key.ToValidPropertyName()] = propertyGroup.First().Value;
                }
                else
                {
                    var multipleValues = new List<string>();
 
                    foreach (XElement element in propertyGroup)
                    {
                        multipleValues.Add(element.Value);
                    }
 
                    props[propertyGroup.Key.ToValidPropertyName()] = multipleValues;
                }
            }
 
            /* Children of current node. Single and Lists are created here dynamic */
            IEnumerable<IGrouping<string, XElement>> groupedElements = item.Elements().Where(element => element.HasElements).GroupBy(x => x.Name.ToString());
 
            foreach (IGrouping<string, XElement> elementGroup in groupedElements)
            {
                int nrElements = elementGroup.Count();
                if (nrElements == 1)
                {
                    props[elementGroup.Key.ToValidPropertyName()] = ParseNode(elementGroup.First());
                }
                else
                {
                    var multipleElements = new List<dynamic>();
 
                    foreach (XElement element in elementGroup)
                    {
                        multipleElements.Add(ParseNode(element));
                    }
 
                    props[elementGroup.Key.ToValidPropertyName()] = multipleElements;
                }
            }
 
            return expando;
        }
    }
}

Categories: C# Tags: , , , ,

Grails cheatsheet

September 26th, 2011 No comments

This is supposed to be a cheatsheet for some common elements in Grails.
It’s a little bare at the moment but I hope that in time it will be a nice mashup of different Grails elements.

Grails Cheatsheet

Constraints

static constraints = {
    propertyName(
        blank: false,
        nullable: false,
        inList: ['a', 'b'], //Or reference property here
        matches: '[0-9]+',
        minSize: 1,
        maxSize: 10,
        min: 1,
        max: 10,
        range: 1..10,
        unique: true,
        url: true,
        email: true,
        notEqual: "passwd", //Or reference property here
        validator: { val, obj ->
            return val != obj.propertyName
        },
 
        /* Display Options */
        attributes: [year: 2000..2011], //Adds extra attributes to item when rendered.
        password: true, //Indicate that this is a password field
        widget: 'textarea', //Choose what widget will be used to render this item.
                //textField, hiddenField, submitButton, field, textArea, form, actionSubmit, actionSubmitImage, datePicker, renderNoSelectionOption, timeZoneSelect, localeSelect, currencySelect, select, checkBox, radio
        display: false //Hide this item when scaffolding
    )
}

Persistence Callbacks

  • beforeInsert – Executed before an object is initially persisted to the database
  • beforeUpdate – Executed before an object is updated
  • beforeDelete – Executed before an object is deleted
  • beforeValidate – Executed before an object is validated
  • afterInsert – Executed after an object is persisted to the database
  • afterUpdate – Executed after an object has been updated
  • afterDelete – Executed after an object has been deleted
  • onLoad – Executed when an object is loaded from the database

Sample:

def beforeInsert() {
	doSomething()
}
 
def beforeUpdate() {
	if (isDirty('fieldName')) {
		doSomething()
	}
}

Showing SQL-queries

Edit the DataSource.groovy file in the Configuration directory and add the following to the hibernate section (preferably in non-production environments):

hibernate {
	show_sql = true
}
Categories: Groovy Tags:

Configuring Tomcat, PostgreSQL and Grails on Ubuntu

September 18th, 2011 1 comment

First install tomcat and tomcat on your ubuntu machine if you have not already done so.

sudo apt-get install openjdk-7-jdk tomcat7 postgresql

Setup the required PostgreSQL database on ubuntu. We will connect to it as a JNDI DataSource later on.
Usually I create a new superuser to do maintenance tasks.

CREATE USER <role_name> superuser login encrypted password '<password>';
-- Connect to the database from command line
psql -d postgres
 
CREATE USER userName WITH PASSWORD 'yourPassword';
 
CREATE DATABASE databaseName;
 
GRANT ALL PRIVILEGES ON DATABASE databaseName TO userName;

Get the postgreSQL JDBC driver.

cd /usr/share/tomcat7/lib
sudo wget http://jdbc.postgresql.org/download/postgresql-9.1-901.jdbc3.jar

Create a Tomcat Context configuration for your grails webapp.

sudo vi /etc/tomcat7/Catalina/localhost/yourappname.xml

Fill it with something like the following, (adapted to your webapps name / context root of course)

<Context path="/yourContextPath" reloadable="false">
          <Resource name="jdbc/yourName" auth="Container"
                    type="javax.sql.DataSource" driverClassName="org.postgresql.Driver"
                    url="jdbc:postgresql://127.0.0.1:5432/mydb"
                    username="myuser" password="mypasswd" maxActive="20" maxIdle="10"
                    maxWait="-1"/>
</Context>

We’re almost there. Update DataSource.groovy

    production {
        dataSource {
            dbCreate = "update"
            jndiName = "java:comp/env/jdbc/yourName"
        }
    }

Awesome! Restart tomcat (sudo /etc/init.d/tomcat7 restart). Build (grails prod war) and deploy (copy file to /var/lib/tomcat7/webapps) your grails webapp and go bananas!

Update:

I got an “Unsupported major.minor version 51.0” error. This was because by default java 6 was used instead of java 7 on my machine.

Caused by: java.lang.UnsupportedClassVersionError: org/codehaus/groovy/grails/scaffolding/GrailsTemplateGenerator : Unsupported major.minor version 51.0 (unable to load class org.codehaus.groovy.grails.scaffolding.GrailsTemplateGenerator)

My default-java was set wrong in the /usr/lib/jvm directory. (ls -l /usr/lib/jvm) default-java was pointing to the java 6 version.

cd /usr/lib/jvm
sudo rm default-java
sudo ln -s java-1.7.0-openjdk-amd64 default-java
Categories: Groovy Tags: