.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
Easy Web
Imran Ghani
Post New Web Links

sqldatasource with transaction

Posted By:      Posted Date: September 30, 2010    Points: 0   Category :ASP.Net
 

hi, i have an "sqldatasource" attached to a formview. When ever an update requst is made through this datasource "onupdating" event fires. I wrote the following code in the event handler function

protected void FormViewDataSource_Updating(object sender, SqlDataSourceCommandEventArgs e)
    {
        DbCommand cmd = e.Command;
        DbConnection con = cmd.Connection;
        con.Open();
        DbTransaction trans = con.BeginTransaction();
        cmd.Transaction = trans;
    }


To commit the transaction, i wrote the following code in the event handler routine of "onupdated" event.

protected void FormViewDataSource_Updated(object sender, SqlDataSourceStatusEventArgs e)
    {
        DbTransaction trans = e.Command.Transaction;
        if (e.Exception != null)
        {
            trans.Commit();
        }
        else
        {
            Response.Write(e.Exception.Message);
            try
            {
                trans.Rollback();
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }
    }

But the problem is that, the event "onupdate" fires only after the transaction is succeeded. So where should i check and commit the transaction. Please help.

View Complete Post


More Related Resource Links

sqldatasource with transaction

  

hi, i have an "sqldatasource" attached to a formview. When ever an update requst is made through this datasource "onupdating" event fires. I wrote the following code in the event handler function

protected void FormViewDataSource_Updating(object sender, SqlDataSourceCommandEventArgs e)
    {
        DbCommand cmd = e.Command;
        DbConnection con = cmd.Connection;
        con.Open();
        DbTransaction trans = con.BeginTransaction();
        cmd.Transaction = trans;
    }


To commit the transaction, i wrote the following code in the event handler routine of "onupdated" event.

protected void FormViewDataSource_Updated(object sender, SqlDataSourceStatusEventArgs e)
    {
        DbTransaction trans = e.Command.Transaction;
        if (e.Exception != null)
        {
            trans.Commit();
        }
        else
        {
            Response.Write(e.Exception.Message);
            try
            {
                trans.Rollback();
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }
    }

But the problem is that, the event "onupdate" fires only after the transaction is succeeded. So where should i check and commit the transaction. Please help.


SQL Server Database Transaction

  
A transaction is a group of SQL commands executed together as a single component of work to be accomplished. If all of these commands succeed, then a transaction is committed - the changes to the data are made final. If any of the commands within a transaction fail, then the entire transaction is cancelled, or in SQL Server terms, the transaction will be rolled back.

Transactions are one of the things that keep your data safe, but they're not necessarily easy to understand. Here's some help:

How to retrieve data from SqlDataSource and pass to a variable?

  

Hi there,

I have a page in my website where there is very little code-behind. I only have two lines of code in Page_Load() and the rest of the code is declarative ASP.NET code. I have a FormView control which uses a SqlDataSource to get some order information. The SqlDataSource calls a stored procedure called usp_GetOrderDetails, here's the code for the SqlDataSource:

    <asp:SqlDataSource ID="sdsFormOrderDetails" runat="server" 
ConnectionString="<%$ ConnectionStrings:ForexDB %>"
ProviderName="<%$ ConnectionStrings:ForexDB.ProviderName %>"
SelectCommand="usp_GetOrderDetails" SelectCommandType="StoredProcedure"
UpdateCommand="usp_UpdateOrder" UpdateCommandType="StoredProcedure"
>
<SelectParameters>
<asp:ControlParameter Name="orderId" ControlID="grdOrders" PropertyName="SelectedDataKey.Value" />
</SelectParameters>
<UpdateParameters>
<asp:ControlParameter Name="orderId" ControlID="frmOrderDetails" PropertyName="SelectedValue" />
</UpdateParameters>
</asp:SqlDataSource>

Binding GridView with SqlDataSource at runtime?

  

Hi, I want to create a generic page which contains a gridview and sqldatasource. I want to put these two controls on .aspx (C#) page but bind them at runtime. It should have selectcommand, updatecommand, deletecommand and insertcommand. Stored procedures are created for that. Help is needed to make it. Please post some link or code. Regards, ap.


SqlDataSource how to change the stored procedures at run time

  

Hi

Is it possible to change the select, insert and update stored procedure of an SqlDataSource at run time. I don't mean to change the definition of the stored procedure, but I mean to change the assignment, i.e. To change the select stored procedure from "selectSP1" to "selectSP2" at run time. Is it possible?

Regards

Dimitris


SqlDataSource UpdateCommand using 2 tables

  

I have two tables

Trans  with fields TransID, Date, CustomerID and some other stuff

Customer with fields CustomerID, Name, TaxId

On the screen the user only sees the fields Date and Customer Name. CustomerID is behind the scenes only.

 

I'm using SqlDataSource. Having no problems with SelectCommand. I don't know how to construct the UpdateCommand and InsertCommand.

Let's say the user changes the date, then I need to do an UPDATE.

UPDATE Trans SET Date = @Date, CustomerID = @CustomerID results in an error message and the record is not updated.

I get an error on the page that says "Sys.WebForms.PageRequestManagerServerErrorException: Input string was not in correct format".

 

I tried taking out the set for CustomerID and I still get the error on page.

 

Also, for inserting, the users will see a dropdownlist with Customer Names. I need to convert that to a CustomerID to be used in the new record being inserted in the database. I'm not sure how to do this.

 

Do I need to do something with Control Parameters?


Multiple web methods in one transaction

  

Hi everyone

Sorry I am kinda new in web services, so it may sound a bit newbish question.

We have a web service that comunicates with the database and exposes web methods that enables the application to access the database. Each method does only one operation (Insert, Update or Delete). What I need to do is create a transaction that will be consisted of multiple calls to the database, meaning multiple calls of more then one web methods. Can I do that? (I read that if the web method does not throw exception - or ContextUtil.SetAbort() is not called - the transaction will be commited automatically when the web method finishes executing, which I don't want to happen because I want to call another web method in the same transaction, and then manually commit the transaction)

Thank you in advance.


Web Services: Capturing and Analyzing Client Transaction Metrics for .NET-Based Web Services

  

This article presents a general-purpose client quality reporting mechanism that can be used in any .NET-based transaction system that employs HTTP/SOAP. The design uses client response time and quality recording, upload of logs as SOAP headers attached to new transaction requests, and server handoff of these headers to a low priority queue for logging and analysis. This technique gives an enterprise near real-time information on actual end-user response times. These response times reflect network delays, client application overhead and server delays. By using this technique, enterprises can avoid the need to develop custom software to mine HTTP logs.

Brian Connolly

MSDN Magazine July 2004


Using SqlDataSource as the Datasource to Accordion

  

Hi,

The accordion does not renders. What am I missing? I want to use a parent child kind of accordion. Perhaps the child is not defined correctly, but I would like to see at list the seven tabs with the name of each organ system show up. The numbers of records for each organ system varies and I need a text box for each organ/tissue to be displayed, so I can insert in a findings table.

Here is what I have

new protected void Page_Load(object sender, EventArgs e)
        {
            ModalPanel.Visible = false;
            ds1 = GetSqlOrganSystems();
            Page.Controls.Add(ds1);
          
        }

protected SqlDataSource GetSqlOrganSystems()
        {

         SqlDataSource dsL = new SqlDataSource();
            dsL.ID = "ds1";
            //#DataBinder.Eval(Container.DataItem,"Organ_System_ID" DataBinder.Ev

SqlDataSource and Parameters query

  

Hi everyone,

I'm on the edge wondering is it possible ? I have got 2 questions. Please help me out.

1. I have a GridView on my page and it uses sqldatasource with parameterized query. What I want to do is, on page load (where nothing has been selected so no parameter supplied), I want it to query everything (something like SELECT * FROM [this_table]) but since my SelectCommand is something like

SELECT * FROM [this_table] WHERE [this_column] = @someParameters AND [that_column] = @someParameters.

Can I play around with default value to achieve something like that but how ? Now, when the page loads, it doesn't show anything (No Gridview).

2. On my page, I made something like (username, gender, address, and more) and one single search button. That means, no single control enable auto postback. What I am trying to accomplish is building dynamic query

(if username specifed -> SELECT * FROM [this_table] WHERE [username] LIKE @username).

If both username and gender are specified (SELECT * FROM [this_table] WHERE [username] LIKE @username AND [gender] = @gender) and you know the rest. How can I do this using GridView and SqlDataSource ? To my knowledge, I can only specify one SELECT statement in a sqldatasource.  I am stucked and desparately looking for help. Thanks all.


sqldatasource's filter returns too few records

  

I have a puzzling issue.  This is in asp.net 2.0, using vb.  I have a gridview that is bound to a sqldatasource.  Here is the datasource code:

<asp:SqlDataSource ID="fellowsSqlDataSource" runat="server"
        ConnectionString="<%$ ConnectionStrings:PFPFellowsConnectionString %>"
        ProviderName="<%$ ConnectionStrings:PFPFellowsConnectionString.ProviderName %>"
        SelectCommand="usp_v_fellows2"
        SelectCommandType="StoredProcedure"
        UpdateCommandType="StoredProcedure"
        UpdateCommand="usp_edit_selected"
        FilterExpression="{0}"  >
        <SelectParameters>
            <asp:SessionParameter Name="psuaccessid" SessionField="username" />         
        </SelectParameters>
         <UpdateParameters>

Gridview Update outside of SqlDatasource

  

Is it possible to use a SQLDataSource to populate a gridview but not use the SQLDataSource for Updating?

I wanted to add the update code in the Gridview_RowUpdating event since it is a complex update I need to do.


I get this message when i click the update button


Updating is not supported by data source 'SqlDataSource1' unless UpdateCommand is specified.


dropdownlist bound to sqldatasource adds items instead of replacing on change

  

Hello,

I have a series of dropdownlists on webform in ASP 4.0. The first drop down is filled upon load, and then when a user selects a value from that list, it populates the second dropdown. To accomplish this, I have a SQLdatasource with a parametersource of the first drop-down list control. This works great, except when a user changes their selection from the first drop down. It performs the query, but then adds the list of items to the ones that were already there from the previous selection, instead of replacing it with the new data. Here is the code:


 <asp:DropDownList ID="ddlMajor" runat="server" DataMember="DefaultView" 
      DataSourceID="SqlDataSource1" DataTextField="majortext" 
      DataValueField="majorkey" AppendDataBoundItems="True" AutoPostBack="True">
         <asp:ListItem Value="0">Select Major</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="ddlReq" runat="server" DataMember="DefaultView" 
      DataSourceID="SqlDataSource2" DataTextField="req" DataValueField="admreqkey" 
            AppendDataBoundItems="True" AutoPostBack="True">
                <asp:ListItem Value="0">Sel

SSIS Package Transaction locks entire table

  
Hello, I have SSIS package that using transactions and working as expected. But this locks all the tables involved in the data flow that are get inserted/loaded. If I query those tables during package execution the query waits till SSIS releases the lock. But I can still query those tables using NOLOCK hint. Is this possible SSIS will lock only the rows that it insert/update/delete etc? So that other user can still use that table or another instance of same SSIS Package can load data into those tables? My Package: In the package level I have TransactionOption = Required. The Sequence (Data Flow is inside this sequence) TransactionOption = Supported. I had some issue in my package that I posted here: http://social.msdn.microsoft.com/Forums/en-US/sqlintegrationservices/thread/dfb5a8b9-d43c-452b-bb21-d6aea192fc97 and also resolved. Now I descovered this issue and trying to resolve. Thanks, Prabhat

CLR Trigger with stored procedures - transaction error

  
Hi, I've developed sample CLR trigger which call stored procedure but if execution of stored procedure fail I got following exception The context transaction which was active before entering user defined routine, trigger or aggregate "CskTest" has been ended inside of it, which is not allowed. Change application logic to enforce strict transaction nesting. The statement has been terminated.  My trigger [SqlTrigger(Event = "FOR INSERT", Name = "CskTest", Target = "Requirement")] public static void HandleRequirement() { using ( SqlConnection conn = new SqlConnection("Context Connection=true") ) { SqlCommand cmd = conn.CreateCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "Test"; conn.Open(); try { cmd.ExecuteNonQuery(); } catch ( Exception ex ) { SqlContext.Pipe.Send(ex.Message); } } } I wanna handle this exception in my catch block. How can I do this?

Return value from SqlDataSource in GridView ?

  
Hi, everyone. I have textbox for searching a Names in My database. I return the information from the Select Statement in  GridView, but i want to know the number of affecter rows. How to do that?
Categories: 
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend