Search code examples
c#asp.netwcfrandommscorlib

Logic Ideas - Building a URL Shortener Service with C# and WCF


I need some ideas how to implement a URL Shortener Service with WCF along with sql server as database.

I will handle my url shortening logic with WCF. this project will handle creating short aliases for the urls and write them on the database with the actual url so that the project which will redirect the ulrs could use them.

where I need the logic ideas is on how to create short random letters. I will only allow numerical digits and letters in american alphabetic. Also;

  1. it should make the first char a numerical digit and the second char a letter. rest could be anything. how can I implement that feature so that framework could create random aliases for me.
  2. firstly, it will create 4 chars long words. but what if there are no 4 chars long unused words left? how can I implement that feature? if there are no unique 4 chars long words left, it should create 5 chars long words but it should make the first char a numerical digit again and the second char a letter. rest could be anything on this, too.

I know that I will be using System.Random class inside the mscorlib.dll but honestly, do not know much about it. More detailedly, I do not have any idea how to create a random unique word with numerical digit and letters in american alphabetic.


Solution

  • You do not need a Random function. Randomness only gives you a chance for collisions.

    Simply use an incrementing, numerical, key and encode it. Your database already provides a way to create them.

    A simple encoding would be Hex (base 16) but you can get shorter and fancier with a base 32 (or higher) encoding. I'm not sure if the requirement for 'first char should be numerical' is useful but it's easy to accomplish.

    And while a reversible encoding seems logical, it's also quite feasible to store the generated encoding as a column (Key) in the database and use that for lookup. That allows more fancy encoding, even adding a (random) digit in front.