[CSHARP-2277] Provide Transactions example for Docs Created: 23/May/18  Updated: 28/Oct/23  Resolved: 26/Jun/18

Status: Closed
Project: C# Driver
Component/s: None
Affects Version/s: None
Fix Version/s: 2.7.0

Type: Improvement Priority: Major - P3
Reporter: Rathi Gnanasekaran Assignee: Robert Stam
Resolution: Fixed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Depends
is depended on by DRIVERS-488 Provide Transactions example for Docs Closed
Epic Link: CSHARP MongoDB 4.0 Support

 Description   

Hi –
for the manual – would like to pop in driver examples in
Drivers section and Retry section

If we could get the corresponding driver examples.

  • The Intro example will be for the Drivers section – where it's to highlight – how to use a transaction, and the section will be emphasizing the passing of the session to the operations in the txn.
  • The retry examples will of course be in the retry section.

// Start Transactions Intro Example 1
 
function updateEmployeeInfo(session) {
    employeesCollection = session.getDatabase("hr").employees;
    eventsCollection = session.getDatabase("reporting").events;
 
    session.startTransaction( { readConcern: { level: "snapshot" }, writeConcern: { w: "majority" } } );
 
    try{
        employeesCollection.updateOne( { employee: 3 }, { $set: { status: "Inactive" } } );
        eventsCollection.insertOne( { employee: 3, status: { new: "Inactive", old: "Active" } } );
    } catch (error) {
        print("Caught exception during transaction, aborting.");
        session.abortTransaction();
        throw error;
    }
 
    while (true) {
        try {
            session.commitTransaction(); // Uses write concern set at transaction start.
            print("Transaction committed.");
            break;
        } catch (error) {
            // Can retry commit
            if (error.hasOwnProperty("errorLabels") && error.errorLabels.includes("UnknownTransactionCommitResult") ) {
                print("UnknownTransactionCommitResult, retrying commit operation ...");
                continue;
            } else {
                print("Error during commit ...");
                throw error;
            }
       }
    }
}
// End Transactions Intro Example 1
 
 
// Start Transactions Retry Example 1
function runTransactionWithRetry(txnFunc, session) {
    while (true) {
        try {
            txnFunc(session);  // performs transaction
            break;
        } catch (error) {
            print("Transaction aborted. Caught exception during transaction.");
 
            // If transient error, retry the whole transaction
            if ( error.hasOwnProperty("errorLabels") && error.errorLabels.includes( "TransientTransactionError")  ) {
                print("TransientTransactionError, retrying transaction ...");
                continue;
            } else {
                throw error;
            }
        }
    }
}
// End Transactions Retry Example 1
 
// Start Transactions Retry Example 2
 
function commitWithRetry(session) {
    while (true) {
        try {
            session.commitTransaction(); // Uses write concern set at transaction start.
            print("Transaction committed.");
            break;
        } catch (error) {
            // Can retry commit
            if (error.hasOwnProperty("errorLabels") && error.errorLabels.includes( "UnknownTransactionCommitResult") ) {
                print("UnknownTransactionCommitResult, retrying commit operation ...");
                continue;
            } else {
                print("Error during commit ...");
                throw error;
            }
       }
    }
}
// End Transactions Retry Example 2
 
// Start Transactions Retry Example 3
 
function runTransactionWithRetry(txnFunc, session) {
    while (true) {
        try {
            txnFunc(session);  // performs transaction
            break;
        } catch (error) {
            // If transient error, retry the whole transaction
            if ( error.hasOwnProperty("errorLabels") && error.errorLabels.includes("TransientTransactionError")  ) {
                print("TransientTransactionError, retrying transaction ...");
                continue;
            } else {
                throw error;
            }
        }
    }
}
 
function commitWithRetry(session) {
    while (true) {
        try {
            session.commitTransaction(); // Uses write concern set at transaction start.
            print("Transaction committed.");
            break;
        } catch (error) {
            // Can retry commit
            if (error.hasOwnProperty("errorLabels") && error.errorLabels.includes("UnknownTransactionCommitResult") ) {
                print("UnknownTransactionCommitResult, retrying commit operation ...");
                continue;
            } else {
                print("Error during commit ...");
                throw error;
            }
       }
    }
}
 
// Updates two collections in a transactions
 
function updateEmployeeInfo(session) {
    employeesCollection = session.getDatabase("hr").employees;
    eventsCollection = session.getDatabase("reporting").events;
 
    session.startTransaction( { readConcern: { level: "snapshot" }, writeConcern: { w: "majority" } } );
 
    try{
        employeesCollection.updateOne( { employee: 3 }, { $set: { status: "Inactive" } } );
        eventsCollection.insertOne( { employee: 3, status: { new: "Inactive", old: "Active" } } );
    } catch (error) {
        print("Caught exception during transaction, aborting.");
        session.abortTransaction();
        throw error;
    }
 
    commitWithRetry(session);
}
 
// Start a session.
session = db.getMongo("myRepl/mongodb0.example.net:27017,mongodb1.example.net:27017,mongodb2.example.net:27017").startSession( { mode: "primary" } );
 
try{
   runTransactionWithRetry(updateEmployeeInfo, session);
} catch (error) {
   // Do something with error
} finally {
   session.endSession();
}
 
// End Transactions Retry Example 3



 Comments   
Comment by Kay Kim (Inactive) [ 21/Aug/18 ]

Thank you for doing work

Comment by Vincent Kam (Inactive) [ 21/Aug/18 ]

kay.kim Thanks for noticing! I've pushed a fix

Comment by Kay Kim (Inactive) [ 09/Aug/18 ]

rstam – just noticed a small typo – where the label is misspelled.

Example 2 has:

 
            if (exception.HasErrorLabel("UnknwonTransactionCommitResult"))

Example 3 has

                Console.WriteLine("UnknwonTransactionCommiResult, retrying commit operation");

Comment by Kay Kim (Inactive) [ 27/Jun/18 ]

Thanks much! They're out there now

Comment by Robert Stam [ 26/Jun/18 ]

The examples can be found in this folder:

 

https://github.com/mongodb/mongo-csharp-driver/tree/master/tests/MongoDB.Driver.Examples/TransactionExamplesForDocs

 

Comment by Githook User [ 26/Jun/18 ]

Author:

{'username': 'rstam', 'name': 'rstam', 'email': 'robert@robertstam.org'}

Message: CSHARP-2277: Provide Transactions example for Docs.
Branch: master
https://github.com/mongodb/mongo-csharp-driver/commit/58a73d5543c8105cba210f361d28caaf82458ae8

Generated at Wed Feb 07 21:42:06 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.