Do you know how to implement transactions in Castle ActiveRecord? - activerecord

I decided to make a system for a client using Castle ActiveRecord, everything went well until I found that the transactions do not work, for instance;
TransactionScope t = new TransactionScope();
try
{
member.Save();
//This is just to see transaction working
throw new Exception("Exception");
foreach (qfh.Beneficiary b1 in l)
{
b1.Create();
}
}
catch (Exception ex)
{
t.VoteRollBack();
MessageBox.Show(ex.Message);
}
finally
{
t.Dispose();
}
But it doesn't work, I throw an Exception just to try the transaction rolls back, but for my surprise I see that the first [Save] records into the database. What is happening?
I'm new on Castle and NHibernate, firstly I saw it very attractive and I decided to go on with it and MySQL (I've never worked with this DB), I tried ActiveWriter and it seemed very promising but after a long and effortly week I see this issue and now I feel like I'm stuck and like I've wasted my time. It is supposed to be easy but right now I'm feeling a frustated cause I cannot find enough information to make this workout, can you help me?

You need to wrap the code in a session scope, like this:
using(new SessionScope())
{
a.Save();
b.Save();
c.Save();
}
Read more here.

Ben's got it. That doc is a little confusing. Refer to the last block on the page, "Nested transactions".

I finally fixed, it happened that I was doing wrong, I overrode the Save method of the Member class and made sessionScope inside and inside of it a transaction scope, so when a involved all of that in a transaction scope it saved in the database, so when I threw the exception everything was already saved, I think that's it.
All in all, thanks for the help.

Related

JDBC, Fortify and Try-With-Resource

I'm currently working through a project that is using HP's Fortify SCA tool to catch security issues in the code base. I'm having a bit of issue determining the best approach to correctly handling JDBC resources.
The code I have at the minute looks like this;
try (Connection conn = new DatabaseService().getConnection();
PreparedStatement ps = conn.prepareStatement(query);) {
ps.setString(1, mString);
try (ResultSet rs = ps.executeQuery();) {
while (rs.next()) {
...Do logic...
}
} catch (SQLException e) {
e.printStackTrace();
}
} catch (SQLException e){
e.printStackTrace();
}
}
The problem is that Fortify will flag this code stating that if an exception were to happen in the nested try statement then the reference to conn and ps will be lost and they won't be properly closed. Is fortify correct to flag this or is it a false positive? From what I understand try-with-resource should always close their resource but perhaps this doesn't always happen when they're nested like this.
I've scoured other related questions and blogs around the internet but I haven't been able to get any definitive proof on this.
The most documented solution that's always safe in this situation is to not use try-with-resource and wrap each resource with a try-catch in both the catch and finally blocks of a broader try-catch statement. However, I'd rather avoid this because it's horribly verbose.
Thanks in advance!
Edit: So I realized I've left something out of the code when I was re-writing it into SO. The original catch blocks had a System.exit(1); statement in them (bad practice I know). That would mean that if an exception was thrown in the nested try-with-resource then Fortify would be correct to say the conn and ps would not be properly closed.
Thanks for the replies, without the System.exit(1); all resources in this situation will be closed properly and I've selected the answer indicating that.
Using try-with-resource is always supported on Java 7 and higher, no matter tooling is sitting on top of it.
So, if this code compiles (meaning you are on Java7+), you can safely ignore any warnings as they are indeed false positives. The auto-closing resource contract is guaranteed for JRE classes.
Now, if you decide to write you own resource that implements AutoCloseable then it's up to you to make sure that the close() method actually closes the resource =)
The Fortify Java translator may never have been updated with this Java 7+ construct. You should contact Fortify Technical Support and submit the test case. The analysis is incorrect.
Further, you should mark this and other identical findings "Not an Issue" and move on with your life.

Meteor 0.5.9: replacement for using Session in a server method?

So, I was attempting to do something like the following:
if(Meteor.isServer){
Meteor.methods({connect_to_api: function(vars){
// get data from remote API
return data;
}});
}
if(Meteor.isClient){
Template.myTpl.content = function(){
Meteor.call('connect_to_api', vars, function(err,data){
Session.set('placeholder', data);
});
return Session.get('placeholder');
};
}
This seemed to be working fine, but, of course, now breaks in 0.5.9 as the Session object has been removed from the server. How in the world do you now create a reactive Template that uses a server-only (stuff we don't want loading on the client) method call and get data back from that Method call. You can't put any Session references in the callback function because it doesn't exist on the server, and I don't know of any other reactive data sources available for this scenario.
I'm pretty new to Meteor, so I'm really trying to pin down best-practices stuff that has the best chance of being future-proof. Apparently the above implementation was not it.
EDIT: To clarify, this is not a problem of when I'm returning from the Template function. This is a problem of Session existing on the server. The above code will generate the following error message on the server:
Exception while invoking method 'connect_to_api' ReferenceError: Session is not defined
at Meteor.methods.connect_to_api (path/to/file.js:#:#)
at _.extend.protocol_handlers.method.exception ... etc etc
Setting the session in the callback seems to work fine, see this project I created on github: https://github.com/jtblin/meteor_session_test. In this example, I return data in a server method, and set it in the session in the callback.
There are 2 issues with your code:
1) Missing closing brace placement in Meteor.methods. The code should be:
Meteor.methods({
connect_to_api: function(vars) {
// get data from remote API
return data;
}
});
2) As explained above, you return the value in the session, before the callback is completed, i.e. before the callback method had the time to set the session variable. I guess this is why you don't see any data in the session variable yet.
I feel like an idiot (not the first time, not the last). Thanks to jtblin for showing me that Session.set does indeed work in the callback, I went back and scoured my Meteor.method function. Turns out there was one spot buried in the code where I was using Session.get which was what was throwing the error. Once I passed that value in from the client rather than trying to get it in the method itself, all was right with the world.
Oh, and you can indeed order things as above without issue.

Joomla 3.0 generic database error handling

Going from Joomla 2.5 to 3.0 with my extension, I'm struggling with how to do the DB error handling (since GetErrorNum is deprecated, see also Joomla! JDatabase::getErrorNum() is deprecated, use exception handling instead).
The way that seems to be the one to go according to the question linked above, is to add the following code for each db->query() code:
if (!$db->query()) {
throw new Exception($db->getErrorMsg());
}
In my opinion, that makes DB error handling more awkward than it was before. So far, I simply called a checkDBError() function after a DB call, which queried the ErrorNum and handled any possible error accordingly.
That was independent from how the DB query was actually triggered - there are different ways to do that, and different results on an error: $db->loadResult() returns null on error, $db->query() returns false. So there will now be different checks for different DB access types.
Isn't there any generic way to handle this, e.g. a way to tell Joomla to throw some exception on DB problems? Or do I have to write my own wrapper around the DatabaseDriver to achieve that? Or am I maybe missing something obvious?
Or should I just ignore the deprecation warning for now and continue with using getErrorNum()? I'd like to make my extension future-proof, but I also don't want to clutter it too much with awkward error handling logic.
Just found this discussion: https://groups.google.com/forum/#!msg/joomla-dev-general/O-Hp0L6UGcM/XuWLqu2vhzcJ
As I interpret it, there is that deprecation warning, but there is no proper replacement yet anyway...
Unless somebody points out any other proper documentation of how to do it in 3.0, I will keep to the getErrorNum method of doing stuff...
Get getErrorNum() function will solve your problem....
$result = $db->loadResult();
// Check for a database error.
if ($db->getErrorNum())
{
JFactory::getApplication()->enqueueMessage($db->getErrorMsg());
return false;
}

Update transaction in SQL Server 2008 R2 from ASP.Net not working

Even though I've been a stalker here for ages, this is the first post I'm making. Hopefully, it won't end here and more optimistically future posts might actually be me trying to give a hand to someone else, I do owe this community that much and more.
Now, what I'm trying to do is simple and most probably the reason behind it not working is my own stupidity. However, I'm stumped here.
I'm working on an ASP.Net website that interacts with an SQL Server 2008 R2 database. So far everything has been going okay but updating a row (or more) just won't work. I even tried copying and pasting code from this site and others but it's always the same thing.
In short: No exception or errors are shown when the update command executes (it even gives the correct count of affected rows) but no changes are actually made on the database.
Here's a simplified version of my code (the original had more commands and tons of parameters each, but even when it's like this it doesn't work):
protected void btSubmit_Click(object sender, EventArgs e)
{
using (SqlConnection connection =
new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString))
{
string commandString = "UPDATE [impoundLotAlpha].[dbo].[Vehicle]" +
"SET [VehicleMake] = #VehicleMake" +
" WHERE [ComplaintID] = #ComplaintID";
using (SqlCommand command = new SqlCommand(commandString, connection))
{
SqlTransaction transaction = null;
try
{
command.Connection.Open();
transaction = connection.BeginTransaction(IsolationLevel.Serializable);
command.Transaction = transaction;
SqlParameter complaintID = new SqlParameter("#complaintID", SqlDbType.Int);
complaintID.Value = HttpContext.Current.Request.QueryString["complaintID"];
command.Parameters.Add(complaintID);
SqlParameter VehicleMake = new SqlParameter("#VehicleMake", SqlDbType.VarChar, 20);
VehicleMake.Value = tbVehicleMake.Text;
command.Parameters.Add(VehicleMake);
command.ExecuteNonQuery();
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
finally
{
connection.Close();
}
}
}
}
I've tried this with the "SqlTransaction" stuff and without it and nothing changes.
Also, since I'm doing multiple updates at once, I want to have them act as a single transaction. I've found that it can be either done like this or by use of the classes included in the System.Transactions namespace (CommittableTransaction, TransactionScope...).
I tried all I could find but didn't get any different results.
The connection string in web.config is as follows:
<connectionStrings>
<add name="ApplicationServices"
connectionString="Data Source=localhost;Initial Catalog=ImpoundLotAlpha;Integrated Security=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>
So, tldr; version:
What is the mistake that I did with that record update attempt? (Figured it out, check below if you're having a similar issue.)
What is the best method to gather multiple update commands as a single transaction?
Thanks in advance for any kind of help and/or suggestions!
Edit:
It seems that I was lacking some sleep yesterday cause this time it only took me 5 minutes to figure out my mistake.
Apparently the update was working properly but I failed to notice that the textbox values were being overwritten in Page_Load. For some reason I had this part commented:
if (IsPostBack)
return;
The second part of the question still stands. But should I post this as an answer to my own question or keep it like this?
Have you tried running the query against the database directly (i.e. SQL Management Studio itself)? I'm not sure how you'd implement the "START TRANSACTION... COMMIT TRANSACTION" commands from ASP... for what it's worth we do all our database operations from within stored procedures.

Adding custom code to mootools addEvent

Even though I've been using mootools for a while now, I haven't really gotten into playing with the natives yet. Currently I'm trying to extend events by adding a custom addEvent method beside the original. I did that using the following code(copied from mootools core)
Native.implement([Element, Window, Document], {
addMyEvent:function(){/* code here */}
}
Now the problem is that I can't seem to figure out, how to properly overwrite the existing fireEvent method in a way that I can still call the orignal method after executing my own logic.
I could probably get the desired results with some ugly hacks but I'd prefer learning the elegant way :)
Update: Tried a couple of ugly hacks. None of them worked. Either I don't understand closures or I'm tweaking the wrong place. I tried saving Element.fireEvent to a temporary variable(with and without using closures), which I would then call from the overwritten fireEvent function(overwritten using Native.implement - the same as above). The result is an endless loop with fireEvent calling itself over and over again.
Update 2:
I followed the execution using firebug and it lead me to Native.genericize, which seems to act as a kind of proxy for the methods of native classes. So instead of referencing the actual fireEvent method, I referenced the proxy and that caused the infinite loop. Google didn't find any useful documentation about this and I'm a little wary about poking around under the hood when I don't completely understand how it works, so any help is much appreciated.
Update 3 - Original problem solved:
As I replied to Dimitar's comment below, I managed to solve the original problem by myself. I was trying to make a method for adding events that destroy themselves after a certain amount of executions. Although the original problem is solved, my question about extending natives remain.
Here's the finished code:
Native.implement([Element, Window, Document], {
addVolatileEvent:function(type,fn,counter,internal){
if(!counter)
counter=1;
var volatileFn=function(){
fn.run(arguments);
counter-=1;
if(counter<1)
{
this.removeEvent(type,volatileFn);
}
}
this.addEvent(type,volatileFn,internal);
}
});
is the name right? That's the best I could come up with my limited vocabulary.
document.id("clicker").addEvents({
"boobies": function() {
console.info("nipple police");
this.store("boobies", (this.retrieve("boobies")) ? this.retrieve("boobies") + 1 : 1);
if (this.retrieve("boobies") == 5)
this.removeEvents("boobies");
},
"click": function() {
// original function can callback boobies "even"
this.fireEvent("boobies");
// do usual stuff.
}
});
adding a simple event handler that counts the number of iterations it has gone through and then self-destroys.
think of events as simple callbacks under a particular key, some of which are bound to particular events that get fired up.
using element storage is always advisable if possible - it allows you to share data on the same element between different scopes w/o complex punctures or global variables.
Natives should not be modded like so, just do:
Element.implement({
newMethod: function() {
// this being the element
return this;
}
});
document.id("clicker").newMethod();
unless, of course, you need to define something that applies to window or document as well.

Resources