8
I am developing a small application to perform XML import, which searches the items present in the note and performs the search for them in DB
company. When the item is not found, the link is done manually and this information is saved in a table ItemFornecXItemEmpresa
and, next time, the program will find the item.
My problem is in the generation of ObjID
, which is generated based on the day and time of insertion and plus 5 random numbers:
for (int i = 0; i < itens.Count; i++)
{
if (itens[i].Novo == true)
{
Random rand = new Random();
string ano = String.Format("{0:yy}", DateTime.Now);
string mes = String.Format("{0:MM}", DateTime.Now);
string dia = String.Format("{0:dd}", DateTime.Now);
string hora = String.Format("{0:hh}", DateTime.Now);
string mili = String.Format("{0:ff}", DateTime.Now);
string random = rand.Next(10000,99999).ToString();
string id = ano + mes + dia + hora + mili + random;
[...]
}
}
And every insertion I make I have that kind of ID
generated:
150325094512431
1503250946*44723*
1503250947*44723*
150325094929997
150325095062289
1503250951*94581*
1503250952*94581*
201513031638315
201516031131187
201516031136284
201516031137201
I observe several ID
s repeated. There is some logic to this?
I think it would be better to use an Identity column in the database (assuming SQL Server), or UUID, and save the date in a separate location. The identifier is not a good place to store record creation date and time.
– bfavaretto
The idea is to generate unrepeated numbers using the date as the basis for @bfavaretto actually, and not to store the date properly. Anyway, it won’t be an app for distribution, just for testing.
– Cassio Milanelo
I get it. With the solution of the bigown, I understand that the numbers will no longer repeat themselves inside the loop, but nothing prevents them from repeating themselves between several executions of this block of code that you posted (which I assume is in a function). Even if you created a guard for this, sooner or later they would repeat themselves, since there are a not so large amount of numbers in the range that you have determined.
– bfavaretto
The random number will repeat itself sooner or later, no doubt, that’s where the date and time comes in, because when the
string
Random repeat, it will be another day (or year). If it is the same day, it will be another time. I think I’ll have no problem with it the way it is (for my application size, of course). But thanks for the remark.– Cassio Milanelo
In this case would not it be much better to use sequential instead of Random? It’s increasing one by one, which by about 100,000 increments probably the minute has already changed.
– Bacco