How use Transaction within an ASMX Web Service? RRS feed

  • Question

  • User-1286071582 posted

    i begin use Transaction in Web Service. i use C# and begin insert with Transaction. But i don't insert to database.

    Code WebService.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Services;
    using System.Data.SqlClient;
    using System.Data;
    [WebService(Namespace = "example.org")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class WebService : System.Web.Services.WebService 
    SqlConnection conn;
    SqlCommand comm1, comm2, comm3;
    SqlTransaction trans;
    SqlDataAdapter adapter1, adapter2;
    DataSet ds1, ds2;
    string constring = "Database=transaction;server=localhost;user=sa;password=toon2255";
    [WebMethod(Description = "Transaction")]
    public string transaction(int userid, int amount)
    conn = new SqlConnection(constring);
    comm2 = new SqlCommand("INSERT INTO moneytrans VALUES('" + userid + "','" + amount + "')");
    trans = conn.BeginTransaction();
    comm2.Transaction = trans;
    return "Transaction Complted. ";
    catch (Exception)
    return "Transaction Failed..";

    Code Default.aspx.cx (Website)

    using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Web;
        using System.Web.UI;
        using System.Web.UI.WebControls;
        protected void btnok_Click(object sender, EventArgs e)
                WSLogin.WebService obj = new WSLogin.WebService();
                lblmsg.Text = obj.transaction(Convert.ToInt32(txtuserid.Text), Convert.ToInt32(txtamount.Text));

    i want Result "Transaction Compelted" and insert to database complete.

    But Result now "Transaction Failed.."
    This Line Error: comm2.ExecuteNonQuery();

    Transaction Failed: System.InvalidOperationException: ExecuteNonQuery:
    Connection property has not been initialized. at System.Data.SqlClient.SqlCommand.ValidateCommand(String method,Boolean async) at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout,
    Boolean asyncWrite) at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at
    WebService.transaction(Int32 userid, Int32 amount) in c:\WEB\WebSites\App_Code\WebService.cs:line 49

    Thanks you for your time. :)

    Wednesday, October 16, 2013 11:43 AM


  • User-488622176 posted
    comm2 = new SqlCommand(...)

    Ok, but you still need to set comm2.Connection = conn;

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, October 17, 2013 9:53 AM