I have a admin account in Windows Forms. I have a code that create a account to the lusrmgr but the problem is when I want to write username before creating a account, I will always have a username called NowyUzytkownik (in polish language it's: NewUser) and I want to make textbox write a username that really works.
What I have tried:
This is parts of my code from Form2.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
namespace WindowsFormsApp1
{
public partial class Form2 : Form
{
private static string savedUsername = "";
private static string savedFirstPassword = "";
public static string AllForm2 = "";
private string sqlServerName;
public string UsernameValue { get; private set; }
public string PasswordValue { get; private set; }
public string EnteredUsername { get; private set; }
List<string> users = new List<string>();
List<string> passwords = new List<string>();
public string SqlServerName
{
get { return sqlServerName; }
set { sqlServerName = value; }
}
public Form2()
{
InitializeComponent();
CenterToScreen();
}
public static string DataFromUsername { get; set; }
private int failedAttempts=0;
private bool buttonBlocked = false;
string connectionString = $"Server=localhost;Database=master;Integrated Security=True;";
private string selectedUsername = "";
private void Username_TextChanged(object sender, EventArgs e)
{
string[] allowedUsers = {
"Test",
"Gość",
"Konto domyślne",
"WDAGUtilityAccount",
"Administrator"
};
string inputText = Username.Text.Trim();
if (allowedUsers.Contains(inputText))
{
if (inputText == "Administrator")
{
string allText = $"Domenowy i lokalny użytkownik: {inputText}";
AllText2.Text = allText;
}
else
{
string allText = $"Lokalny użytkownik: {inputText}";
AllText2.Text = allText;
}
}
else
{
string allText = $"Nowy użytkownik: {inputText}";
AllText2.Text = allText;
}
selectedUsername = Username.Text;
savedUsername = Username.Text;
UsernameValue = Username.Text;
EnteredUsername = Username.Text;
}
private void FirstPassword_TextChanged(object sender, EventArgs e)
{
string enteredPassword = FirstPassword.Text;
savedFirstPassword = FirstPassword.Text;
PasswordValue = FirstPassword.Text;
}
private void NextForm3_Click(object sender, EventArgs e)
{
string username = Username.Text;
string password = FirstPassword.Text;
string enteredPassword = FirstPassword.Text;
string password1 = FirstPassword.Text;
string password2 = FirstPassword.Text;
string[] dozwoloneNazwy = { "Test", "Gość", "Konto Domyślne", "WDAGUtilityAccount" };
string wpisaneNazwa = Username.Text;
string sqlServerName = SqlServerName;
bool containsDigit = false;
foreach (char c in password1)
{
if (char.IsDigit(c))
{
containsDigit = true;
break;
}
}
bool containsSpecialCharacter = false;
foreach (char c in password2)
{
if (!char.IsLetterOrDigit(c))
{
containsSpecialCharacter = true;
break;
}
}
string password3 = FirstPassword.Text;
bool hasUpperCaseLetter = false;
foreach (char character in password3)
{
if (char.IsUpper(character))
{
hasUpperCaseLetter = true;
break;
}
}
string password4 = FirstPassword.Text;
bool hasLowerCaseLetter = false;
foreach (char character in password4)
{
if (char.IsLower(character))
{
hasUpperCaseLetter = true;
break;
}
}
if (UserNotExistRadioButton.Checked)
{
if (password1 == password2 && !string.IsNullOrEmpty(password1) && !string.IsNullOrEmpty(password2))
{
ExistUserList.Items.Add(username);
SaveUsersToFile();
}
}
if (Array.Exists(dozwoloneNazwy, nazwa => nazwa == wpisaneNazwa))
{
MessageBox.Show("Wybierz przycisk istniejący użytkownik i wybierz nazwę użytkownika z listy", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (UserExistRadioButton.Checked == false && UserNotExistRadioButton.Checked == false)
{
MessageBox.Show("Wybierz przycisk nowy użytkownik lub istniejący użytkownik", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (UserExistRadioButton.Checked)
{
if (buttonBlocked)
{
MessageBox.Show("Przycisk jest zablokowany. Poczekaj 10 sekund.");
return;
}
if (ExistUserList.SelectedItem == null)
{
MessageBox.Show("Wybierz istniejącą nazwę użytkownika", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (buttonBlocked)
{
MessageBox.Show("Przycisk jest zablokowany. Poczekaj lub skontaktuj się z administratorem.");
return;
}
bool userExists = CheckIfUserExists(selectedUsername);
if (userExists)
{
bool passwordIsCorrect = CheckIfPasswordIsCorrect(selectedUsername, enteredPassword);
if (AuthenticateUser(username, password))
{
Form3 next3 = new Form3(username, password);
next3.Show();
this.Close();
}
else
{
failedAttempts++;
if (failedAttempts >= 3)
{
BlockButtonForSomeTime();
}
else
{
MessageBox.Show("Podałeś złe hasło. Pozostało prób: " + (3 - failedAttempts));
}
}
}
else
{
MessageBox.Show("Użytkownik nie istnieje.");
}
if (ExistUserList.SelectedItem != null)
{
string selectedUsername = ExistUserList.SelectedItem.ToString();
string connectionString = $"Server={sqlServerName};Database=master;Integrated Security=True;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
try
{
connection.Open();
}
catch (Exception ex)
{
MessageBox.Show("Wystąpił błąd: " + ex.Message);
}
finally
{
connection.Close();
}
}
}
else
{
MessageBox.Show("Proszę wybrać użytkownika z listy.");
}
}
else if (UserNotExistRadioButton.Checked)
{
if (string.IsNullOrEmpty(Username.Text))
{
MessageBox.Show("Musisz wpisać nazwę użytkownika", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (Username.Text.Length < 3)
{
MessageBox.Show("Musisz wpisać 3 lub więcej liter w nazwie użytkownika", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (FirstPassword.Text != SecondPassword.Text)
{
failedAttempts++;
if (failedAttempts >= 3)
{
NextForm3.Enabled = false;
buttonBlocked = true;
FirstPassword.Enabled = false;
SecondPassword.Enabled = false;
FirstPassword.Text = string.Empty;
SecondPassword.Text = string.Empty;
failedAttempts = 0;
MessageBox.Show("Podałeś złe hasło trzy razy. Przycisk zostanie zablokowany na 10 sekund.");
Timer timer = new Timer();
timer.Interval = 10000;
Czas czas = new Czas();
czas.Show();
this.Close();
timer.Tick += (s, ev) =>
{
NextForm3.Enabled = true;
buttonBlocked = false;
FirstPassword.Enabled = true;
SecondPassword.Enabled = true;
MessageBox.Show("Przycisk został odblokowany.");
timer.Stop();
};
timer.Start();
}
else
{
MessageBox.Show("Hasła muszą być takie same. Pozostało prób: " + (3 - failedAttempts));
}
}
else if (string.IsNullOrEmpty(FirstPassword.Text) && string.IsNullOrEmpty(SecondPassword.Text) && password.Length < 8)
{
MessageBox.Show("Musisz wpisać hasło, powtórzyć hasło, musisz wpisać 8 znaków w haśle", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (!containsDigit && !containsSpecialCharacter && !hasUpperCaseLetter && !hasLowerCaseLetter)
{
MessageBox.Show("Musisz wpisać chociażby jedną liczbę w haśle." +
"Musisz wpisać chociażby jeden znak specjalny w haśle" +
"Musisz wpisać chociażby jedną dużą literę w haśle" +
"Musisz wpisać chociażby jedną mniejszą literę w haśle", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
AllForm2 = AllText2.Text;
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string query = $"SELECT COUNT(*) FROM sys.server_principals WHERE name = @Username";
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("@Username", selectedUsername);
int count = (int)command.ExecuteScalar();
MessageBox.Show("Połączono użytkownika: " + selectedUsername + " z bazą danych");
}
}
}
catch (Exception ex)
{
MessageBox.Show("Błąd połączenia z bazą danych: " + ex.Message, "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
Form3 next3 = new Form3(username, password);
next3.Show();
this.Close();
}
if (string.IsNullOrEmpty(enteredPassword))
{
MessageBox.Show("Musisz wpisać hasło", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
}
This is all my Form3.cs code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using System.Management;
namespace WindowsFormsApp1
{
public partial class Form3 : Form
{
private Form2 form2;
private string usernameFromForm2;
private string passwordFromForm2;
private string enteredUsername;
private string enteredPassword;
public Form3(string username, string password)
{
this.form2 = form2;
InitializeComponent();
CenterToScreen();
AllText3.Text = Form1.AllForm1 + "\r\n" + Form2.AllForm2;
usernameFromForm2 = username;
passwordFromForm2 = password;
enteredUsername = username;
enteredPassword = password;
}
private void Back_Click(object sender, EventArgs e)
{
Form2 back2 = new Form2();
back2.Show();
this.Close();
}
private void AllText3_TextChanged(object sender, EventArgs e)
{
}
private void NextForm4_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
string username = "NowyUzytkownik";
string password = "NoweHaslo";
Process process = new Process();
process.StartInfo.FileName = "net";
process.StartInfo.Arguments = $"user {username} {password} /add";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.CreateNoWindow = true;
process.Start();
string output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
if (process.ExitCode == 0)
{
MessageBox.Show($"Utworzono nowego użytkownika: {username}");
}
else
{
MessageBox.Show($"Błąd podczas tworzenia użytkownika. Wynik: {output}");
}
}
private void CreateLocalUserAccount(string username, string password)
{
try
{
ObjectGetOptions options = new ObjectGetOptions();
ManagementPath path = new ManagementPath("Win32_UserAccount");
ManagementClass processClass = new ManagementClass(new ManagementScope("\\\\.\\root\\cimv2"), path, options);
ManagementBaseObject inParams = processClass.GetMethodParameters("Create");
inParams["Name"] = username;
inParams["Password"] = password;
inParams["Description"] = "Nowy użytkownik";
inParams["PasswordChangeable"] = true;
inParams["PasswordExpires"] = false;
ManagementBaseObject outParams = processClass.InvokeMethod("Create", inParams, null);
uint result = (uint)(outParams.Properties["ReturnValue"].Value);
if (result == 0)
{
MessageBox.Show("Utworzono nowego użytkownika: " + username);
}
else
{
MessageBox.Show("Błąd podczas tworzenia użytkownika. Kod błędu: " + result);
}
}
catch (Exception ex)
{
MessageBox.Show("Wystąpił błąd: " + ex.Message);
}
}
}
}