logo

Automatic generation of passwords

When creating new users, you may need to generate password automatically. This is especially useful when creating many users at the same time. You can generate and write passwords using a script. Create a script (e.g. in a process). Add the method:

public static string GetPass(Random r, int x )
{
    string pass="";
    while (pass.Length < x)
    {
        Char c = (char)r.Next(33, 125);
    //33, 125 are borders of characters used
        if (Char.IsLetterOrDigit(c))
            pass += c;
    }
    return pass;
}

The method gets random and a number and returns a string with a password. The number is responsible for the password length.

The script below allows generating and assigning a password to a system user and then saving the user data on the server.

To use the script you do not need to publish and start the process. You can start it in the emulation mode with disabled rollback. 

This script is implemented with the standard C# and ELMA methods and does not require improvements. During its execution, a unique password is generated for each user. After generating the password, the user full name, login and password are written to a .txt file on the server.

//table header
string text = "Full Name \\ Login \\ Password" + Environment.NewLine + Environment.NewLine;           //load all the users
var r = new Random();
if (context.User != null)
{
    string tempPassword = GetPass(r, 8);
    //passwords are stored encrypted in the database, therefore they need to be written to a file before being assigned to users
    text += context.User.FullName + " \\ " + context.User.UserName + " \\ " + tempPassword + Environment.NewLine + Environment.NewLine;                
    //the method PasswordReset get the user ID and the new password
    UserManager.Instance.PasswordReset(context.User.Id, tempPassword);
}
//write data to a file, the first argument is the path to the file, if the file does not exist, it will be created
System.IO.File.WriteAllText("C:\\Login.txt", text);

For the script to work, add namespaces:

using EleWise.ELMA.Security.Managers;
using System.IO

An example of a file with user data is attached.

Attachments