Thursday, July 17, 2014

Create Random String in InfoPath Form

     A question came up in class this week during our SharePoint InfoPath and Workflow Deep Dive.
     How do we create a random string in InfoPath?  The background is that one of the students wants to use an InfoPath form for access requests.  The form would submit to a SharePoint Library which would then e-mail the approver.  A confirmation code would be created by the form and forwarded to the user once the request was approved.
     Well, unfortunately there is not a function that will allow us to magically create a random number so we're going to have to put some effort into creating a pseudo random string.

     The first function I reached for was the trusty now() function which gives you the exact date and time down to the second.  This is a great baseline for getting a number that will never be the same twice.  The only problem is that it isn't actually a number.  The answer was provided by the famous Laura Rogers on a Microsoft discussion board.  The discussion can be found here. If you find it helpful, go give her an upvote of support.

     The answer she provided was to use the following: translate(now(),"_-:T","")

     This function of translate will replace the first set of characters ("_-:T") with the second set of characters ("").  In this case we simply want to remove them so our second set of characters is empty.  This gives you a nice big long unique number to start with.
     But wait! What if two people fill out the form at exactly the same time?!  Despite the near impossibility of this happening, I don't like taking chances.  So to make the string even more unique, we chose to take the username and use the translate function to convert it into numbers by substituting every letter of the alphabet with a number; translate(username(),"abcdefghijklmnopqrstuvwxyz", "12345678901234567890123456"
     Now we multiply our now() number by our username number for a unique string of numbers.
  While it won't stand up to a mathematician, this "random" string will definitely suffice for most applications.  

No comments: