<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Tony Williams</title>
	<atom:link href="http://blog.tonywilliams.me.uk/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.tonywilliams.me.uk</link>
	<description></description>
	<lastBuildDate>Sun, 15 Apr 2012 19:32:14 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Project Euler: Problem 4</title>
		<link>http://blog.tonywilliams.me.uk/project-euler-problem-4/</link>
		<comments>http://blog.tonywilliams.me.uk/project-euler-problem-4/#comments</comments>
		<pubDate>Sun, 15 Apr 2012 19:32:14 +0000</pubDate>
		<dc:creator>Tony</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Project Euler]]></category>

		<guid isPermaLink="false">http://blog.tonywilliams.me.uk/?p=195</guid>
		<description><![CDATA[Problem: A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 99. Find the largest palindrome made from the product of two 3-digit numbers. Source: http://projecteuler.net/problem=4 Solution: Before we can being to solved the problem above we first must answer the questions raised [...]]]></description>
			<content:encoded><![CDATA[<h2>Problem:</h2>
<blockquote><p>A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 99.</p>
<p>Find the largest palindrome made from the product of two 3-digit numbers.</p></blockquote>
<p><em>Source: <a href="http://projecteuler.net/problem=4">http://projecteuler.net/problem=4</a></em></p>
<p><em><br />
</em></p>
<h2>Solution:</h2>
<p>Before we can being to solved the problem above we first must answer the questions raised by it. In other words:</p>
<ul>
<li>Palindromic Number?</li>
</ul>
<p>&nbsp;</p>
<h3>Palindromic Number?</h3>
<p>A <a title="Palindromic Number" href="http://en.wikipedia.org/wiki/Palindromic_number" target="_blank">palindromic number</a> a number that is a <a title="Palindrome" href="http://en.wikipedia.org/wiki/Palindrome" target="_blank">palindrome</a>, which is just a word or phrase that is the same in either direction.</p>
<p>&nbsp;</p>
<h2>Code:</h2>
<p><em>Source: <a href="https://bitbucket.org/TWith2Sugars/project-euler/src/dbd1afaa7fc6/python/4.py">https://bitbucket.org/TWith2Sugars/project-euler/src/dbd1afaa7fc6/python/4.py</a></em></p>
<pre class="brush:python">def isPalindrome(n):
    return (n==n[::-1])

def findLargestPalindrome():
    largest = 0
    for x in range(100,1000):
        for y in range(100,1000):
            product = x*y

            if product &gt; largest and isPalindrome(str(product)):
                largest = product
    return largest

print(findLargestPalindrome())</pre>
<p>&nbsp;</p>
<h3>IsPalindrome</h3>
<p>This method is what is responsible for checking if a number is a palindrome; the &#8220;[::-1]&#8221; is what takes the parameter and reverses it. That&#8217;s it!</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tonywilliams.me.uk/project-euler-problem-4/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Unit of Work, NHibnernate and Asp.Net MVC</title>
		<link>http://blog.tonywilliams.me.uk/unit-of-work-nhibnernate-and-asp-net-mvc/</link>
		<comments>http://blog.tonywilliams.me.uk/unit-of-work-nhibnernate-and-asp-net-mvc/#comments</comments>
		<pubDate>Mon, 19 Mar 2012 13:41:15 +0000</pubDate>
		<dc:creator>Tony</dc:creator>
				<category><![CDATA[Asp.Net MVC]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Asp.Net MVC3]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[UnitOfWork]]></category>

		<guid isPermaLink="false">http://blog.tonywilliams.me.uk/?p=182</guid>
		<description><![CDATA[In a previous post I mentioned for some projects I&#8217;m using a combination of NHibernate, unit of work and asp.net mvc; this post will give an example of how I set this up for a project and how to get mvc to automatically create instances of UoW, wrap our code in transactions and clean up after it&#8217;s self [...]]]></description>
			<content:encoded><![CDATA[<p>In a previous <a href="http://blog.tonywilliams.me.uk/nhibernate-leaking-connections-with-unitofwork-pattern-and-transactions">post </a>I mentioned for some projects I&#8217;m using a combination of <a href="http://nhforge.org/Default.aspx">NHibernate</a>, <a href="http://martinfowler.com/eaaCatalog/unitOfWork.html">unit of work</a> and <a href="http://www.asp.net/mvc">asp.net mvc</a>; this post will give an example of how I set this up for a project and how to get mvc to automatically create instances of UoW, wrap our code in transactions and clean up after it&#8217;s self via <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.actionfilterattribute.aspx">ActionFilterAttributes</a>. Some of the code I have is a modified version of <a href="http://davybrion.com/blog/2009/12/using-nhibernate-in-your-service-layer/">this</a> but probably not as nice.</p>
<p>Here is a list of the interfaces that&#8217;ll be created:</p>
<ul>
<li><strong><a href="#iunitofwork">IUnitOfWork</a></strong>: Defines the basic methods for a unit of work class.</li>
<li><strong><a href="#irequeststate">IRequestState</a></strong>: An abstraction of the<a href="http://davybrion.com/blog/2009/01/abstracting-request-state/"> request state</a>.</li>
<li><strong><a href="#isessionprovider">ISessionProvider</a></strong>: Handles the NHibernate session factory</li>
<li><strong><a href="#iactivesessionmanager">IActiveSessionManager</a></strong>: Maintains the current session</li>
</ul>
<p>And classes that implement them:</p>
<ul>
<li><strong><a href="#unitofwork">UnitOfWork</a></strong></li>
<li><strong><a href="#aspnetrequeststate">AspNetRequestState</a></strong></li>
<li><strong><a href="#sessionprovider">SessionProvider</a></strong></li>
<li><strong><a href="#activesessionmanager">ActiveSessionManager</a></strong></li>
</ul>
<p>And finally the mvc Attribute: <strong><a href="#unitofworkfilter">UnitOfWorkFilter</a></strong>.</p>
<p>This maybe(is) a lot of work for for something that seems pretty straight forward but it allows the code to be decoupled and makes testing much easier.  For example a project I&#8217;ve been working on uses this workflow and has a windows service to do some back end processing; by creating a <em>RequestState</em> to work with a windows service the rest of the code doesn&#8217;t need changing (apart from the filter obviously.)</p>
<p>I&#8217;ll leave the code further down in the post so things don&#8217;t get messy.</p>
<h2>Actually using this setup.</h2>
<p>This post makes the assumption that your data access is all via nhibernate and you&#8217;re using the <a href="http://martinfowler.com/eaaCatalog/repository.html">repository pattern</a> or something similar. Your repositories will need access to the <em>IActiveSessionManager</em>. If you&#8217;re using a <a title="Dependency Injection" href="http://en.wikipedia.org/wiki/Dependency_injection">DI</a> like <a href="http://www.ninject.org/">Ninject</a> it should pass it through for you.</p>
<p>In your repository you can access the nhibernate session like so:</p>
<pre class="brush:c#">this.activeSessionManager.GetActiveSession();</pre>
<p>I personally have a property to do this for me:</p>
<pre class="brush:c#">    public ISession Session
    {
      get
      {
        return this.activeSessionManager.GetActiveSession();
      }
    }</pre>
<p>From here on do what ever queries you need, all the repositories in the will share the same session during the same request.</p>
<h2>Applying the attribute</h2>
<p>You can either have the <strong><a href="#unitofworkfilter">UnitOfWorkFilter</a> </strong>attached to each controller/method or in the global.asax you can register is as a global filter.</p>
<pre class="brush:c#"> [UnitOfWorkFilter]
  public class UserController : Controller
{
}</pre>
<p>or</p>
<pre class="brush:c#">    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
      filters.Add(new UnitOfWorkFilter());

    }</pre>
<p>That&#8217;s it!.</p>
<h2>How it all fits together</h2>
<p>Imagine you have a controller that gets you a list of users (UserController).</p>
<ol>
<li>You issue a <strong>GET</strong> to the controller action</li>
<li>The <strong>UnitOfWorkFilter </strong>kicks in and starts a new transaction from the <strong>ActiveSessionManager </strong>(The same manager your repo&#8217;s use)</li>
<li>The ActiveSessionManager checks for/creates a new nhibernate session to work with</li>
<li>Your repos use this ActiveSessionManager/NHibernate session to get its data</li>
<ol>
<li>If you have more than one repo in the controller action then no new sessions are created, the same one is shared.</li>
</ol>
<li>The controller returns the users</li>
<li>The UnitOfWorkFilter then commits the transaction and closes the current session</li>
<ol>
<li>If something goes wrong like an exception the the UnitOfWorkFilter rollsback the transaction &#8211; preserving the integrity of the database</li>
</ol>
</ol>
<div></div>
<p>Below is the code to implement this.</p>
<h2 id="iunitofwork">IUnitOfWork</h2>
<pre class="brush:c#">  public interface IUnitOfWork : IDisposable
  {

    void BeginTransaction();

    void EndTransaction();

    void RollBack();
  }</pre>
<h2 id="irequeststate">IRequestState</h2>
<pre class="brush:c#">  public interface IRequestState
  {
    T Get&lt;T&gt;(string key);

    void Store(string key, object something);
  }</pre>
<h2 id="isessionprovider">ISessionProvider</h2>
<p>The ISession is the NHibernate session.</p>
<pre class="brush:c#">  public interface ISessionProvider
  {
    ISession Create();
  }</pre>
<h2 id="iactivesessionmanager">IActiveSessionManager</h2>
<pre class="brush:c#">  public interface IActiveSessionManager: IDisposable
  {
    ISession GetActiveSession();

    void ClearActiveSession();

    bool HasActiveSession { get; }
  }</pre>
<h2 id="unitofwork">UnitOfWork</h2>
<pre class="brush:c#">/// &lt;summary&gt;
  /// An nhibernate specific implementation of the unit of work concept
  /// &lt;/summary&gt;
  public class UnitOfWork : IUnitOfWork
  {
    private readonly IActiveSessionManager sessionManager;

    private ITransaction transactionScope;

    public UnitOfWork(IActiveSessionManager sessionManager)
    {
      this.sessionManager = sessionManager;
    }

    public void Dispose()
    {
      if (this.transactionScope != null)
      {
        this.transactionScope.Dispose();
      }

      this.sessionManager.Dispose();
    }

    public void BeginTransaction()
    {
      if (this.transactionScope != null)
      {
        throw new InvalidOperationException("Transaction already started; nested transactions are not supported");
      }

      this.transactionScope = this.sessionManager.GetActiveSession().BeginTransaction();
    }

    public void EndTransaction()
    {
      if (this.transactionScope == null)
      {
        throw new InvalidOperationException("No active transaction found");
      }

      if (!this.transactionScope.IsActive)
      {
        throw new InvalidOperationException("This transaction is no longer active");
      }

      try
      {
        this.transactionScope.Commit();
      }
      catch (Exception ex1)
      {
          this.RollBack();
      }
    }

    public void RollBack()
    {
      this.transactionScope.Rollback();
    }
  }</pre>
<h2 id="aspnetrequeststate">AspNetRequestState</h2>
<pre class="brush:c#">  public class AspNetRequestState : IRequestState
  {
    public T Get&lt;T&gt;(string key)
    {
      return (T)HttpContext.Current.Items[key];
    }

    public void Store(string key, object something)
    {
      HttpContext.Current.Items[key] = something;
    }
  }</pre>
<h2 id="sessionprovider">SessionProvider</h2>
<p>Note that the session factory has not been configured, this is left up you to configure.</p>
<pre class="brush:c#"> public class SessionProvider : ISessionProvider
  {
    private static ISessionFactory sessionFactory;

    public SessionProvider()
    {
      if (sessionFactory == null)
      {
	    // Do your mhibernate configuration here
        var configration = new Configuration();
        sessionFactory = configration.BuildSessionFactory();
      }
    }

    public ISession Create()
    {
      return sessionFactory.OpenSession();
    }
  }</pre>
<h2 id="activesessionmanager">ActiveSessionManager</h2>
<pre class="brush:c#">public class ActiveSessionManager : IActiveSessionManager
  {
    private const string sessionKey = "_currentSession";

    private readonly IRequestState requestState;

    private readonly ISessionProvider sessionProvider;

    public ActiveSessionManager(IRequestState requestState, ISessionProvider sessionProvider)
    {
      this.requestState = requestState;
      this.sessionProvider = sessionProvider;
    }

    public ISession GetActiveSession()
    {
      if (this.Current == null)
      {
        var newSession= this.sessionProvider.Create();
        this.Current = newSession;
        return newSession;
      }

      return this.Current;
    }

    public void ClearActiveSession()
    {
      this.Current = null;
    }

    public bool HasActiveSession
    {
      get { return this.Current != null; }
    }

    protected virtual ISession Current
    {
      get
      {
        return requestState.Get&lt;ISession&gt;(sessionKey);
      }
      set
      {
        requestState.Store(sessionKey, value);
      }
    }

    public void Dispose()
    {
      var session = this.Current;
      if(session != null)
      {
        session.Dispose();
        this.ClearActiveSession();
      }
    }
  }</pre>
<p>&nbsp;</p>
<h2 id="unitofworkfilter">UnitOfWorkFilter</h2>
<p>&nbsp;</p>
<pre class="brush:c#">public class UnitOfWorkFilter : ActionFilterAttribute
  {
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
      var unitOfWork = DependencyResolver.Current.GetService&lt;IUnitOfWork&gt;();
      unitOfWork.BeginTransaction();
    }

    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
      var unitOfWork = DependencyResolver.Current.GetService&lt;IUnitOfWork&gt;();
      unitOfWork.EndTransaction();
    }
  }</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.tonywilliams.me.uk/unit-of-work-nhibnernate-and-asp-net-mvc/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to enable CORS in Asp.Net</title>
		<link>http://blog.tonywilliams.me.uk/how-to-enable-cors-in-asp-net/</link>
		<comments>http://blog.tonywilliams.me.uk/how-to-enable-cors-in-asp-net/#comments</comments>
		<pubDate>Wed, 14 Mar 2012 20:15:12 +0000</pubDate>
		<dc:creator>Tony</dc:creator>
				<category><![CDATA[Asp.Net MVC]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Asp.Net]]></category>
		<category><![CDATA[CORS]]></category>

		<guid isPermaLink="false">http://blog.tonywilliams.me.uk/?p=174</guid>
		<description><![CDATA[CORS is a method of allowing calls from one domain to another that would otherwise be forbidden due to same origin policy. There are many ways to enable this to allow asp.net to respond to these types of request and the method below allows calls from any domain. This might not be right for every application [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://en.wikipedia.org/wiki/Cross-origin_resource_sharing">CORS </a>is a method of allowing calls from one domain to another that would otherwise be forbidden due to <a href="http://www.w3.org/Security/wiki/Same_Origin_Policy">same origin policy</a>. There are many ways to enable this to allow asp.net to respond to these types of request and the method below allows calls from any domain. This might not be right for every application but it&#8217;s a quick way to get started.</p>
<p>In the apps web.config add the following section:</p>
<pre class="brush:xml">  &lt;system.webServer&gt;
    &lt;httpProtocol&gt;
      &lt;customHeaders&gt;
        &lt;add name="Access-Control-Allow-Origin" value="*" /&gt;
      &lt;/customHeaders&gt;
    &lt;/httpProtocol&gt;</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.tonywilliams.me.uk/how-to-enable-cors-in-asp-net/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Clustering RabbitMQ Windows</title>
		<link>http://blog.tonywilliams.me.uk/clustering-rabbitmq-windows/</link>
		<comments>http://blog.tonywilliams.me.uk/clustering-rabbitmq-windows/#comments</comments>
		<pubDate>Tue, 10 Jan 2012 12:30:40 +0000</pubDate>
		<dc:creator>Tony</dc:creator>
				<category><![CDATA[SysAdmin]]></category>
		<category><![CDATA[AWS]]></category>
		<category><![CDATA[Clustering]]></category>
		<category><![CDATA[RabbitMQ]]></category>
		<category><![CDATA[Windows]]></category>

		<guid isPermaLink="false">http://blog.tonywilliams.me.uk/?p=168</guid>
		<description><![CDATA[I recently had to set up a RabbitMQ cluster in windows on AWS , these are just some notes so I can remember what I did. Hopefully it might help others too. Open ports on the machines for the cluster Set the port for the server.bat and service.bat (can be found in C:\Program Files (x86)\RabbitMQ Server\rabbitmq_server-{VERSION}) [...]]]></description>
			<content:encoded><![CDATA[<p>I recently had to set up a <a href="http://www.rabbitmq.com/">RabbitMQ </a>cluster in windows on <a title="Amazon Web Services" href="http://aws.amazon.com/">AWS </a>, these are just some notes so I can remember what I did. Hopefully it might help others too.</p>
<ul>
<li>Open <strong>ports</strong> on the machines for the cluster</li>
<li>Set the <strong>port</strong> for the server.bat and service.bat (can be found in C:\Program Files (x86)\RabbitMQ Server\rabbitmq_server-{VERSION})</li>
<li>Set the <strong>.erlang.cookie</strong> file to be the same value on all machines (Can be found in c:/windows and c:/user/{USER})</li>
<li>Use the following commands to set up the <a title="RabbitMQ Clustering" href="http://www.rabbitmq.com/clustering.html">cluster</a>.</li>
</ul>
<p>And that should do it.</p>
<p>I should really have written this down when I set it up and not 2 months later.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tonywilliams.me.uk/clustering-rabbitmq-windows/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Asynchronous Database Auditing</title>
		<link>http://blog.tonywilliams.me.uk/asynchronous-database-auditing/</link>
		<comments>http://blog.tonywilliams.me.uk/asynchronous-database-auditing/#comments</comments>
		<pubDate>Sun, 25 Sep 2011 20:31:35 +0000</pubDate>
		<dc:creator>Tony</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Async]]></category>
		<category><![CDATA[Auditing]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://blog.tonywilliams.me.uk/?p=157</guid>
		<description><![CDATA[I needed to create an extensive db audit system for a project at work, little bit of searching lead me to these two articles: Trigger Based Audit Centralized Asynchronous Auditing Initially I tried using just the trigger based auditing but that had some performance issues; so my solution was to create a script (3 scripts actually) that [...]]]></description>
			<content:encoded><![CDATA[<p>I needed to create an extensive db audit system for a project at work, little bit of searching lead me to these two articles:</p>
<ol>
<li><a href="http://weblogs.asp.net/jgalloway/archive/2008/01/27/adding-simple-trigger-based-auditing-to-your-sql-server-database.aspx">Trigger Based Audit</a></li>
<li><a href="http://www.sqlteam.com/article/centralized-asynchronous-auditing-with-service-broker">Centralized Asynchronous Auditing</a></li>
</ol>
<div>Initially I tried using just the trigger based auditing but that had some performance issues; so my solution was to create a script (3 scripts actually) that combined the trigger generating code of the first article with the service based asynchronous writing of the second article.</div>
<h2>How it works</h2>
<div><strong>NOTE</strong>: This post will get out of date at some point so it&#8217;s best to get the scripts from the bitbucket repo: <a href="https://bitbucket.org/ThapLtd/async-database-audit">https://bitbucket.org/ThapLtd/async-database-audit</a></div>
<h3>Setting up the Audit Database</h3>
<div>The<a href="https://bitbucket.org/ThapLtd/async-database-audit/src/a101da76cbc0/Audit%20Database.sql"> first script</a> creates the database the records the audit information and sets up a <a href="http://msdn.microsoft.com/en-us/library/ms345108(v=sql.90).aspx">service broker</a> that listens to a queue for a message from another database (we&#8217;ll set this up in another script). This script will generate a guid that you&#8217;ll need to take note of for later:</div>
<pre class="brush:sql">USE master

IF DB_ID('[AUDITDB]') IS NULL
	CREATE DATABASE [AUDITDB]		

-- enable service broker
ALTER DATABASE [AUDITDB] SET ENABLE_BROKER
-- set trustworthy on so we don't need to use certificates
ALTER DATABASE [AUDITDB] SET TRUSTWORTHY ON

GO

USE [AUDITDB] 	

GO
-- get service broker guid for [AUDITDB].
-- we must copy/paste this guid to the BEGIN DIALOG
-- in dbo.spSendAuditData stored procedure
SELECT	service_broker_guid
FROM	sys.databases
WHERE	database_id = DB_ID()

GO

IF OBJECT_ID('dbo.MasterAuditTable') IS NOT NULL
	DROP TABLE dbo.MasterAuditTable

GO
-- Master Audit Table
CREATE TABLE MasterAuditTable
(
	AuditID BIGINT IDENTITY(1,1) NOT NULL,
	DMLType char(1) NOT NULL CHECK (DMLType IN ('D', 'U', 'I')),
	DatabaseName nvarchar(128),
	TableName nvarchar(128),
	PrimaryKeyField nvarchar(1000),
	PrimaryKeyValue nvarchar(1000),
	FieldName nvarchar(128),
	OldValue nvarchar(1000),
	NewValue nvarchar(1000),
	UpdateDate datetime DEFAULT (GetDate()),
	UserName nvarchar(128)
)

GO

IF OBJECT_ID('dbo.AuditDialogs') IS NOT NULL
	DROP TABLE dbo.AuditDialogs

GO
-- Table that will hold dialog id's for each database on the server
-- These dialogs will be reused. why this is a good thing is explained here:
-- http://blogs.msdn.com/remusrusanu/archive/2007/04/24/reusing-conversations.aspx
CREATE TABLE dbo.AuditDialogs
(
	DbId INT NOT NULL,
	DialogId UNIQUEIDENTIFIER NOT NULL
)

GO
IF OBJECT_ID('dbo.AuditErrors') IS NOT NULL
	DROP TABLE dbo.AuditErrors

GO
-- create Errors table
CREATE TABLE dbo.AuditErrors
(
	Id BIGINT IDENTITY(1, 1) PRIMARY KEY,
	ErrorProcedure NVARCHAR(126) NOT NULL,
	ErrorLine INT NOT NULL,
	ErrorNumber INT NOT NULL,
	ErrorMessage NVARCHAR(4000) NOT NULL,
	ErrorSeverity INT NOT NULL,
	ErrorState INT NOT NULL,
	AuditedData XML NOT NULL,
	ErrorDate DATETIME NOT NULL DEFAULT GETUTCDATE()
)

GO
IF OBJECT_ID('dbo.usp_WriteAuditData') IS NOT NULL
	DROP PROCEDURE dbo.usp_WriteAuditData

GO

-- stored procedure that writes the audit data from the queue to the audit table
CREATE PROCEDURE dbo.usp_WriteAuditData
AS
BEGIN
	DECLARE @msgBody XML
	DECLARE @dlgId uniqueidentifier

	WHILE(1=1)
	BEGIN
		BEGIN TRANSACTION
		BEGIN TRY

			-- insert messages into audit table one message at a time
			;RECEIVE top(1)
					@msgBody	= message_body,
					@dlgId		= conversation_handle
			FROM	dbo.TargetAuditQueue

			-- exit when the whole queue has been processed
			IF @@ROWCOUNT = 0
			BEGIN
				IF @@TRANCOUNT &gt; 0
				BEGIN
					ROLLBACK;
				END
				BREAK;
			END 

			DECLARE @DatabaseName NVARCHAR(128), @TableName NVARCHAR(128),
					@DMLType CHAR(1),
					@PrimaryKeyField nvarchar(1000), @PrimaryKeyValue nvarchar(1000),
					@FieldName nvarchar(128), @OldValue nvarchar(1000), @NewValue nvarchar(1000),
					@UpdateDate datetime, @UserName nvarchar(128)

			-- xml datatype and its capabilities rock
			SELECT	@DatabaseName = T.c.query('/AuditMsg/DatabaseName').value('.[1]', 'NVARCHAR(128)'),
					@TableName = T.c.query('/AuditMsg/TableName').value('.[1]', 'NVARCHAR(128)'),
					@DMLType = T.c.query('/AuditMsg/DMLType').value('.[1]', 'CHAR(1)'),
					@PrimaryKeyField = T.c.query('/AuditMsg/PrimaryKeyField').value('.[1]', 'NVARCHAR(1000)'),
					@PrimaryKeyValue = T.c.query('/AuditMsg/PrimaryKeyValue').value('.[1]', 'NVARCHAR(1000)'),
					@FieldName = T.c.query('/AuditMsg/FieldName').value('.[1]', 'NVARCHAR(128)'),
					@OldValue = T.c.query('/AuditMsg/OldValue').value('.[1]', 'NVARCHAR(1000)'),
					@NewValue = T.c.query('/AuditMsg/NewValue').value('.[1]', 'NVARCHAR(1000)'),
					@UpdateDate = T.c.query('/AuditMsg/UpdateDate').value('.[1]', 'datetime'),
					@UserName = T.c.query('/AuditMsg/UserName').value('.[1]', 'NVARCHAR(128)')
			FROM	@msgBody.nodes('/AuditMsg') T(c)

			INSERT INTO dbo.MasterAuditTable(DatabaseName, TableName, DMLType, PrimaryKeyField, PrimaryKeyValue, FieldName, OldValue, NewValue, UpdateDate, UserName)
			SELECT @DatabaseName, @TableName, @DMLType, @PrimaryKeyField, @PrimaryKeyValue, @FieldName, @OldValue, @NewValue, @UpdateDate, @UserName

			-- No need to close the conversation because auditing never ends
			-- you can end conversations if you want periodicaly with a scheduled job
			-- END CONVERSATION @dlgId

			IF @@TRANCOUNT &gt; 0
			BEGIN
				COMMIT;
			END
		END TRY
		BEGIN CATCH
			IF @@TRANCOUNT &gt; 0
			BEGIN
				ROLLBACK;
			END
			-- insert error into the AuditErrors table
			INSERT INTO AuditErrors (
					ErrorProcedure, ErrorLine, ErrorNumber, ErrorMessage,
					ErrorSeverity, ErrorState, AuditedData)
			SELECT	ERROR_PROCEDURE(), ERROR_LINE(), ERROR_NUMBER(), ERROR_MESSAGE(),
					ERROR_SEVERITY(), ERROR_STATE(), @msgBody
		END CATCH;
	END
END

GO
IF EXISTS(SELECT * FROM sys.services WHERE NAME = '//Audit/DataWriter')
	DROP SERVICE [//Audit/DataWriter]

IF EXISTS(SELECT * FROM sys.service_queues WHERE NAME = 'TargetAuditQueue')
	DROP QUEUE dbo.TargetAuditQueue

IF EXISTS(SELECT * FROM sys.service_contracts  WHERE NAME = '//Audit/Contract')
	DROP SERVICE [//Audit/Contract]

IF EXISTS(SELECT * FROM sys.service_message_types WHERE name='//Audit/Message')
	DROP MESSAGE TYPE [//Audit/Message]
GO
-- create a message that must be well formed XML
CREATE MESSAGE TYPE [//Audit/Message]
	VALIDATION = WELL_FORMED_XML

-- create a contract for the message
CREATE CONTRACT [//Audit/Contract]
	([//Audit/Message] SENT BY INITIATOR)

-- create the queue to run the spWriteAuditData automaticaly when new messages arrive
-- execute it as dbo
CREATE QUEUE dbo.TargetAuditQueue
	WITH	STATUS=ON,
	ACTIVATION (
		PROCEDURE_NAME = usp_WriteAuditData,	-- sproc to run when the queue receives a message
		MAX_QUEUE_READERS = 50,					-- max concurrently executing instances of sproc
		EXECUTE AS 'dbo' );

-- create a target service that will accept inbound audit messages
-- set the owner to dbo
CREATE SERVICE [//Audit/DataWriter]
		AUTHORIZATION dbo
	ON QUEUE dbo.TargetAuditQueue ([//Audit/Contract])</pre>
<div>Just replace all instances of <strong>AUDITDB </strong>with the name you want to use.</div>
<h3>Creating/Modifying the database to Audit</h3>
<div><strong>NOTE</strong>: If you are modifying an existing database then you may need to kill all connections to run this script, this happened to me a few times.</div>
<div>The<a href="https://bitbucket.org/ThapLtd/async-database-audit/src/a101da76cbc0/Database%20To%20Audit.sql"> second script</a> sets up the database to allow it to talk to the audit database you just setup; creates the store procedure which will send a message to the audit db queue and create a table to log any auditing problems</div>
<pre class="brush:sql">USE master
GO

IF DB_ID('[DBToAudit]') IS NULL
	CREATE DATABASE [DBToAudit]

-- enable service broker
ALTER DATABASE [DBToAudit] SET ENABLE_BROKER
-- set trustworthy on so we don't need to use certificates
ALTER DATABASE [DBToAudit] SET TRUSTWORTHY ON

GO
USE [DBToAudit]

GO
-- Drop existing service broker items
IF EXISTS(SELECT * FROM sys.services WHERE NAME = '//Audit/DataSender')
	DROP SERVICE [//Audit/DataWriter]

IF EXISTS(SELECT * FROM sys.service_queues WHERE NAME = 'InitiatorAuditQueue')
	DROP QUEUE InitiatorAuditQueue

IF EXISTS(SELECT * FROM sys.service_contracts  WHERE NAME = '//Audit/Contract')
	DROP SERVICE [//Audit/Contract]

IF EXISTS(SELECT * FROM sys.service_message_types WHERE name='//Audit/Message')
	DROP MESSAGE TYPE [//Audit/Message]

GO
-- create a message that must be well formed
CREATE MESSAGE TYPE [//Audit/Message]
	VALIDATION = WELL_FORMED_XML

-- create a contract for the message
CREATE CONTRACT [//Audit/Contract]
	([//Audit/Message] SENT BY INITIATOR)

-- create the initiator queue
CREATE QUEUE dbo.InitiatorAuditQueue

-- create an initiator service that will send audit messages to target service
CREATE SERVICE [//Audit/DataSender]
	AUTHORIZATION dbo
	ON QUEUE dbo.InitiatorAuditQueue	-- no contract means service can only be the initiator

GO
IF OBJECT_ID('dbo.AuditErrors') IS NOT NULL
	DROP TABLE dbo.AuditErrors

GO
-- create Errors table
CREATE TABLE dbo.AuditErrors
(
	Id BIGINT IDENTITY(1, 1) PRIMARY KEY,
	ErrorProcedure NVARCHAR(126) NOT NULL,
	ErrorLine INT NOT NULL,
	ErrorNumber INT NOT NULL,
	ErrorMessage NVARCHAR(4000) NOT NULL,
	ErrorSeverity INT NOT NULL,
	ErrorState INT NOT NULL,
	AuditedData XML NOT NULL,
	ErrorDate DATETIME NOT NULL DEFAULT GETUTCDATE()
)

GO
IF OBJECT_ID('dbo.usp_SendAuditData') IS NOT NULL
	DROP PROCEDURE dbo.usp_SendAuditData

GO
-- stored procedure that sends the audit data to the be audited
CREATE PROCEDURE dbo.usp_SendAuditData
(
	@AuditedData XML
)
AS
BEGIN
	BEGIN TRY
		IF @AuditedData IS NULL
			RETURN
		DECLARE @dlgId UNIQUEIDENTIFIER, @dlgIdExists BIT
		SELECT @dlgIdExists = 1

		-- Check if our database already has a dialog id that was previously used
		-- Why reusing conversation dialogs is a good this is explaind here
		-- http://blogs.msdn.com/remusrusanu/archive/2007/04/24/reusing-conversations.aspx
		-- very well
		SELECT	@dlgId = DialogId
		FROM	[AUDITDB].dbo.AuditDialogs AD
		WHERE	AD.DbId = DB_ID()
		IF 	@dlgId IS NULL
		BEGIN
			SELECT @dlgIdExists = 0
		END

		-- Begin the dialog, either with existing or new Id
		BEGIN DIALOG @dlgId
			FROM SERVICE    [//Audit/DataSender]
			TO SERVICE      '//Audit/DataWriter',
							-- this is a [AUDITDB] Service Broker Id (change it to yours)
							'A688B601-A575-4458-9D7C-1607CD7F540D'
			ON CONTRACT     [//Audit/Contract]
		WITH ENCRYPTION = OFF;

		-- add our db's dialog to AuditDialogs table if it doesn't exist yet
		IF @dlgIdExists = 0
		BEGIN
			INSERT INTO [AUDITDB].dbo.AuditDialogs(DbId, DialogId)
			SELECT	DB_ID(), @dlgId
		END
		--SELECT @AuditedData

		-- Send our data to be audited
		;SEND ON CONVERSATION @dlgId
		MESSAGE TYPE [//Audit/Message] (@AuditedData)
	END TRY
	BEGIN CATCH
		INSERT INTO AuditErrors (
				ErrorProcedure, ErrorLine, ErrorNumber, ErrorMessage,
				ErrorSeverity, ErrorState, AuditedData)
		SELECT	ERROR_PROCEDURE(), ERROR_LINE(), ERROR_NUMBER(), ERROR_MESSAGE(),
				ERROR_SEVERITY(), ERROR_STATE(), @AuditedData
	END CATCH
END

GO</pre>
<div>Replace all instances of <strong>DBToAudit</strong> with the name of your database to audit, replace all instances of <strong>AUDITDB</strong> with the name of the audit database you set up previously and finally replace the GUID (on line 100 or near it) with the GUID generated by the first script.</div>
<h3>Generating Triggers</h3>
<p>The <a href="https://bitbucket.org/ThapLtd/async-database-audit/src/a101da76cbc0/Create%20Audit%20Triggers.sql">final script</a> is generates a trigger for each table that in turn generates a script to pull the changes made during an insert/update/delete operation and sends it to the store procedure generated in the second script. There is nothing to do here but run it <img src='http://blog.tonywilliams.me.uk/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><strong>NOTE</strong>: This script hasn&#8217;t been adapted to ignore tables that store binary information, if you know how to do this then feel free to fork /submit a patch.</p>
<pre class="brush:sql">

DECLARE @sql varchar(max), @TABLE_NAME sysname
SET NOCOUNT ON

SELECT @TABLE_NAME= MIN(TABLE_NAME)
FROM INFORMATION_SCHEMA.TABLES
WHERE
TABLE_TYPE= 'BASE TABLE'
AND TABLE_NAME!= 'sysdiagrams'
AND TABLE_NAME NOT LIKE 'Audit%'

WHILE @TABLE_NAME IS NOT NULL
 BEGIN
EXEC('IF OBJECT_ID (''' + @TABLE_NAME+ '_ChangeTracking'', ''TR'') IS NOT NULL DROP TRIGGER ' + @TABLE_NAME+ '_ChangeTracking')
SELECT @sql = ''
SELECT @sql = @sql+
'
create trigger ' + @TABLE_NAME+ '_ChangeTracking on [' + @TABLE_NAME+ '] for insert, update, delete

as

SET NOCOUNT ON

  declare @bit           int,
          @field         int,
          @maxfield      int,
          @char          int,
          @fieldname     varchar(128),
          @TableName     varchar(128),
          @PKCols        varchar(1000),
          @sql           varchar(2000),
          @UpdateDate    varchar(21),
          @UserName      varchar(128),
          @Type          char(1),
          @PKFieldSelect varchar(1000),
          @PKValueSelect varchar(1000)

  select @TableName = '''+@TABLE_NAME+'''

  select @UserName = system_user,
         @UpdateDate = convert(varchar(8), getdate(), 112) + '' '' +
                       convert(varchar(12), getdate(), 114)

  if exists (select *
             from   inserted)
    if exists (select *
               from   deleted)
      select @Type = ''U''
    else
      select @Type = ''I''
  else
    select @Type = ''D''

  select *
  into   #ins
  from   inserted

  select *
  into   #del
  from   deleted

  select @PKCols = coalesce(@PKCols + '' and'', '' on'') + '' i.'' + c.COLUMN_NAME +
                   '' = d.'' +
                          c.COLUMN_NAME
  from   INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk,
         INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
  where  pk.TABLE_NAME = @TableName
         and CONSTRAINT_TYPE = ''PRIMARY KEY''
         and c.TABLE_NAME = pk.TABLE_NAME
         and c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME

  select @PKFieldSelect = COLUMN_NAME
  from   INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk,
         INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
  where  pk.TABLE_NAME = @TableName
         and CONSTRAINT_TYPE = ''PRIMARY KEY''
         and c.TABLE_NAME = pk.TABLE_NAME
         and c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME

  select @PKValueSelect = coalesce(@PKValueSelect + ''+'', '''') +
                                 ''isnull(convert(nvarchar(100), coalesce(i.'' +
                                                  COLUMN_NAME + '',d.'' +
                          COLUMN_NAME +
                                 '')),'''''''')''
  from   INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk,
         INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
  where  pk.TABLE_NAME = @TableName
         and CONSTRAINT_TYPE = ''PRIMARY KEY''
         and c.TABLE_NAME = pk.TABLE_NAME
         and c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME

  if @PKCols is null
    begin
        raiserror(''no PK on table %s'',
                  16,
                  -1,
                  @TableName)

        return
    end

  select @field = 0,
         @maxfield = max(ORDINAL_POSITION)
  from   INFORMATION_SCHEMA.COLUMNS
  where  TABLE_NAME = @TableName

  while @field < @maxfield
    begin
        select @field = min(ORDINAL_POSITION)
        from   INFORMATION_SCHEMA.COLUMNS
        where  TABLE_NAME = @TableName
               and ORDINAL_POSITION > @field

        select @bit = ( @field - 1 )% 8 + 1

        select @bit = power(2, @bit - 1)

        select @char = ( ( @field - 1 ) / 8 ) + 1

        if substring(COLUMNS_UPDATED(), @char, 1) &#038; @bit > 0
            or @Type in ( ''I'', ''D'' )
          begin
              select @fieldname = COLUMN_NAME
              from   INFORMATION_SCHEMA.COLUMNS
              where  TABLE_NAME = @TableName
                     and ORDINAL_POSITION = @field

             	SELECT @sql =''
             DECLARE @auditBody XML

             	SELECT  @auditBody =
		''''<AuditMsg>
			<DatabaseName>'+DB_NAME()+'</DatabaseName>
			<TableName>'' + @TableName + ''</TableName>
			<DMLType>'' + @Type + ''</DMLType>
			<PrimaryKeyField>'' + @PKFieldSelect + ''</PrimaryKeyField>
			<PrimaryKeyValue>''''+'' + @PKValueSelect + ''+''''</PrimaryKeyValue>
			<FieldName>'' + @fieldname + ''</FieldName>
			<OldValue>''''+isnull(convert(nvarchar(1000),d.'' + @fieldname + ''), '''''''') + ''''</OldValue>
			<NewValue>''''+isnull(convert(nvarchar(1000),i.'' + @fieldname + ''), '''''''') + ''''</NewValue>
			<UpdateDate>'' + @UpdateDate + ''</UpdateDate>
			<UserName>'' + @UserName+ ''</UserName>
		</AuditMsg>''''

	''

    SELECT @sql = @sql + '' from #ins i full outer join #del d''

    SELECT @sql = @sql + @PKCols

    SELECT @sql = @sql + '' where i.'' + @fieldname + '' <> d.'' + @fieldname

    SELECT @sql = @sql + '' or (i.'' + @fieldname + '' is null and  d.'' +
                  @fieldname +
                         '' is not null)''

    SELECT @sql = @sql + '' or (i.'' + @fieldname + '' is not null and  d.'' +
                  @fieldname +
                         '' is null)

				EXEC dbo.usp_SendAuditData @auditBody
                         ''
    exec( @sql)
end
end
'

SELECT @sql
EXEC(@sql)
SELECT @TABLE_NAME= MIN(TABLE_NAME) FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME> @TABLE_NAME
AND TABLE_TYPE= 'BASE TABLE'
AND TABLE_NAME!= 'sysdiagrams'
AND TABLE_NAME NOT LIKE 'Audit%'
END
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.tonywilliams.me.uk/asynchronous-database-auditing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Project Euler: Problem 3</title>
		<link>http://blog.tonywilliams.me.uk/project-euler-problem-3/</link>
		<comments>http://blog.tonywilliams.me.uk/project-euler-problem-3/#comments</comments>
		<pubDate>Sun, 05 Jun 2011 16:05:44 +0000</pubDate>
		<dc:creator>Tony</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Project Euler]]></category>

		<guid isPermaLink="false">http://blog.tonywilliams.me.uk/?p=143</guid>
		<description><![CDATA[Problem: The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143? Source: http://projecteuler.net/index.php?section=problems&#38;id=3 Solution: Before we can being to solved the problem above we first must answer the questions raised by it. In other words: What is a prime number? What is a factor? What [...]]]></description>
			<content:encoded><![CDATA[<h2>Problem:</h2>
<blockquote><p>The prime factors of 13195 are 5, 7, 13 and 29.</p>
<p>What is the largest prime factor of the number 600851475143?</p></blockquote>
<p><em>Source: <a href="http://projecteuler.net/index.php?section=problems&amp;id=3">http://projecteuler.net/index.php?section=problems&amp;id=3</a></em></p>
<p><em><br />
</em></p>
<h2>Solution:</h2>
<p>Before we can being to solved the problem above we first must answer the questions raised by it. In other words:</p>
<ul>
<li>What is a prime number?</li>
<li>What is a factor?</li>
<li>What is a prime factor?</li>
<li>How do we find the prime factors for a number?</li>
</ul>
<p>&nbsp;</p>
<h3>What is a prime number?</h3>
<p>A <a title="Prime Numbers" href="http://en.wikipedia.org/wiki/Prime_number" target="_blank">prime number</a> is any <a title="Natural Numbers Explained" href="http://en.wikipedia.org/wiki/Natural_number" target="_blank">natural number</a> that can only be divided by 1 or itself. E.G. 7 is a prime number because it can only be divided by 1 or 7 while 10 is not a prime number because it&#8217;s divisors are 1,2,5,10.</p>
<p>&nbsp;</p>
<h3>What is a factor?</h3>
<p>A <a title="Factors" href="http://en.wikipedia.org/wiki/Divisor" target="_blank">factor</a> (also known as a divisor) is any number that that can divide in to another number and not leave a remainder. In the previous section about prime numbers you can see the for 10 it&#8217;s factors are:</p>
<ul>
<li>1</li>
<li>2</li>
<li>5</li>
<li>10</li>
</ul>
<p>&nbsp;</p>
<h3>What is a prime factor?</h3>
<p>A <a title="Prime Factors" href="http://en.wikipedia.org/wiki/Prime_factor" target="_blank">prime factor</a> is any factor that is also a prime number.</p>
<p>&nbsp;</p>
<h3>How do we find the prime factors for a number?</h3>
<p>The method of finding prime factors is called <a title="Primer Factorisation" href="http://en.wikipedia.org/wiki/Integer_factorization" target="_blank">Prime Factorisation</a>.  It involves taking a number and dividing it by the smallest prime possible, then taking what&#8217;s remaining and dividing that by the smallest prime possible; keep doing this until the remainder is a prime. This <a title="Prime Factorisation example" href="http://www.khanacademy.org/video/prime-factorization?playlist=Developmental%20Math" target="_blank">Khans Academy</a> video offers a great introduction to this concept.</p>
<p>&nbsp;</p>
<h2>Code:</h2>
<p><em>Source: <a href="https://bitbucket.org/TWith2Sugars/project-euler/src/8892d0a39946/python/3.py">https://bitbucket.org/TWith2Sugars/project-euler/src/8892d0a39946/python/3.py</a></em></p>
<pre class="brush:python">def primeNumbers(n):
    # Found this example on Wikipedia: http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
    # Create a candidate list within which non-primes will be
    # marked as None; only candidates below sqrt(n) need be checked.
    candidates = list(range(n+1))

    # Square root of n
    fin = int(n**0.5)

    # Loop over the candidates, marking out each multiple.
    for i in xrange(2, fin+1):
        if candidates[i]:
            candidates[2*i::i] = [None] * (n//i - 1)

    # Filter out non-primes and return the list.
    return [i for i in candidates[2:] if i]

def primeFactors(n):
    # Generators all of the prime factors for n

    # The largest number that a prime factor could be
    maxPossiblePrimeNumber = int(n**0.5)

    # List of all prime numbers up to the square root of n
    primes = primeNumbers(maxPossiblePrimeNumber)

    while n &gt; 1:
        for p in primes:
            # This is a prime factor
            if n % p == 0:
                # Set n to be the result of the division of n by the current prime number (p)
                n = n / p
                yield p

maxPrime = max(primeFactors(600851475143))
print(maxPrime)</pre>
<p>The code is broken down in to two parts:</p>
<ul>
<li>Generating Prime Numbers (<em>primeNumbers</em>)</li>
<li>Performing Prime Factorisation (<em>primeFactors</em>)</li>
</ul>
<p>&nbsp;</p>
<h3>Generating Prime Numbers</h3>
<p>There are many methods of generating prime numbers and in my search I&#8217;ve decided to use a method called <a title="Generating prime numbers" href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes" target="_blank">Sieve of Eratosthenes</a> which is pretty efficient are generating prime numbers below 100. It also comes with a python example that we can use. You&#8217;ll see the code below.</p>
<p>&nbsp;</p>
<h3>Performing Prime Factorisation</h3>
<p>This function just implemented the method of finding prime factors as mentioned earlier, there is probably a more efficient/mathematical way of doing this but for now it&#8217;s a good start.</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tonywilliams.me.uk/project-euler-problem-3/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Project Euler: Problem 2</title>
		<link>http://blog.tonywilliams.me.uk/project-euler-problem-2/</link>
		<comments>http://blog.tonywilliams.me.uk/project-euler-problem-2/#comments</comments>
		<pubDate>Wed, 25 May 2011 19:54:37 +0000</pubDate>
		<dc:creator>Tony</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Project Euler]]></category>

		<guid isPermaLink="false">http://blog.tonywilliams.me.uk/?p=137</guid>
		<description><![CDATA[Right, here is my attempt at problem 2 of project euler. Problem: http://projecteuler.net/index.php?section=problems&#38;id=2 source: https://bitbucket.org/TWith2Sugars/project-euler/changeset/3ec9f237dbb9 def fib(n): evenSum, a, b = 0, 0, 1 while a &#60; n: a, b = b, a+b if b % 2 == 0: evenSum += b return evenSum; result = fib(4000000) print(result) Update: Thanks to Mohammad&#8217;s advice the code has been [...]]]></description>
			<content:encoded><![CDATA[<p>Right, here is my attempt at problem 2 of project euler.</p>
<p><em>Problem: <a href="http://projecteuler.net/index.php?section=problems&amp;id=2">http://projecteuler.net/index.php?section=problems&amp;id=2</a></em></p>
<p><em>source: <a href="https://bitbucket.org/TWith2Sugars/project-euler/changeset/3ec9f237dbb9">https://bitbucket.org/TWith2Sugars/project-euler/changeset/3ec9f237dbb9</a></em></p>
<pre class="brush:python">def fib(n):
    evenSum, a, b = 0, 0, 1
    while a &lt; n:
        a, b = b, a+b
        if b % 2 == 0:
		    evenSum += b

    return evenSum;

result = fib(4000000)
print(result)</pre>
<h2>Update:</h2>
<p>Thanks to Mohammad&#8217;s advice the code has been update to avoid pointlessly assigning variables.</p>
<pre class="brush:python">def fib(n):
    evenSum, a, b = 0, 1, 2
    while a &lt; n:
        if b % 2 == 0:
		    evenSum += b
        a, b = b, a+b
    return evenSum;

result = fib(4000000)
print(result)</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.tonywilliams.me.uk/project-euler-problem-2/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Project Euler + Python</title>
		<link>http://blog.tonywilliams.me.uk/project-euler-python/</link>
		<comments>http://blog.tonywilliams.me.uk/project-euler-python/#comments</comments>
		<pubDate>Mon, 23 May 2011 13:05:39 +0000</pubDate>
		<dc:creator>Tony</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Project Euler]]></category>

		<guid isPermaLink="false">http://blog.tonywilliams.me.uk/?p=131</guid>
		<description><![CDATA[For a while I&#8217;ve been meaning to play with python but I could never think of something to do with it; so I decided to try and solve as many problems in Project Euler as I can. Here is my mercurial repository on bitbucket: https://bitbucket.org/TWith2Sugars/project-euler This is my attempt at the first problem so far: [...]]]></description>
			<content:encoded><![CDATA[<p>For a while I&#8217;ve been meaning to play with <a href="http://www.python.org">python</a> but I could never think of something to do with it; so I decided to try and solve as many problems in <a href="http://projecteuler.net">Project Euler</a> as I can.</p>
<p>Here is my <a href="http://mercurial.selenic.com/">mercurial</a> repository on bitbucket: <a href="https://bitbucket.org/TWith2Sugars/project-euler">https://bitbucket.org/TWith2Sugars/project-euler</a></p>
<p>This is my attempt at the first problem so far:</p>
<p><em>Problem: <a href="http://projecteuler.net/index.php?section=problems&amp;id=1">http://projecteuler.net/index.php?section=problems&amp;id=1</a></em><br />
<em>source: <a href="https://bitbucket.org/TWith2Sugars/project-euler/src/813d5ec90687/python/1.py">https://bitbucket.org/TWith2Sugars/project-euler/src/813d5ec90687/python/1.py</a></em></p>
<pre class="brush:python">result = 0
for i in range(1000):
    if i % 5 == 0:
	    result += i
    elif i % 3 == 0:
	    result += i

print(result)</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.tonywilliams.me.uk/project-euler-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How I fixed FluentNHibernate.Cfg.FluentConfigurationException on MVC 3</title>
		<link>http://blog.tonywilliams.me.uk/how-i-fixed-fluentnhibernate-cfg-fluentconfigurationexception-on-mvc-3/</link>
		<comments>http://blog.tonywilliams.me.uk/how-i-fixed-fluentnhibernate-cfg-fluentconfigurationexception-on-mvc-3/#comments</comments>
		<pubDate>Wed, 19 Jan 2011 12:55:26 +0000</pubDate>
		<dc:creator>Tony</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Asp.Net MVC3]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[DI]]></category>
		<category><![CDATA[Exception]]></category>
		<category><![CDATA[FluentNHibernate]]></category>
		<category><![CDATA[IoC]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Ninject]]></category>

		<guid isPermaLink="false">http://blog.tonywilliams.me.uk/?p=123</guid>
		<description><![CDATA[How I fixed the problem in the title.]]></description>
			<content:encoded><![CDATA[<p><strong><span style="text-decoration: underline;">Just to let you know this may not solve your version of this error (since it&#8217;s so vague) but it&#8217;s how I solved it in one of my projects.</span></strong></p>
<p>On a previous <a href="http://blog.tonywilliams.me.uk/nhibernate-leaking-connections-with-unitofwork-pattern-and-transactions/">post </a>I mention I was using NHibernate in one of the projects I&#8217;m working on and as such we&#8217;re using <a href="http://fluentnhibernate.org/">FluentNHibernate</a>.</p>
<p>I&#8217;ve created a class (let&#8217;s call it SessionManager) that handles creating the ISessionFactory instance (and stores it in a static field). The project is built with <a href="http://www.asp.net/mvc/mvc3">MVC 3</a> and makes use of the DI provider along with <a href="http://ninject.org/">Ninject</a> so this code snippet should look familiar. (It&#8217;s where you set up you DI &#8211; usually the AppStart_NinjectMVC3)</p>
<pre class="brush:c#">kernel.Bind&lt;ISessionFactory&gt;().ToConstant(SessionManager.CreateSessionFactory());</pre>
<p>That is the line the caused the problems; not sure how but the aspnet compiler dies. In the end I changed ninject to use &#8220;ToMethod&#8221; instead:</p>
<pre class="brush:c#">kernel.Bind&lt;ISessionFactory&gt;().ToMethod(c =&gt; SessionManager.CreateSessionFactory());</pre>
<p>Since the session manager handles creating the ISessionFactory like I mentioned earlier we don&#8217;t get multiple instances of ISessionFactory.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tonywilliams.me.uk/how-i-fixed-fluentnhibernate-cfg-fluentconfigurationexception-on-mvc-3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>NHibernate leaking connections with UnitOfWork pattern and transactions</title>
		<link>http://blog.tonywilliams.me.uk/nhibernate-leaking-connections-with-unitofwork-pattern-and-transactions/</link>
		<comments>http://blog.tonywilliams.me.uk/nhibernate-leaking-connections-with-unitofwork-pattern-and-transactions/#comments</comments>
		<pubDate>Mon, 17 Jan 2011 13:13:59 +0000</pubDate>
		<dc:creator>Tony</dc:creator>
				<category><![CDATA[Asp.Net MVC]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Pattern]]></category>
		<category><![CDATA[UnitOfWork]]></category>

		<guid isPermaLink="false">http://blog.tonywilliams.me.uk/?p=113</guid>
		<description><![CDATA[And how to fix it]]></description>
			<content:encoded><![CDATA[<p>Recently I&#8217;ve been using <a href="http://nhforge.org/Default.aspx">NHibernate</a> in a project at work along with the <a href="http://martinfowler.com/eaaCatalog/unitOfWork.html">unit of work</a> pattern in an asp.net mvc site. Only 1 instance of the UoW is created per request and disposed of at end of the request.</p>
<p>In fact here is a UoW class we&#8217;re using:</p>
<pre class="brush:c#">public class UnitOfWork : INHibernateUnitOfWork
  {
    /// &lt;summary&gt;
    /// The session factory
    /// &lt;/summary&gt;
    private readonly ISessionFactory sessionFactory;

    /// &lt;summary&gt;
    /// The current transaction
    /// &lt;/summary&gt;
    private readonly ITransaction transaction;

    /// &lt;summary&gt;
    /// Gets the session.
    /// &lt;/summary&gt;
    /// &lt;value&gt;The session.&lt;/value&gt;
    public ISession Session { get; private set; }

    /// &lt;summary&gt;
    /// Initializes a new instance of the &lt;see cref="UnitOfWork"/&gt; class.
    /// &lt;/summary&gt;
    /// &lt;param name="sessionFactory"&gt;The session factory.&lt;/param&gt;
    public UnitOfWork(ISessionFactory sessionFactory)
    {
      this.sessionFactory = sessionFactory;

      Session = this.sessionFactory.OpenSession();
      Session.FlushMode = FlushMode.Auto;
      transaction = Session.BeginTransaction();
    }

    /// &lt;summary&gt;
    /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
    /// &lt;/summary&gt;
    public void Dispose()
    {
      transaction.Dispose();
    }

    /// &lt;summary&gt;
    /// Commits this instance.
    /// &lt;/summary&gt;
    public void Commit()
    {
      if (!transaction.IsActive)
      {
        throw new InvalidOperationException("No active transation");
      }

     /transaction.Commit();
    }

    /// &lt;summary&gt;
    /// Rollbacks this instance.
    /// &lt;/summary&gt;
    public void Rollback()
    {
      if (transaction.IsActive)
      {
        transaction.Rollback();
      }
    }
  }</pre>
<p>As you can see in the constructor we create a new NHibernate transaction and dispose of it when the request ends (by calling the dispose method).</p>
<p>The problem with this is that it created a connection with an open transaction but never closed it. Any way to resolve this we removed the use of transactions (until such a time they are working or we&#8217;ve figured out a suitable alternative). Two changes where made to the dispose and commit method to clean up the session instance and make sure the data is flushed.</p>
<pre class="brush:c#">    public void Dispose()
    {
      Session.Dispose();
    }

    public void Commit()
    {
      Session.Flush();
    }</pre>
<p><strong>Note: </strong>This project also is using the Velocity cache provider and by removing the transactions / replacing the code the caching mechanisms still work.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tonywilliams.me.uk/nhibernate-leaking-connections-with-unitofwork-pattern-and-transactions/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>

