Sunday, 4 August 2013

Creating random authorization code in c# in ASP.NET MVC.

We are going to create random 15 characters long authorization number. This can be used for many different purposes in your MVC application like unique barcodes, authorization codes etc. To make thinks more interesting we are going to force the method to place letter before and after random code.
GenerateLetter method is responsible to give us only letter. I used this code based on small tutorial

public char GenerateLetter()
            Random randomNumber = new Random();

            int number = randomNumber.Next(0, 26);
            char letter = (char)('a' + number);
            return letter;

        public string GenerateAuthCode()
            bool codeExists = false;

            string code = GenerateLetter().ToString();

                code += Guid.NewGuid().ToString("N").Substring(0, 13);

                code += GenerateLetter().ToString();

                YourDBContext dbContext = new YourDBContext();

var Exists = dbContext.products.FirstOrDefault(m => m.barcode ==   code);

                codeExists = Exists == null? false : true;
            while (codeExists);
            return code;

We are calling GenerateLetter method twice before and after random 13 characters code is generated. We also want to make sure that code is always unique so we are calling Data base to find if any product already have this barcode, if so we method will repeat whole process.

Adam Bielecki.