I recently had to make a method that creates a random generated password in C#. So, I looked at the web for such a function and I found this one. It was really simple and short and just what I was looking for. But, there is always a but, it didn't work. So I modified it a bit, and it now looks like this and it works.
private static string CreateRandomPassword(int passwordLength)
{
string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789!@$?_-";
char[] chars = new char[passwordLength];
Random rd = new Random();
for (int i = 0; i < passwordLength; i++)
{
chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];
}
return new string(chars);
}
It's that simple.
If you use FxCop, then you are probably also aware of this rule. Exceptions should only be catched if they can be handled. A lot of exception handling code I’ve seen, are handling exceptions that could easily be avoided by simple If-statements. That’s why I don’t do a lot of try/catch blocks, other than when I’m working with external resources like files and MSMQ. In these situations, you cannot be sure of the outcome because you are not in control over the windows file system.
Here is what NOT to do:
try
{
//Do something with an XML file
}
catch (Exception)
{
Console.WriteLine("An error occured");
}
or
try
{
//Do something with an XML file
}
catch
{
Console.WriteLine("An error occured");
}
And here is an example of doing it correctly:
try
{
// Do something with an XML file
}
catch (XmlException)
{
Console.WriteLine("The XML has been corrupted");
}
catch (UnauthorizedAccessException)
{
Console.WriteLine("You do not have permission to save the document. Make sure the file isn't write protected.");
}
I personally only do exception handling at the UI and never at the data logic or business logic. It’s my rule of thumb on exception handling, but I do break it on rare occasions. I have found it to be the best way to avoid exceptions, because you make your code more robust this way.