How implement Rollback feature?
Question
I want to create a C# application in which copy some files in two diffrent folders(already contains older version files) and also run sql scripts. During whole process if any exception generate i need to rollback all the changes.
For sql scripts, transation can be used but how implement files copying process with rollback?
Solution
You can make a copy from the old file before replacing it, and then if an exception happened restore from this copy.
OTHER TIPS
You can take advantage of Transactional NTFS if possible. If not, then you can keep a list of the operations you did and do the reverse of it when a rollback is needed.
Or you can evolve as a software developer and use the Command Pattern and implement a BatchCommand. Commands make it very easy to add undo functionality and encapsulate it in an intelligent way. A BatchCommand can then call undo() on each Command within its list.
For a good primer to patterns, check out Head First Design Patterns
Would it fit your use case to copy the files to a temporary directory and then move the whole directory into place? If so, rollback is as simple as deleting the temporary directory.
I would copy the new files appending a suffix and a random number, thus avoiding to clash with preexisting file names.
Sample... Old file="myfile.txt", New file="myfile.txt.new.285387".
Then, when the copy process is finished ok, I would... -Rename the old file as "myfile.txt.old.3464353". -Rename the new file as "myfile.txt" -Finally the old will be erased.
Try THis code
public bool updateusertable(string UserName,string Password,string Datetime)
{
bool bResult = false;
SqlTransaction tx;
try
{
tx=conn.Begintransaction();
SqlCommand Ocmd = new SqlCommand();
Sqlconnect = Cconnect.OpenSqlConnection();
Ocmd.Connection = Sqlconnect;
Ocmd.CommandType = CommandType.StoredProcedure;
Ocmd.CommandText = "SP_User_login_Update";
Ocmd.Parameters.Add("@UserName", SqlDbType.VarChar, 100).Value = UserName;
Ocmd.Parameters.Add("@Password", SqlDbType.VarChar, 100).Value = Password;
Ocmd.Parameters.Add("@lastlogin", SqlDbType.VarChar, 100).Value = Datetime;
int i = Ocmd.ExecuteNonQuery();
if (i <= 1)
{
bResult = true;
tx.Commit();
}else
{
tx.Rollback();
}
}
catch (Exception ex)
{
string msg = ex.Message.ToString();
tx.Rollback();
}
finally
{
}
return bResult;
}