473,662 Members | 2,454 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Place of BeginTransactio n in code

Hi all,
Consider this code

SqlConnection oConn = new
SqlConnection(A ccountsConnecti onString);
SqlCommand cmdInsert = new SqlCommand("Upd ateQuery");
//Location 1:
//SqlTransaction sqlTran = oConn.BeginTran saction();
try
{
oConn.Open();
//Location 2:
//SqlTransaction sqlTran = oConn.BeginTran saction();
cmdInsert.Execu teNonQuery();
sqlTran.Commit( );
}
catch (Exception ex)
{
//Location 3:
sqlTran.Rollbac k();
}
finally
{
oConn.Close();
}

I have to start a transaction and commit or rollback depending upon the
condition of success of command execution. The problem is if I write
code to Begin Transaction at location 1 it won't work as connection is
still closed. If I write the same at location 2, I won't be able to
rollback transaction at location 3 as sqlTran object is out of
referance. What should I do? I am using framework 2.0.

Thanks and Regards
Chakravarti Mukesh

Oct 10 '06 #1
20 10305
On Oct 10, 8:09 am, "Mukesh" <cmukes...@gmai l.comwrote:
SqlConnection oConn = new
SqlConnection(A ccountsConnecti onString);
SqlCommand cmdInsert = new SqlCommand("Upd ateQuery");
//Location 1:
//SqlTransaction sqlTran = oConn.BeginTran saction();
try
{
oConn.Open();
//Location 2:
//SqlTransaction sqlTran = oConn.BeginTran saction();
cmdInsert.Execu teNonQuery();
sqlTran.Commit( );
}
catch (Exception ex)
{
//Location 3:
sqlTran.Rollbac k();
}
finally
{
oConn.Close();
}
Declare the transaction variable in Location 1, but Begin it in
location 2:

SqlConnection oConn = new
SqlConnection(A ccountsConnecti onString);
SqlCommand cmdInsert = new SqlCommand("Upd ateQuery");
//Location 1:
SqlTransaction sqlTran = null;
try
{
oConn.Open();
//Location 2:
sqlTran = oConn.BeginTran saction();
cmdInsert.Execu teNonQuery();
sqlTran.Commit( );
}
catch (Exception ex)
{
//Location 3:
sqlTran.Rollbac k();
}
finally
{
oConn.Close();
}

Oct 10 '06 #2
Declare the transaction object outside the try/catch. Just don't set it to
anything. Then, after you open the connection, inside the try block, set
the variable to the new transaction.

There is no law that says you have to declare the variable and set it to
something in the same line. You can declare everything at the top of your
method, and then use it later. In fact, that is my personal preference,
just to see all the variables involved in my method, so I don't have to
track them down throughout the method.

"Mukesh" <cm*******@gmai l.comwrote in message
news:11******** *************@k 70g2000cwa.goog legroups.com...
Hi all,
Consider this code

SqlConnection oConn = new
SqlConnection(A ccountsConnecti onString);
SqlCommand cmdInsert = new SqlCommand("Upd ateQuery");
//Location 1:
//SqlTransaction sqlTran = oConn.BeginTran saction();
try
{
oConn.Open();
//Location 2:
//SqlTransaction sqlTran = oConn.BeginTran saction();
cmdInsert.Execu teNonQuery();
sqlTran.Commit( );
}
catch (Exception ex)
{
//Location 3:
sqlTran.Rollbac k();
}
finally
{
oConn.Close();
}

I have to start a transaction and commit or rollback depending upon the
condition of success of command execution. The problem is if I write
code to Begin Transaction at location 1 it won't work as connection is
still closed. If I write the same at location 2, I won't be able to
rollback transaction at location 3 as sqlTran object is out of
referance. What should I do? I am using framework 2.0.

Thanks and Regards
Chakravarti Mukesh

Oct 10 '06 #3
Hi,
In fact I tried declaring it on location 1 before posting. But as you
wrote, I was not setting it to anything. Thus I am getting the error
"Object reference not found...". But when I set it to null as Chris
suggested, it is working fine.

Thanks and Regards
Chakravarti Mukesh

Marina Levit [MVP] wrote:
Declare the transaction object outside the try/catch. Just don't set it to
anything. Then, after you open the connection, inside the try block, set
the variable to the new transaction.

There is no law that says you have to declare the variable and set it to
something in the same line. You can declare everything at the top of your
method, and then use it later. In fact, that is my personal preference,
just to see all the variables involved in my method, so I don't have to
track them down throughout the method.

"Mukesh" <cm*******@gmai l.comwrote in message
news:11******** *************@k 70g2000cwa.goog legroups.com...
Hi all,
Consider this code

SqlConnection oConn = new
SqlConnection(A ccountsConnecti onString);
SqlCommand cmdInsert = new SqlCommand("Upd ateQuery");
//Location 1:
//SqlTransaction sqlTran = oConn.BeginTran saction();
try
{
oConn.Open();
//Location 2:
//SqlTransaction sqlTran = oConn.BeginTran saction();
cmdInsert.Execu teNonQuery();
sqlTran.Commit( );
}
catch (Exception ex)
{
//Location 3:
sqlTran.Rollbac k();
}
finally
{
oConn.Close();
}

I have to start a transaction and commit or rollback depending upon the
condition of success of command execution. The problem is if I write
code to Begin Transaction at location 1 it won't work as connection is
still closed. If I write the same at location 2, I won't be able to
rollback transaction at location 3 as sqlTran object is out of
referance. What should I do? I am using framework 2.0.

Thanks and Regards
Chakravarti Mukesh
Oct 10 '06 #4
Whether or not you set it to null is irrelevant. When you declare a
variable, it is already null. Setting it to null explitily doesn't change
the value of the variable.

In your exception, you are assuming you have a transaction. If the
connection could not be opened, no transaction would ever have been started.

"Mukesh" <cm*******@gmai l.comwrote in message
news:11******** **************@ b28g2000cwb.goo glegroups.com.. .
Hi,
In fact I tried declaring it on location 1 before posting. But as you
wrote, I was not setting it to anything. Thus I am getting the error
"Object reference not found...". But when I set it to null as Chris
suggested, it is working fine.

Thanks and Regards
Chakravarti Mukesh

Marina Levit [MVP] wrote:
>Declare the transaction object outside the try/catch. Just don't set it
to
anything. Then, after you open the connection, inside the try block, set
the variable to the new transaction.

There is no law that says you have to declare the variable and set it to
something in the same line. You can declare everything at the top of your
method, and then use it later. In fact, that is my personal preference,
just to see all the variables involved in my method, so I don't have to
track them down throughout the method.

"Mukesh" <cm*******@gmai l.comwrote in message
news:11******* **************@ k70g2000cwa.goo glegroups.com.. .
Hi all,
Consider this code

SqlConnection oConn = new
SqlConnection(A ccountsConnecti onString);
SqlCommand cmdInsert = new SqlCommand("Upd ateQuery");
//Location 1:
//SqlTransaction sqlTran = oConn.BeginTran saction();
try
{
oConn.Open();
//Location 2:
//SqlTransaction sqlTran = oConn.BeginTran saction();
cmdInsert.Execu teNonQuery();
sqlTran.Commit( );
}
catch (Exception ex)
{
//Location 3:
sqlTran.Rollbac k();
}
finally
{
oConn.Close();
}

I have to start a transaction and commit or rollback depending upon the
condition of success of command execution. The problem is if I write
code to Begin Transaction at location 1 it won't work as connection is
still closed. If I write the same at location 2, I won't be able to
rollback transaction at location 3 as sqlTran object is out of
referance. What should I do? I am using framework 2.0.

Thanks and Regards
Chakravarti Mukesh

Oct 10 '06 #5
"Marina Levit [MVP]" <so*****@nospam .comwrote in message
news:%2******** ********@TK2MSF TNGP02.phx.gbl. ..
Whether or not you set it to null is irrelevant. When you declare a
variable, it is already null.
Actually, I don't believe that's true, is it?

///ark
Oct 10 '06 #6
Yes, it is. A variable that is an object, is initially not pointing to
anything- a.k.a null.

Declare a variable and try to use it without instantiating it - you will
get a NullReferenceEx ception.
Declare the same variable and point it to null and try to use it - you will
get a NullReferenceEx ception.

This applies to objects, not structures.

"Mark Wilden" <mw*****@commun itymtm.comwrote in message
news:eE******** ******@TK2MSFTN GP02.phx.gbl...
"Marina Levit [MVP]" <so*****@nospam .comwrote in message
news:%2******** ********@TK2MSF TNGP02.phx.gbl. ..
>Whether or not you set it to null is irrelevant. When you declare a
variable, it is already null.

Actually, I don't believe that's true, is it?

///ark


Oct 10 '06 #7
This is only valid for member variables, local need to be explicitely
assigned/initialized, though failing to do so results in a compiler error .

Willy.

"Marina Levit [MVP]" <so*****@nospam .comwrote in message
news:%2******** ********@TK2MSF TNGP04.phx.gbl. ..
| Yes, it is. A variable that is an object, is initially not pointing to
| anything- a.k.a null.
|
| Declare a variable and try to use it without instantiating it - you will
| get a NullReferenceEx ception.
| Declare the same variable and point it to null and try to use it - you
will
| get a NullReferenceEx ception.
|
| This applies to objects, not structures.
|
| "Mark Wilden" <mw*****@commun itymtm.comwrote in message
| news:eE******** ******@TK2MSFTN GP02.phx.gbl...
| "Marina Levit [MVP]" <so*****@nospam .comwrote in message
| news:%2******** ********@TK2MSF TNGP02.phx.gbl. ..
| >
| >Whether or not you set it to null is irrelevant. When you declare a
| >variable, it is already null.
| >
| Actually, I don't believe that's true, is it?
| >
| ///ark
| >
| >
|
|
Oct 10 '06 #8
Error or warning? I know in VB, it is a warning. And in 2003 I don't
remember C# requiring you to assign values to variables.

Either way, it is a compiler issue. That is a compiler validation - but
effectively assigning a variable to null is the same as not assigning it a
value to begin with.

"Willy Denoyette [MVP]" <wi************ *@telenet.bewro te in message
news:uz******** ******@TK2MSFTN GP05.phx.gbl...
This is only valid for member variables, local need to be explicitely
assigned/initialized, though failing to do so results in a compiler error
.

Willy.

"Marina Levit [MVP]" <so*****@nospam .comwrote in message
news:%2******** ********@TK2MSF TNGP04.phx.gbl. ..
| Yes, it is. A variable that is an object, is initially not pointing to
| anything- a.k.a null.
|
| Declare a variable and try to use it without instantiating it - you
will
| get a NullReferenceEx ception.
| Declare the same variable and point it to null and try to use it - you
will
| get a NullReferenceEx ception.
|
| This applies to objects, not structures.
|
| "Mark Wilden" <mw*****@commun itymtm.comwrote in message
| news:eE******** ******@TK2MSFTN GP02.phx.gbl...
| "Marina Levit [MVP]" <so*****@nospam .comwrote in message
| news:%2******** ********@TK2MSF TNGP02.phx.gbl. ..
| >
| >Whether or not you set it to null is irrelevant. When you declare a
| >variable, it is already null.
| >
| Actually, I don't believe that's true, is it?
| >
| ///ark
| >
| >
|
|


Oct 10 '06 #9
"Marina Levit [MVP]" <so*****@nospam .comwrote in message
news:Oz******** ******@TK2MSFTN GP03.phx.gbl...
Error or warning? I know in VB, it is a warning. And in 2003 I don't
remember C# requiring you to assign values to variables.
C# require variables to be "definitely assigned" before use. So an
uninitialized variable could be null or it could be anything else - there's
no way to tell. :)

///ark
Oct 10 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
2944
by: Andrew Morgan | last post by:
Hi I have a matrix class: template<class Type> class TMatrix { //... TMatrix& T(); //... }
9
4793
by: justanotherguy63 | last post by:
Hi, I am designing an application where to preserve the hierachy and for code substitability, I need to pass an array of derived class object in place of an array of base class object. Since I am using vector class(STL), the compiler does not allow me to do this. I do realize there is a pitfall in this approach(size of arrays not matching etc), but I wonder how to get around this problem. I have a class hierachy with abstract base...
1
1755
by: Sabine Oebbecke | last post by:
Hi there, Need some help again ... I have a continuous form which shows the attendees of a competition as per their placing in the competition. So, the first record is the winner, the second record is the 2nd place, etc. The continuous form's recordsource is an updatable query. The query/form has got a field 'place' into which the reached place is
2
1804
by: Jason Shohet | last post by:
Page_a.aspx.cs does a loop thru 7 days of the week. W/in the loop, it makes a call to myService - a webservice - passing in a serialized objDay (which represents the day's info). The webservice function deserializes objDay and writes to the db. Works great. Problem is if 1 of the 7 days fails to write, there's no rollback functionality. I want it so that if a day doesn't write, none of the days should write. BeginTransaction is a...
4
3486
by: Michael | last post by:
Hi When I New a web site, the default coding model is code-separation. I can uncheck the "place code in separate file" checkbox when I add a new WebForm, and VS2005 will remember this setting. I'm wondering where does VS2005 store the settings for "place code in separate file"?
5
1974
by: Ian Bicking | last post by:
I got a puzzler for y'all. I want to allow the editing of functions in-place. I won't go into the reason (it's for HTConsole -- http://blog.ianbicking.org/introducing-htconsole.html), except that I really want to edit it all in-process and in-memory. So I want the identity of the function to remain the same, even as I edit the body and hopefully the signature too. Well, the reason is that I want to edit any function object, without...
10
2149
by: mark4asp | last post by:
I ask this because only today I read advice telling me to put it within the <headelement. This is the same advice I've always been given but no one ever explained why. Last week I was told to put it at the bottom of the html just before </ body>; the reason being that html won't start rendering until all the script files have downloaded and if they're all in the head ... Right now I'm putting all my javascript at the end of the html...
1
1965
by: Leon Mayne | last post by:
Hello, I had a chunk of code that would execute a stored proc to migrate data between two systems (takes a few minutes) and then performs some data manipulation on the migrated data. This was working fine when I was using SqlCommand.CommandTimeout = 0. After getting the basics to work I wanted to wrap the whole block in a transaction to roll back everything if something went wrong: Dim cnMigrate As New SqlConnection(pConnectionString)
2
3306
by: Reggie | last post by:
Hi and TIA! I have a class file located in my root directory with all me web pages. I call/use the class and it works fine. I have no imports statements aspx or codebehind. My question is why? I thought the class file had to be compiled and placed in the bin directory or added to the App_Code(as a class file) folder. I don't have it in either it's simply in the root. Now When I compile it and place the dll in the bin and remove the...
0
8343
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
8545
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8633
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7365
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6185
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5653
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4179
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2762
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1747
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.