Click here to Skip to main content
15,917,320 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I created a web app with sign-in and sign-up facility in my college project.
And when the user is login he has some authority for CRUD operations. When he creates from his authority I send a notification to his email with some information using SMTP protocol, this is working fine.
My Questions:
1. But when something goes wrong during the data saving to a database and sending an email to he/she, how I roll back those changes?
2. How to apply transaction for email service and creation?
3. Is I'm on the right path or not?

What I have tried:

From my research, I found the transaction is used to roll back the changes? (see my second question)
Any Something else is there please tell me.


Thank you.
Posted
Updated 26-Aug-19 6:01am

1 solution

Transactions are fairly simple: You create a transaction before you make any changes, then you either Commit it when they all work, or Rollback if something fails:

C#
private void DoDB(...)
    {
    string strConnect = SMDBSupport.SMInstanceStorage.GetInstanceConnectionString("Testing");
    using (SqlConnection con = new SqlConnection(strConnect))
        {
        con.Open();
        SqlTransaction transaction = con.BeginTransaction("MyTransaction");
        try
            {
            using (SqlCommand cmd = new SqlCommand("...", con))
                {
                 ...
                cmd.ExecuteNonQuery();
                }
            using (SqlCommand cmd = new SqlCommand("...", con))
                {
                 ...
                cmd.ExecuteNonQuery();
                }
            transaction.Commit();
            }
        catch (Exception ex)
            {
            transaction.Rollback();
            Console.WriteLine(ex.Message);
            }
        }
    }
 
Share this answer
 
Comments
Maciej Los 26-Aug-19 13:31pm    
5ed!
SSP0055 26-Aug-19 13:49pm    
what about email transaction?
OriginalGriff 26-Aug-19 14:00pm    
What on earth do you think an email transaction is?
SSP0055 26-Aug-19 14:07pm    
what if the database saves the data into table and exception is thrown from the email handling process? how would I handle those process?
So here, the email process is dependent on the creation process...How would I handle it?
OriginalGriff 26-Aug-19 14:12pm    
What email process?
If you put the Commit at the end of the try block, any exception inside the try block will cause a Rollback via the catch block - it doesn't matter what caused the exception. So if you have problems with emails, send it before the Commit and a failure will Rollback the DB.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900