SolvedPrivate

Is this a good way of generating confirmation code?

Posted on 2014-11-17
29
36 Views
Last Modified: 2016-02-17
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 chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var random = new Random();
var result = new string(
    Enumerable.Repeat(chars, 8)
              .Select(s => s[random.Next(s.Length)])
              .ToArray());

Open in new window

0
Comment
Question by:Camillia
  • 14
  • 10
  • 5
29 Comments
 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 40448883
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.)
0
 
LVL 7

Author Comment

by:Camillia
ID: 40448893
So, using database identity field might be better?
0
 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 40448910
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.)
0
 
LVL 7

Author Comment

by:Camillia
ID: 40448915
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();

            
            try
            {
                
                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



                };

                
                _dataContext.Consumers.InsertOnSubmit(c);
                _dataContext.SubmitChanges();
                return string.Concat("CONF-", confirmationCode);
                
            }
            catch (Exception ex)
            {
                //TODO log error
                return string.Empty;
            }
           
        }

Open in new window

0
 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 40448967
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.
0
 
LVL 7

Author Comment

by:Camillia
ID: 40448974
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)?
0
 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 40448977
Is this Entity Framework, or LINQ-to-SQL? If EF, what version?
0
 
LVL 7

Author Comment

by:Camillia
ID: 40448982
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.
0
 
LVL 18

Assisted Solution

by:Richard Lee
Richard Lee earned 250 total points
ID: 40449279
If I understand correctly:

1.

A transaction has taken place

2.

You need a unique confirmation code

1.

The confirmation code  maximum length is 8 characters

1.

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.

Guid.NewGuid().GetHashCode()

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:

1.

You already have a unique value

2.

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

1.

Pure productivity without compromising on code quality. You are more productive without having to do anything else and its a good design.
0
 
LVL 7

Author Comment

by:Camillia
ID: 40449592
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.
0
 
LVL 18

Expert Comment

by:Richard Lee
ID: 40449610
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)
OUTPUT INSERTED.ID
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:

http://stackoverflow.com/questions/10999396/how-do-i-use-an-insert-statements-output-clause-to-get-the-identity-value
http://msdn.microsoft.com/en-us/library/ms177564.aspx
0
 
LVL 7

Author Comment

by:Camillia
ID: 40449635
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.
0
 
LVL 18

Expert Comment

by:Richard Lee
ID: 40449656
Okay no problem. Well at least you have these options in the future.
0
 
LVL 7

Author Comment

by:Camillia
ID: 40449669
I'll see if I can get it working with LINQ and get the identity field without doing an insert, then an update.
0
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 
LVL 7

Author Comment

by:Camillia
ID: 40449675
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.
0
 
LVL 18

Expert Comment

by:Richard Lee
ID: 40449682
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
0
 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 40449711
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.

Screenshot
0
 
LVL 7

Author Comment

by:Camillia
ID: 40449753
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.

Table:
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)
0
 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 40449758
Just use that Id field as confirmation field and not create a new field.
Exactly. Why duplicate the data for no real benefit?
0
 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 40449775
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.
0
 
LVL 7

Author Comment

by:Camillia
ID: 40449804
It's only one application. You're right...no need to duplicate the data.

 I added CONF just because I read it somewhere :)

Thanks again for the help.
0
 
LVL 18

Expert Comment

by:Richard Lee
ID: 40449820
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.
0
 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 40449894
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.
0
 
LVL 7

Author Comment

by:Camillia
ID: 40449904
Yes, I understand this much better now.
0
 
LVL 7

Author Comment

by:Camillia
ID: 40450664
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.
0
 
LVL 74

Accepted Solution

by:
käµfm³d   👽 earned 250 total points
ID: 40450679
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.
0
 
LVL 7

Author Comment

by:Camillia
ID: 40450695
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?
0
 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 40450846
Yes. Just be careful as to where you put that logic (to do the concatenation).
0
 
LVL 7

Author Comment

by:Camillia
ID: 40450876
ok, thanks
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now