C #- make a simple password management tool with Winform

Why?

The first is to practice c#.
Presumably, everyone has had the experience of not remembering the account and password of a platform. That feeling is really crazy. I can't remember so many accounts and passwords! I used python to write a super simple console program (even the account information is written in the code) to prompt me for the password, but when I wanted to add an account, I was directly bothered to vomit. That's why I want to use Winform to make a simple gadget to help me remember. (only for my own use (so the interface will be ugly.), But I'll post the code, so I can actually make one for myself if it's a little c# basic)

imagine

My needs are very simple

  1. When I need it, I can enter a platform to display the corresponding account and password
  2. Can add account information

Another point is that before querying the account, you need to enter a password to verify your identity. This password is only known to me (I saved it in the app.config file, and the function of changing the password can be extended if necessary). Therefore, even if someone runs this program on my computer, it is useless for him not to know the password.

How to save account information?

I once wanted to save with SQL Server. After all, c# I was so close to it, but what I wanted to save was essentially just some strings. I felt a little overqualified, so I didn't choose SQL Server. Recently, I learned about JS and some knowledge of json. I found that json file is a good choice, so I decided to use it. But I can't c# process json data yet. So I went online to find a way, and then I found out newtonsoft.json(json.NET) , it's a model NET. With it, I can solve my problem.

code

First, set up the entry interface, a super simple form, with only three controls.

In order to facilitate operation, add an exit shortcut key ESC to it. Very simple. Just write the following code in the KeyDown event:

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if(e.KeyCode==Keys.Escape)
    {
        this.Close();
    }
}

Then determine the function of this button: after entering the correct password, click OK to enter the next interface.

Where is the password?

I put the password data in app In the config file, right-click add new item in solution explorer to add it. Then add the following code to it:

  <appSettings>
    <add key="CMD" value="123123"/>
  </appSettings>

Then add a field CMD to the entry form just now, and use the configuration manager to read out the configuration and assign it:

public readonly string CMD=ConfigurationManager.AppSettings["CMD"].ToString() ;

The function of the OK button above is to display the next interface if the password is correct, so let's create the next interface first:

With this interface, you can write the click event of the OK button in the first interface:

private void button1_Click(object sender, EventArgs e)
{
    ;
    string entered_cmd = textBox1.Text; 
    if(entered_cmd.Equals(CMD))
    {
        (new GetPwd()).Show();
        this.Hide();
    }
    else
    {
        MessageBox.Show("error!","warning",MessageBoxButtons.OK, MessageBoxIcon.Warning);
    }
}

In this way, the code of the first interface is finished (yes, it's so simple).

Account information query interface

That is, the second form above. The initial state of its loading is as follows:

The two text boxes used to display the account and password are invisible (when the entered platform exists and click OK), and read-only. like this:

A small problem

Like the previous form, I bound this form with enter (equivalent to clicking the OK button) and esc shortcut keys. But when I close this form, I can't do any more operations, but the process of this program is not over. How to solve this problem? I learned about delegation some time ago, so I thought of a better method than the school teacher once taught (I didn't learn delegation at that time. The teacher taught me to pass the first form object to the second form): define a delegation field public action close for the second form_ main; Then, when the form is displayed, you can pass the close() method of the previous form.
Modify the previous code:

(new GetPwd() {close_main=this.Close}).Show();

Then execute this method in the FormClosed event of the second form.

private void GetPwd_FormClosed(object sender, FormClosedEventArgs e)
{
    close_main();
}

query

I put all the account information in a json file: PWD json, about various logical operations on it, I draw a class Manager:

class Manager
{
    public static string GetjsonString()
    {
        // Get the entire json string
        if(!File.Exists(Path.GetFullPath(@"..//..") + ".../PWD.JSON"))
        {
            File.Create(Path.GetFullPath(@"..//..") + ".../PWD.JSON");
        }
        StreamReader jsonFile = File.OpenText(Path.GetFullPath(@"..//..") + ".../PWD.JSON");
        string res = jsonFile.ReadToEnd();
        jsonFile.Close();
        return res;
    }
    public static List<Acount> GetAcountsList()
    {
        //Serialize the json string into a collection object
        return JsonConvert.DeserializeObject<List<Acount>>(GetjsonString());
    }
    public static Acount SearchAcount(string platform)
    {
        //Search for platform account
        List<Acount> acounts = GetAcountsList();
        if(acounts==null||acounts.Count==0)
        {
            return null;
        }
        var res = from a in acounts
              where a.platForm == platform
              select a;
        return res.Count()>=1?res.First():null;
    }
    public static bool CheckExistence(Acount acount)
    {
        //Check whether the account of account exists
        //Check whether the account exists
        List<Acount> acounts = GetAcountsList();
        var res = from a in acounts
                  where a.platForm==acount.platForm&&a.acount == acount.acount && a.password == acount.password
                  select a;
        return res.Count() == 1;
    }
    public static void AddAcount(Acount a)
    {
        //Add an account information
        if(a.platForm==""||a.acount==""||a.password=="")
        {
            MessageBox.Show("Please enter complete information!", "warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return ;
        }
        List<Acount> acounts = GetAcountsList();
        acounts.Add(a);
        string res = JsonConvert.SerializeObject(acounts);
        StreamWriter jsonwriter = new StreamWriter(Path.GetFullPath(@"..//..") + ".../PWD.JSON");
        jsonwriter.WriteLine(res);
        jsonwriter.Close();
    }
}

With these methods, other places are very simple. Click OK on the query interface to see the following events:

private void button1_Click(object sender, EventArgs e)
{
    Acount acount = Manager.SearchAcount(txt_platform.Text.ToLower());
    if(acount!=null)
    {
        txt_uId.Text = acount.acount;
        txt_pwd.Text = acount.password;
        txt_uId.Visible = true;
        txt_pwd.Visible = true;
        txt_uId.ReadOnly = true;
        txt_pwd.ReadOnly = true;
    }
    else
    {
        MessageBox.Show("No such account!", "warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
    }
}

add to

The third interface is used to add and call out through the Add button in the second interface.
It looks like this:

My assumption is that if you want to Add account information, you need to verify your identity again: enter an existing correct account information to pass the verification, and still use this interface to Add after passing the verification (the three text boxes are used to enter the platform, account and password in turn). This interface has only one button. Its text attribute is "Check" during verification and "Add" when adding. The title of the form also changes accordingly. The click events of this button are as follows:

private void button1_Click(object sender, EventArgs e)
{
    if(btn_check.Text=="Check")
    {
        if (Manager.CheckExistence(new Acount(txt_check_platform.Text.ToLower(), txt_check_uid.Text, txt_check_pwd.Text)))
        {
            txt_check_platform.Text = "";
            txt_check_uid.Text = "";
            txt_check_pwd.Text = "";
            this.Text = "Add password";
            btn_check.Text = "Add";
            txt_check_platform.Focus();
        }
        else
        {
            MessageBox.Show("Verification failed!!", "Verification feedback", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }
    }
    else
    {
        Manager.AddAcount(new Acount(txt_check_platform.Text.ToLower(), txt_check_uid.Text, txt_check_pwd.Text));
        this.close();
    }            
}

When adding:

In addition, the third interface also performs the same shortcut keys and closing processing as the previous interface

last

This program is very simple. Of course, many other functions can be extended in the future. Although the production process is very simple, I still have a very important harvest, which is newtonsoft JSON is a tool. Of course, there is also a point when it eases my burden of remembering countless passwords.

To record their learning process

Tags: C#

Posted by PHP-Editors.com on Mon, 23 May 2022 22:59:00 +0300