开发者

SQL Server CLR Integration enlisting in current transaction

I'm trying to use CLR integration in SQL Server to handle accessing external files instead of storing them internally as BLOBs. I'm trying to figure out the pattern I need to follow to make my code enlist in the current SQL transaction. I figured I would start with the simplest scenario, deleting an existing row, since the insert/update scenarios would be more complex.

[SqlProcedure]
public static void DeleteStoredImages(SqlInt64 DocumentID)
{
    if (DocumentID.IsNull)
        return;

    using (var conn = new SqlConnection("context connection=true"))
    {
        conn.Open();

        string FaceFileName, RearFileName;
        int Offset, Length;
        GetFileLocation(conn, DocumentID.Value, true,
            out FaceFileName, out Offset, out Length);
        GetFileLocation(conn, DocumentID.Value, false,
            out RearFileName, out Offset, out Length);

        new DeleteTransaction().Enlist(FaceFileName, RearFileName);

        using (var comm = conn.CreateCommand())
        {
            comm.CommandText = "DELETE FROM ImagesStore WHERE DocumentID = " + DocumentID.Value;
            comm.ExecuteNonQuery();
        }
    }
}

private class DeleteTransaction : IEnlistmentNotific开发者_如何学编程ation
{
    public string FaceFileName { get; set; }
    public string RearFileName { get; set; }
    public void Enlist(string FaceFileName, string RearFileName)
    {
        this.FaceFileName = FaceFileName;
        this.RearFileName = RearFileName;
        var trans = Transaction.Current;
        if (trans == null)
            Commit(null);
        else
            trans.EnlistVolatile(this, EnlistmentOptions.None);
    }
    public void Commit(Enlistment enlistment)
    {
        if (FaceFileName != null && File.Exists(FaceFileName))
        {
            File.Delete(FaceFileName);
        }
        if (RearFileName != null && File.Exists(RearFileName))
        {
            File.Delete(RearFileName);
        }
    }

    public void InDoubt(Enlistment enlistment)
    {
    }

    public void Prepare(PreparingEnlistment preparingEnlistment)
    {
        preparingEnlistment.Prepared();
    }

    public void Rollback(Enlistment enlistment)
    {
    }
}

When I actually try to run this, I get the following exception:

A .NET Framework error occurred during execution of user defined routine or aggregate 'DeleteStoredImages': 
System.Transactions.TransactionException: The operation is not valid for the state of the transaction. ---> System.Transactions.TransactionPromotionException: MSDTC on server 'BD009' is unavailable. ---> System.Data.SqlClient.SqlException: MSDTC on server 'BD009' is unavailable.
System.Data.SqlClient.SqlException: 
   at System.Data.SqlServer.Internal.StandardEventSink.HandleErrors()
   at System.Data.SqlServer.Internal.ClrLevelContext.SuperiorTransaction.Promote()
System.Transactions.TransactionPromotionException: 
   at System.Data.SqlServer.Internal.ClrLevelContext.SuperiorTransaction.Promote()
   at System.Transactions.TransactionStatePSPEOperation.PSPEPromote(InternalTransaction tx)
   at System.Transactions.TransactionStateDelegatedBase.EnterState(InternalTransaction tx)
System.Transactions.TransactionException: 
   at System.Transactions.TransactionState.EnlistVolatile(InternalTransaction tx, IEnlistmentNotification enlistmentNotification, EnlistmentOptions enlistmentOptions, Transaction atomicTransaction)
   at System.Transactions.TransactionStateSubordinateActive.EnlistVolatile(InternalTransaction tx, IEnlistmentNotification enlistmentNotification, EnlistmentOptions enlistmentOptions, Transaction atomicTransaction)
   at System.Transactions.Transaction.EnlistVolatile(IEnlistmentNotification enlistmentNotification, EnlistmentOptions enlistmentOptions)
   at ExternalImages.StoredProcedures.DeleteTransaction.Enlist(String FaceFileName, String RearFileName)
   at ExternalImages.StoredProcedures.DeleteStoredImages(SqlInt64 DocumentID)
. User transaction, if any, will be rolled back.
The statement has been terminated.

Can anyone explain what I'm doing wrong, or point me to an example of how to do it right?


You have hopefully solved this by now, but in case anyone else has a similar problem: the error message you are getting suggests that you need to start the Distributed Transaction Coordinator service on the BD009 machine (presumably your own machine).


@Aasmund's answer regarding the Distributed Transaction Coordinator might solve the stated problem, but that still leaves you in a non-ideal state: You are tying a transaction, which locks the ImagesStore table (even if it is just a RowLock), to two file system operations? And you need to BEGIN and COMMIT the transaction outside of this function (since that isn't being handled in the presented code).

I would separate those two pieces:

  • Step 1: Delete the row from the table

    and then, IF that did not error,

  • Step 2: Delete the file(s)

In the scenario where Step 1 succeeds but then Step 2, for whatever reason, fails, do one or both of the following:

  • return an error status code and keep track of which DocumentIDs got an error when attempting to delete the file in a status table. You can use that to manually delete the files and/or debug why the error occurred.

  • create a process that can run periodically to find and remove unreferenced files.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜