views:

38

answers:

2

I need a way to serialize objects in a transactional context.

Given the following pseudo-code:

transation.Begin()
try{
    serializeObj(obj1);
    serializeObj(obj2);
    serializeObj(obj3);
}
catch(Exception){
    transaction.RollBack();
}
transaction.Commit();

I want that, after this code runs, or all the objects had been serialized or none of then had been serialized.

I dont think TransactionScpe gives me this ability. I would prefer some built-in .NET mechanism instead some external library.

Thanks.

A: 

Assuming serializeObj(Object obj) specifically serializes to a file:

List<string> FileNames = new List<string>();
try
{        
    serializeObj(obj1);
    //Add a method to determine the filename to which you wrote
    FileNames.Add(GetSerializedFileName(obj1)) 
    //repeat for all your objects
}
catch(Exception)
{
    Foreach(string fn in FileNames)
    {
        if(File.Exists(fn) File.Delete(fn);
    }
}

Assuming serializeObj(Object obj) simply writes to a memory stream for IO later it's even easier:

List<Stream> Files = new List<Stream>();
try
{        
    Files.Add(serializeObj(obj1));
    //repeat for all your objects
}
catch(Exception)
{
    Foreach(Stream fn in Files)
    {
        fn.Dipose();
    }
}   
AllenG
Thanks. But this is not a transaction. What if for some reason hardware stops to respond and force application to restart? If the fail happens during the obj3 serialization (in my pseudo-code) the obj1 and obj2 will stay in file system.
Zé Carlos
I've never used TransactionScope personally, but could you not just wrap it in a `using(TransactionScope myScope = new TransactionScope){}` block?
AllenG
I think not. Anyway, that's part of my question! :)
Zé Carlos
+2  A: 

If you have a transactional filesystem (transaction ntfs), I think you can achieve what you want via the methods discussed in this and that blog. Also alphafs might be worth a look (they wrote a managed wrapper for the transaction ntfs) but I don't know the status of the project.

tobsen