I have been using the .net based Umbraco CMS for more then a year now and never have I had the feeling it limited me in anyway. But now I need a quick and dirty approach to connect to a database other then the Umbraco database.
Umbraco can grab XML feeds using the build in XSLT library extension, but I am just playing around at the moment and need direct access to manipulating query results.
So I created my own XSLT library. It has one 1 method at the moment: QueryDatabase(‘connection string’,'query’)
Just a note: it probably is not the greatest idea to use this in a production environment. What I plan to do afterwards, is to hard-code the query into another method not allowing any unknown request to the database.
But here is the code anyway (code pasted below), the dll and the VS 2003 project zip file.
If you want to use it without looking at the code just do the following actions:
- Download the astuanax xslt libarary dll
- Unzip the file and put it in the “/bin” folder of your Umbraco website
- Edit the file “xsltExtensions.xml” in the folder “/config” and
- Add the following line:
- Once you got this running, go to the XSLT editor in Umbraco and paste the following code into your xslt file:
This will show you the XML code you can expect from this query.
Leave a comment if you like it. Or if you have a problem using it, let me know and I will try to fix it.
C# Code:
namespace astuanax
{
/// <summary>
/// </summary>
public class Library
{
private static string _ErrorMessage = "";
/*
* This method is enabling debug information to be passed along
* doing them umbraco situps..
*/
public static string ErrorMessage()
{
return _ErrorMessage;
}
/// <summary>
/// Query a database other then the Umbraco database
/// </summary>
/// <param name="connection string">server – database – username – password </param>
/// <param name="sql"> sql query</param>
/// <returns> XML dataset </returns>
public static XPathNodeIterator QueryDatabase(string conn, string query )
{
try
{
SqlConnection thisConnection = new SqlConnection(conn);
// Server=localhost;Database=Northwind;User ID=****;Password=****;Trusted_Connection=False
thisConnection.Open();
SqlCommand thisCommand = thisConnection.CreateCommand();
thisCommand.CommandText = query;
SqlDataAdapter adapter = new SqlDataAdapter(thisCommand);
DataSet ds = new DataSet();
adapter.Fill(ds);
thisConnection.Close();
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(ds.GetXml());
XPathNavigator xp = xdoc.CreateNavigator();
return xp.Select(".");
}
catch (SqlException e)
{
_ErrorMessage = e.Message;
return null;
}
}
}
}