Is this a good way of generating confirmation code?

I came across this code. We want to generate confirmation code.

I used this and contacted "CONF-" to it.

Is this good or should I look for another method? my manager said to use sql server's identity field. I thought about using GUID (in C#) and then just take the first 8 letters of it.

var random = new Random();
var result = new string(
    Enumerable.Repeat(chars, 8)
              .Select(s => s[random.Next(s.Length)])

Open in new window

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

kaufmed 👽Commented:
I think that either method will work, but in either case you'll need to ensure that the generated value hasn't already been used. (Probably less likely with the GUID route, but maybe not since you're only taking 8 characters.)
CamilliaAuthor Commented:
So, using database identity field might be better?
kaufmed 👽Commented:
You'd implicitly get uniqueness that way, so it's feasible. You'll probably want to left-pad the value when you display it to the user, though. (Just a stylistic thing, really.)
Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

CamilliaAuthor Commented:
I don't know how to do it LINQ that I'm using. I insert the row and at that point, I don't have the SQL Identity field to store in the ConfirmationCode field.

I was thinking about using code above and also GUID and concat them. Doubt my manager would go for that.

If I can get the identity field working , that would be great. This is what I have:

public string Save(ConsumerModels model)
           string confirmationCode = CreateConfirmationCode();

                Consumer c = new Consumer
                    FirstName = model.FirstName,
                    LastName = model.FirstName,
                    Address = model.Address,
                    City = model.City,
                    StateId = int.Parse(model.StateId.Substring(0,3)), //remove the dash-countryid //TODO find a better solution for state/country. If time permits, try Scott's suggestion again
                    CountryId = model.CountryId,
                    PostalCode = model.PostalCode,
                    EmailAddress = model.EmailAddress,
                    PhoneNumber = model.PhoneNumber,
                    PromotionId = model.PromotionsId,
                    ProductNumberId = model.ProductId,
                    ProductSerialNumber = model.SerialNumber,
                    RetailLocation = model.RetailLocationPurchase,
                    PurchaseDate = model.PurchaseDate,
                    ConfirmationCode = string.Concat("CONF-", confirmationCode),
                    CreateDate = DateTime.Now


                return string.Concat("CONF-", confirmationCode);
            catch (Exception ex)
                //TODO log error
                return string.Empty;

Open in new window

kaufmed 👽Commented:
I don't think you can use an identity field AND concatenate to it, but I'm not an expert in SQL Server. I would think the idenity by itself would be sufficient. You can concat the "CONF-" in the application, I think. Usually, you wouldn't explicitly insert into an identity field--it's auto-increment.
CamilliaAuthor Commented:
i dont want to concat "conf-" if I use the Identity field.

In my code above, how can I get the identity field? should I do this in a stored proc? should I first insert, get the identity field and then do an update to update the row with the confirmationcode (which is the identity field)?
kaufmed 👽Commented:
Is this Entity Framework, or LINQ-to-SQL? If EF, what version?
CamilliaAuthor Commented:
linq to sql.

No entityframe work. No one at work really knows EF even tho other projects use it.

I have a DBML and it's linq to sql.
Richard LeeSoftware EnthusiastCommented:
If I understand correctly:


A transaction has taken place


You need a unique confirmation code


The confirmation code  maximum length is 8 characters


The confirmation code minimum length is 8 characters.
Guids are handy when generating unique values. They are great when using these values to create new Indentities (Identity values in the database). You can use them to construct in memory relationships which can then be persisted to the database later without worrying about conflicts. I even use them and then get the hashcode if I want a unique number.


Open in new window

In the case where you already have a unique value for the transaction, it may be best to use that value (with padding if necessary) to create your confirmation code. The reasons for this are as follows:


You already have a unique value


Generating another value in code with those requirements would require further comparison against the database to ensure there is no conflict. Waste of time and performance


Pure productivity without compromising on code quality. You are more productive without having to do anything else and its a good design.
CamilliaAuthor Commented:
Doesn't have to be 8 chars.

Again, I don't know how to save the identity field when I'm inserting because I don't have that value when I'm inserting.

I guess I need to first insert, get the Id , then update the same row...updating the confirmationcode field with the Id.

I guess I can use that Guid code you have and save that instead of the code I have. I don't know.
Richard LeeSoftware EnthusiastCommented:
In this case you can use a Guid, but there are other options if you want an integer. If you are using SQL Server it is possible to get the ID on Insert without having to run to separate commands.

INSERT INTO MyTable(Name, Address, PhoneNo)
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')

Open in new window

The OUTPUT INSERTED.ID returns the ID using only one command.

If you are creating a new structure for new business transactions that will immediately send confirmation codes then either way can work. Guid or Numbers with the approaches highlighted.

See Articles & Posts:
CamilliaAuthor Commented:
Thanks but I'm doing this in LINQ. Please see my code above.

I'll go with what I have. I'm spening too much time on this. My manager will be on my case today.
Richard LeeSoftware EnthusiastCommented:
Okay no problem. Well at least you have these options in the future.
CamilliaAuthor Commented:
I'll see if I can get it working with LINQ and get the identity field without doing an insert, then an update.
CamilliaAuthor Commented:
I just googled. I think I'm correct that I have to to an insert first (with LINQ), get the identity back, then update the same row.
Richard LeeSoftware EnthusiastCommented:
Yes this approach works. My concern is why make two trips to the database when you don't have to? If you are using LINQ to perform the insert I guess you might have to since I don't believe LINQ to SQL or LINQ to Entities support SQL OUTPUT variables.

Still one of my main concerns is performance and scale. The less you access the DB the better. Of course this is balanced with efficiency - no retrieving the entire database :) and storing in memory.

The approach I would take is use either:

1. A stored procedure to insert and return to me the ID
2. Use a Guid
kaufmed 👽Commented:
Once you submit the changes, the ID field (or in your case confirmation code) of your entity will be populated by the Framework. You don't have to populate it yourself.

CamilliaAuthor Commented:
kaufmed -- yes, I have that.  I know what you mean now.

However, my table is like this (simplified).  I wanted to store the ID field generated by the insert into the confirmationcode field. Maybe add 2 letters to it as well (my manager suggested that). Now I know what you mean. Just use that Id field as confirmation field and not create a new field.

Id  name  confirmationcode

Richard -- yes , I don't want to make 2 trips to the database. I guess I can use C# Guid code (the one you have) and use that (maybe shorten it in the code and store it as a varchar field in the database)
kaufmed 👽Commented:
Just use that Id field as confirmation field and not create a new field.
Exactly. Why duplicate the data for no real benefit?
kaufmed 👽Commented:
I will add that if multiple applications will need to reference this confirmation number, then perhaps you would want a distinct column that has the prepended text included. If it's only the one application, and you're certain that no other application would need to read this data, then keeping the one column could be sufficient.

It's not that it's technically challenging to maintain one column even if several applications read the column, but if you are going to have the convention of "CONF-XXXXXXXX", then each application would have to add the "CONF-" to the identity value. And if two years from now management wants the string to say something like "CNFRM-XXXXXXXX", then each application has to change. You have to weight the costs of each when you decide which approach to take.
CamilliaAuthor Commented:
It's only one application. You're need to duplicate the data.

 I added CONF just because I read it somewhere :)

Thanks again for the help.
Richard LeeSoftware EnthusiastCommented:
Your welcome.

Just to comment on @Kaufmed point. When exposing other applications to this application it may be a good way to expose the functionality/database via a web service and not let any other application interact directly. This will prevent any issues with how you store the data.
kaufmed 👽Commented:
Richard makes an excellent point regarding having a web service layer that sits on top of your database. While you do incur the overhead of having the new piece sitting between your application and the database, you do gain having only a single place to make a change should management decide the system needs to display confirmation numbers differently.
CamilliaAuthor Commented:
Yes, I understand this much better now.
CamilliaAuthor Commented:
Just had a meeting with my boss. He wants the  the first 3 characters of the user's lastname + the identity field. I guess I do need the confirmation field, and then either do this in a stored proc or do an insert and an update.
kaufmed 👽Commented:
I don't think you need the extra field even for that. So long as you make one layer responsible for interpreting the identity value as a confirmation number (rather than simply a unique ID--i.e. identity), then you still meet your requirement. Nuclear war won't break out if you include the extra column, but it is technically duplicate data, and it's one more column that you have to consider when doing queries, building indexes, etc.

I believe there's a such thing as computed columns, which are psedo-columns who's value is dependent on some other column's value. I'm not familiar with how they function in terms of performance.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
CamilliaAuthor Commented:
I don't think you need the extra field even for that. So long as you make one layer responsible for interpreting the identity value as a confirmation number (rather than simply a unique ID--i.e. identity), then you still meet your requirement.

You mean when I show the confirmation to the user, i should concat identity and their first 2 letters of their last name? but not store it?
kaufmed 👽Commented:
Yes. Just be careful as to where you put that logic (to do the concatenation).
CamilliaAuthor Commented:
ok, thanks
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.