Using Explicit Transactions using CommittableTransaction : Transaction SqlConnection « ADO.net Database « ASP.Net






Using Explicit Transactions using CommittableTransaction

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Transactions" %>
<%@ Import Namespace="System.Web.Configuration" %>
<script runat="server">
    void btnSave_Click(object sender, EventArgs e) {
        CommittableTransaction trans = new CommittableTransaction();
        try {
            string connectionString =  WebConfigurationManager.ConnectionStrings["AdventureWorks"].ConnectionString;
            using (SqlConnection connection = new SqlConnection(connectionString)) {
                string sql = "Insert into Production.ProductCategory(Name,rowguid, ModifiedDate) Values(@Name, @rowguid, @ModifiedDate)";
                connection.Open(); 
                SqlCommand command = new SqlCommand(sql, connection);
                command.CommandType = CommandType.Text;
                SqlParameter nameParam = new SqlParameter("@Name", SqlDbType.NVarChar, 50);
                nameParam.Value = txtCategoryName.Text;
                command.Parameters.Add(nameParam);
                SqlParameter guidParam = new SqlParameter("@rowguid", SqlDbType.UniqueIdentifier);
                guidParam.Value = System.Guid.NewGuid();
                command.Parameters.Add(guidParam);
                SqlParameter modifieDateParam = new SqlParameter("@ModifiedDate", SqlDbType.DateTime);
                modifieDateParam.Value = System.DateTime.Now;
                command.Parameters.Add(modifieDateParam);
                
                connection.EnlistTransaction(trans);
                command.ExecuteNonQuery();

                trans.Commit();
            }
            lblResult.Text = "Category is written successfully";            
        }
        catch (Exception ex)
        {

            trans.Rollback();
            lblResult.Text = "Exception is : " + ex.Message;            
        }
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Using Explicit Transactions using CommittableTransaction</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="lblCategoryName" runat="server" Text="Category Name:" Width="179px"></asp:Label>        
        <asp:TextBox ID="txtCategoryName" runat="server"/>               
        &nbsp;
        <asp:Button ID="btnSave" runat="server" Text="Save" Width="92px" OnClick="btnSave_Click"/>        
        <br/><br/>
        <asp:Label ID="lblResult" runat="server" Font-Bold="true" Font-Size="Small" />
    </div>
    </form>
</body>
</html>

 








Related examples in the same category

1.Working with Transactions with an SQL Server Database
2.Open connection and begin transaction
3.Implicit Transactions using TransactionScope