I've received a rush project (asp.net c# framework v2), of course due on Monday morning. It's a very simple project -- add a "Request Quote" page to an existing site. Basically, collect some info and then email someone at the company the contents of the form, and show the user a "Thank You" page. Simple as pie...until I just read the last requirement.
Every form submission is supposed to have a "Confirmation Number", starting with 10000, and each one successively increments the number by one.
Sounds so easy right? Well, I don't have a database in this site. No idea why, I really don't know anything else about the site other than the info I need to fill the requirements.
So, with this in mind, and realizing that this is less than optimal, I guess my only solution is to make a text file (yuck) and read it in, get the last number used, add one, and 开发者_C百科write that back to the text file. Which of course leaves a lot to be desired in respect to "locking" of the file so I don't get duplicate numbers.
Anyone have any suggestions for me? I'm open to anything at this point...
First, I'm assuming each process has some sort of unique identifier available. This could be a process ID, or something that is guaranteed to be unique without race conditions. Write this value to a file with the same name, so that you don't have a race creating that file. Then, move it to a file called "lock" if it doesn't exist. Check that this happened successfully by looking at the contents. Now read the value from the Confirmation number file. Check that the "lock" file has your unique identifier in it -- this ensures there wasn't a race from two people trying to move their file to lock. If it is yours, write back the incremented number and your unique ID to the Confirmation number file. Check again you hold the lock, and that the Confirmation number file has your ID. Then remove the lock file. Should this fail, just sit around waiting for the lock file to disappear, then try again.
This should allow you write to a file in a race-free manner, and ensures that the sequence number always increases by one.
You could keep track of the confirmation number in the Windows Registry, but given the option it's probably easier to use a simple text file as you suggest. Make sure you clean up (i.e. Dispose) the file handles each time to release any file locks.
I would think of XML as a good solution.
This post might make xml even easier for you.
精彩评论