Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
Creating Temporary Passwords - Bring in da' Func<T>

One of the features that I really like in .NET 3.5 is Func<T>.  For those of you who aren't familiar with Func<T>, it is simply a delegate.  While I generally haven't seen many people who embrace delegates, it may be due to my limited exposure to different programming teams over the past few years.  Generally speaking I see frameworks latch on to many of these new features much sooner than the average web application.  In this post I want to show that Func usage is simple and within reach for you in your application(s).

The Story

As a user I can have a temporary password emailed to me if I forget my own, so that I can regain access to my account.

The Implementation

I've seen various implementations of this over the years and each one seems to want to generate some randomized set of digits and characters with the possibility of special characters in there.  Here's a possible implementation I've made leveraging the use of Func.  Take a look and then I'll break it down.

   1: public string CreateTemporaryPassword(int length)
   2: {
   3:     Func<Random, char> randomNumber = rnd => (char) rnd.Next(48, 58);
   4:     Func<Random, char> randomCharacter = rnd => (char) rnd.Next(97, 123);
   5:  
   6:     var funcArray = new[] {randomNumber, randomCharacter};
   7:     var chars = new char[length];
   8:     for (int i = 0; i < length; i++)
   9:     {
  10:         var index = random.Next(0, funcArray.Length);
  11:         chars[i] = funcArray[index](random);
  12:     }
  13:  
  14:     return new string(chars);
  15: }

Break It Down For Me

Nice, isn't it?  Even if you don't understand Func yet, the code above should be relatively easy on the eyes.  It's not overly long and its brevity implies a certain level of simplicity that welcomes you to come and understand what it's doing rather than scaring you off.  Let's break it down by line by line:

  • I define two Func's, one for generating random numbers and the other for generating random characters (lines 3 and 4).  (This is generating numbers that map to ASCII characters and then casting the number to a char datatype). The Func<Random, char> is the same as "public char(Random r)".  So what I'm saying is, "I'm going to pass you in a Random number generator and you return me back a character, it's up to you whether that character is a letter or number or something else".  If it helps, think of these Func objects as mini-methods.  (Note: I've chosen to pass in the random number generator, you could implement a different way if so desired (what you don't see is that this class has a member variable of type Random)).
  • I then define an array of these Func<Random, char> objects (line 6).  I'll come back to why I am using an array in a moment.
  • I create an array of characters in line 7 to hold the characters that are being generated.
  • Line 8 is a loop defined for the number of characters in the temp password.
  • Line 10 may look a little goofy.  What I'm doing here is allowing passwords to be a bit more random by saying in English, "for however many different ways you can generate a character, randomly pick one".  This has the effect that not only are passwords random, the structure of the generated string is random.  I really like this.
  • Line 11 then is where we leverage the Func.  We take the random index of the func to use from line 10, access a Func at the location in the array we set up in line 6, and execute the function passing in the random number generator.  Take a moment and make sure you understand this line as it is really the heart of the whole method.
  • Line 14 is simply taking the generate characters and returning a string.

Extensibility

Right now I have two Func's defined, one for random characters and another for random numbers.  To change the sequence I could create another Func and simply add it to the array and voila, I've got another character generation option. I only therefore have to touch two lines, the line where the new Func is defined and the line which adds the Func to the array, line 6.  I'm sure there are other ways to add extensibility points, but really how often are you going to want to change your password generation scheme?

Conclusion

If Func seems odd to you make a commitment to use it.  As you use it you'll find that it really isn't that bad and pretty soon you'll be getting down with da Func all the time.


Posted 12-02-2008 8:36 PM by Tim Barcz

[Advertisement]

Comments

Derik Whittaker wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 12-02-2008 9:46 PM

I like it.

I have learned to like both Func<> and Action<> in my current project at work.

Nice post

Jason Bock wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 12-02-2008 10:23 PM

Cute :)

But be careful...this scheme may generate some "interesting" passwords - i.e. swear words, racist terms, etc. One way to alleviate that is to not generate vowels, see if you can work that into your scheme.

Chris Missal wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 12-02-2008 10:24 PM

I too have been trying to find good uses of Func. This one looks like a winner.

I want to listen to The Time all of a sudden...

Kevin H wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 12-03-2008 12:19 AM

Or, the somewhat simpler:

public string CreateTemporaryPassword(int length)

{

 string letters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

  var chars = new char[length];

  for (int i = 0; i < length; i++)

    chars[i] = letters[random.Next(0, letters.Length)];

  return new string(chars);

}

The probability distribution isn't the same, but it should produce the same outputs.

Reflective Perspective - Chris Alcock » The Morning Brew #236 wrote Reflective Perspective - Chris Alcock &raquo; The Morning Brew #236
on 12-03-2008 5:04 AM

Pingback from  Reflective Perspective - Chris Alcock  &raquo; The Morning Brew #236

Anonymost wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 12-03-2008 8:41 AM

<quote>

Line 12 then is where we leverage the Func.  We take the random index of the func to use from line 10, access a Func at the location in the array we set up in line 6, and execute the function passing in the random number generator.  Take a moment and make sure you understand this line as it is really the heart of the whole method.</quote>

Line 12 looks like a closing brace to me... I understand  what that does, but I'm not sure which line you're referring to in your commentary.  Could you please update the line numbers?

Tim Barcz wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 12-03-2008 9:15 AM

@Anonymost

updated...sorry about that.

Tim Barcz wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 12-03-2008 9:18 AM

@Kevin H

I agree that your example is simple as well and in most cases would be acceptable.  I wanted a simple example to demonstrate Func usage.

As you pointed out your the probability for a number is far less in your examples than in mine, otherwise they both accomplish the same goal.

Dew Drop - December 3, 2008 | Alvin Ashcraft's Morning Dew wrote Dew Drop - December 3, 2008 | Alvin Ashcraft's Morning Dew
on 12-03-2008 9:35 AM

Pingback from  Dew Drop - December 3, 2008 | Alvin Ashcraft's Morning Dew

DotNetKicks.com wrote Creating Temporary Passwords - Bring in da' Func
on 12-03-2008 12:43 PM

You've been kicked (a good thing) - Trackback from DotNetKicks.com

Leyu wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 12-04-2008 1:04 AM

I guess you forgot to declare the <b>random</b> object you used on line 10 & 11.

Tim Barcz wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 12-04-2008 9:44 AM

@Leyu

I addressed this in the first bullet point:

"what you don't see is that this class has a member variable of type Random"

Func<T> based Generic List Initializers « If only I were wrote Func&lt;T&gt; based Generic List Initializers &laquo; If only I were
on 12-06-2008 2:19 PM

Pingback from  Func&lt;T&gt; based Generic List Initializers &laquo; If only I were

Justin Etheredge wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 12-08-2008 4:59 PM

I love the title. :-)

Konrad D. wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 12-08-2008 5:53 PM

I really think that your example is rather bad usage of ideas that lay underneath the Func class.

Concept of lambda expressions (which func uses) is borrowed from a world of functional programming where main idea is that function DO NOT HAVE SIDE-EFFECTS. Which means that function will always return same values when called on identical arguments.

For instance, random number generations is perfect example for monads in Haskell.

Also, I think that every person which had finished (or is attending) CS studies should be familiar with concept of lambda expressions and, so forth, this example, as mentioned before, gives pretty bad idea for usage of such language construncts.

Nevertheless, keep up the good work, perhaps other people find it interesting:)

Tim Barcz wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 12-08-2008 7:01 PM

@Konrad

My understanding of side effect might be different, but there isn't anything that says a side-effect free function must return the same value.

Understanding that....

What is the side effect here?   The only "state" (side effect) that changes is the next number on the random number generator and I wouldn't call that a state change, since it changes ANYTIME you use it.

As has been pointed out, this may not be the best use of Func, but I don't think that it necessarily abuses it.

andrew wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 12-09-2008 12:57 AM

just another, simple, way to do it using guid... thanks for the post

       public string CreateTemporaryPassword(int length)

       {

           // Get GUID

           string guid = System.Guid.NewGuid().ToString();

           // Remove the hyphens

           guidResult = guidResult.Replace("-", string.Empty);

           // Make sure length is valid

           if (length <= 0 || length > guidResult.Length)

               throw new ArgumentException("Length must be between 1 and " + guidResult.Length);

           // Return the first length bytes

           return guidResult.Substring(0, length);

       }

Tim Barcz wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 12-09-2008 1:08 AM

Not that I think this would ever necessarily occur, but by doing as you suggest you "weaken" your encryption scheme.

In my original method there are 36 different characters (0-9,a-z).  In a GUID you'll never see a letter greater than F since it's HEX based.  Therefore you have only 16 different character options (0-9,a-f).

In a five letter password the difference is:

36 chars: 60,466,176 different possibilities

16 chars: 1,048,576 different possibilities

again the chances are small that this will make a difference but for very little extra work you get a whole lot more security!

Arch4ngel wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 12-09-2008 11:18 AM

Thread.Sleep(1);

Random random = new Random((int) DateTime.Now.Ticks);

"random" is not defined in that function. I initialize it with the amount of ticks converted to Int32. However, I do add a small Thread.Sleep(1) to randomize consecutive calls.

Might not be necessary in normal usage scenario... but it's there. :)

social bookmarking seo wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 01-18-2013 2:52 PM

yHsHxy I really enjoy the blog.Really thank you! Really Great.

pills for weight loss wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 01-31-2013 9:27 AM

y44RCf I really liked your blog.Really looking forward to read more. Cool.

http://bestmedicineonline.info wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 02-14-2013 5:03 AM

nLgAOe Really enjoyed this blog.Thanks Again. Cool.

buy clomid no prescription wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 02-27-2013 1:02 PM

dqjm0s Im obliged for the blog article. Fantastic.

grizzly bears wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 04-06-2013 10:19 AM

I really liked your post.Much thanks again. Awesome.

best compact digital cameras wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 05-14-2013 3:54 PM

M82wba Say, you got a nice blog post.Really thank you! Really Great.

best social bookmarks wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 06-19-2013 2:45 PM

UDlRYq I cannot thank you enough for the blog.Thanks Again. Much obliged.

great service wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 07-04-2013 11:27 AM

rD1Shw A round of applause for your article. Really Cool.

buy viagra online wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 07-24-2013 7:18 AM

Thank you for your blog post.Really thank you! Will read on...

buy cialis online cheap wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 07-25-2013 9:31 AM

Really enjoyed this blog article. Awesome.

news wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 07-26-2013 5:15 AM

mrkDoH Awesome post.Much thanks again. Awesome.

best news wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 08-02-2013 11:49 AM

Thanks-a-mundo for the blog.Thanks Again. Want more.

amazing news wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 08-02-2013 4:50 PM

OT88q2 Great, thanks for sharing this blog.Really looking forward to read more. Want more.

awesome moldavian news wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 08-05-2013 2:27 AM

F4dO7m Very neat blog. Great.

awesome links for you wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 08-19-2013 10:42 AM

VBf068 Say, you got a nice blog. Awesome.

great link buildng wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 08-19-2013 10:11 PM

pirZpO Hey, thanks for the article post.Really thank you! Want more.

good seo guys wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 09-03-2013 8:00 PM

TBhY2R Thank you for your post.Really looking forward to read more. Keep writing.

pro link building wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 09-24-2013 7:02 AM

ZKkWea I really liked your post.Thanks Again. Great.

best linkbuilding wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 10-01-2013 9:03 AM

LMxdL7 wow, awesome blog article.Really looking forward to read more. Much obliged.

best link build wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 10-16-2013 6:48 AM

wf2aTg I truly appreciate this blog. Keep writing.

smashing top seo wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 11-01-2013 7:03 AM

KOqqSO Thanks for the blog.Much thanks again. Fantastic.

great things to know wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 11-18-2013 8:54 PM

aYhP9H Major thankies for the blog.Really looking forward to read more. Really Cool.

check this out wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 12-15-2013 7:27 AM

aULPMJ Major thanks for the post.Thanks Again. Keep writing.

check it out wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 01-08-2014 5:50 PM

YuMjdM Muchos Gracias for your article post.Really looking forward to read more. Keep writing.

look at this wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 01-16-2014 12:26 AM

Vmee7y Very informative blog article.Really looking forward to read more. Fantastic.

stunning seo guys wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 01-20-2014 3:29 PM

h96uVj Very neat article post.Much thanks again.

best prices wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 03-22-2014 10:54 AM

OzrjVl Major thankies for the article.Really looking forward to read more. Much obliged.

best money here wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 03-25-2014 7:00 AM

1Lrsre Great, thanks for sharing this article.Really looking forward to read more. Cool.

seo for cheap wrote re: Creating Temporary Passwords - Bring in da' Func<T>
on 03-25-2014 9:54 PM

cIvwz7 A big thank you for your article.Really thank you! Keep writing.

Add a Comment

(required)  
(optional)
(required)  
Remember Me?

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)