
- •1.Теоретическое описание линейного списка с алгоритмами реализации основных операций.
- •2.Описание основных понятий и механизмов ооп.
- •3.Описание всех разработанных классов
- •4.Описание демонстрационного модуля с характеристикой использованных стандартных компонентов.
- •5.Описание структуры программы.
- •6) Полный листинг проекта с краткими комментариями:
5.Описание структуры программы.
Приложение состоит из 2 форм и 2 диалога, а так же из классов user, guest, defUser, admin, listElement и Container.
Основная форма Form1 служит для показа текущего состояния контейнера и выполнения с ним всех действий, предусмотренных в задании. Она содержит компоненты dataGridView, menuStrip, openFileDialog, saveFileDIalog.
Вспомогательный диалог userForm используется для задания полей создаваемого пользователя. Для ввода значений каждого из полей используется компонент textBox. Из-за того, что в зависимости от типа создаваемого файла следует задавать три (для гостя) или четыре (для пользователя и администратора) поля, окно создается динамически в зависимости от выбранного типа файла.
6) Полный листинг проекта с краткими комментариями:
user.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace курсовая_2курс
{
abstract class user
{
private string name, rights;
private user next = null;
public user(string Name, string Rights)
{
this.Name = Name;
this.Rights = Rights;
}
public string Name
{
get
{
return this.name;
}
set
{
this.name = value;
}
}
public string Rights
{
get
{
return this.rights;
}
set
{
this.rights = value;
}
}
public user Next
{
get
{
return this.next;
}
set
{
this.next = value;
}
}
abstract public string show();
}
}
admin.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace курсовая_2курс
{
class admin : defUser
{
public admin(string Name, string Rights, string Password) : base(Name, Rights, Password)
{
}
public void deleteUser(defUser user) { /* ... */ }
public override string show()
{
string str = "Администратор " + this.Name + " " + this.Rights + " " + this.Password;
return str;
}
}
}
defUser.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace курсовая_2курс
{
class defUser : user
{
private string password;
public defUser(string Name, string Rights, string Password) : base(Name, Rights)
{
this.Password = Password;
}
public string Password
{
get
{
return this.password;
}
set
{
this.password = value;
}
}
public override string show()
{
string str = "Пользователь " + this.Name + " " + this.Rights + " " + this.Password;
return str;
}
}
}
guest.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace курсовая_2курс
{
class guest : user
{
public guest(string Name, string Rights) : base(Name, Rights)
{
}
public override string show()
{
string str = "Гость " + this.Name + " " + this.Rights;
return str;
}
}
}
elementList.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace курсовая_2курс
{
class listElement
{
private listElement next;
private user info;
public listElement()
{
this.Next = null;
}
public listElement(user User)
{
this.Info = User;
this.Next = null;
}
public listElement Next
{
get { return this.next; }
set { this.next = value; }
}
public user Info
{
get { return this.info; }
set { this.info = value; }
}
}
}
Container.cs
using System;
using System.IO;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace курсовая_2курс
{
class Container
{
private listElement head;
#region Конструктор
public Container()
{
this.head = new listElement();
}
#endregion
#region Добавление пользователя после заданного
public void addUserAfter(user User, user afterUser)
{
listElement iterator, newElement;
bool find;
newElement = new listElement(User);
find = false;
for (iterator = head.Next; iterator != null; iterator = iterator.Next)
{
if (iterator != null && iterator.Info == afterUser && afterUser != null)
{
find = true;
break;
}
}
if (find)
{
newElement.Next = iterator.Next;
iterator.Next = newElement;
}
else
head.Next = newElement;
}
#endregion
#region Добавление пользователя перед заданным
public bool addUserBefore(user User, user beforeUser)
{
listElement iterator, tmp, newElement;
bool find;
newElement = new listElement(User);
find = false;
tmp = null;
if (head.Next == null || head.Info == beforeUser)
{
newElement.Next = head.Next;
head.Next = newElement;
}
else
{
for (iterator = head.Next; iterator != null; iterator = iterator.Next)
{
if (iterator.Info == beforeUser)
{
find = true;
break;
}
tmp = iterator;
}
if (find)
{
tmp.Next = newElement;
newElement.Next = iterator;
}
else
return false;
}
return true;
}
#endregion
#region Удаление пользователя
public bool deleteUser(user User)
{
listElement iterator, tmp;
bool find;
find = false;
tmp = null;
if (head.Next != null)
{
if (head.Next.Info == User)
{
head.Next = head.Next.Next;
}
else
{
for (iterator = head.Next; iterator != null; iterator = iterator.Next)
{
if (iterator.Info == User)
{
find = true;
break;
}
tmp = iterator;
}
if (find)
{
if (iterator.Next != null)
tmp.Next = iterator.Next;
else
tmp.Next = null;
}
else
return false;
}
return true;
}
else
return false;
}
#endregion
#region Сохранение в файл 1.
public void saveToFile()
{
listElement tmp;
try
{
//FileStream outPutFile = new FileStream("D:\\users.txt", FileMode.OpenOrCreate, FileAccess.Write);
//StreamWriter sw = new StreamWriter(outPutFile);
File.Delete("D:\\users.txt");
using (StreamWriter sw = File.AppendText("D:\\users.txt"))
{
tmp = this.head.Next;
while (tmp != null)
{
try
{
sw.WriteLine(tmp.Info.show(), Encoding.GetEncoding(1251));
tmp = tmp.Next;
}
catch (IOException err)
{
MessageBox.Show(err.Message);
}
}
}
//sw.Close();
}
catch (IOException err)
{
MessageBox.Show(err.Message);
}
}
#endregion
#region Сохранение в файл 2.
public void saveToFile(string fName)
{
listElement tmp;
try
{
if (File.Exists(fName))
File.Delete(fName);
using (StreamWriter sw = File.AppendText(fName))
{
tmp = this.head.Next;
while (tmp != null)
{
try
{
sw.WriteLine(Encrypt(tmp.Info.show(), "Passpord11", "Password22", "SHA1", 2,
"16CHARSLONG12345", 256), Encoding.GetEncoding(1251));
tmp = tmp.Next;
}
catch (IOException err)
{
MessageBox.Show(err.Message);
}
}
}
}
catch (IOException err)
{
MessageBox.Show(err.Message);
}
}
#endregion
#region Чтение из файла 1.
public void readFromFile()
{
try
{
StreamReader inputFile = File.OpenText("D:\\users.txt");
string read = null, userParams, Name, Password, Rights;
user userN = null, userBefore = null;
while ((read = inputFile.ReadLine()) != null)
{
string[] split = read.Split(new Char[] { ' ', ',', '.', ':', ';' });
userParams = split[0].Trim();
Name = split[1].Trim();
Rights = split[2].Trim();
switch(userParams)
{
case "Гость":
userN = new guest(Name, Rights);
break;
case "Пользователь":
Password = split[3].Trim();
userN = new defUser(Name, Rights, Password);
break;
case "Администратор":
Password = split[3].Trim();
userN = new admin(Name, Rights, Password);
break;
}
this.addUserAfter(userN, userBefore);
userBefore = userN;
}
inputFile.Close();
}
catch (IOException err)
{
MessageBox.Show(err.Message);
}
}
#endregion
#region Чтение из файла 2.
public void readFromFile(string fName)
{
try
{
StreamReader inputFile = File.OpenText(fName);
string read = null, userParams, Name, Password, Rights;
user userN = null, userBefore = null;
while ((read = inputFile.ReadLine()) != null)
{
read = Decrypt(read, "Passpord11", "Password22", "SHA1", 2,
"16CHARSLONG12345", 256);
string[] split = read.Split(new Char[] { ' ', ',', '.', ':', ';' });
userParams = split[0].Trim();
Name = split[1].Trim();
Rights = split[2].Trim();
switch (userParams)
{
case "Гость":
userN = new guest(Name, Rights);
break;
case "Пользователь":
Password = split[3].Trim();
userN = new defUser(Name, Rights, Password);
break;
case "Администратор":
Password = split[3].Trim();
userN = new admin(Name, Rights, Password);
break;
}
this.addUserAfter(userN, userBefore);
userBefore = userN;
}
inputFile.Close();
}
catch (IOException err)
{
MessageBox.Show(err.Message);
}
}
#endregion
#region Метод show
public void show(DataGridView table)
{
if (this.head.Next != null)
{
listElement tmp = this.head.Next;
while (tmp != null)
{
if (tmp.Info is admin)
table.Rows.Add("Администратор", tmp.Info.Name, (tmp.Info as admin).Password, tmp.Info.Rights);
else if (tmp.Info is guest)
table.Rows.Add("Гость" ,tmp.Info.Name, "", tmp.Info.Rights);
else if (tmp.Info is defUser)
table.Rows.Add("Пользователь", tmp.Info.Name, (tmp.Info as defUser).Password, tmp.Info.Rights);
tmp = tmp.Next;
}
}
}
#endregion
#region Поиск пользователя
public user search(string sName)
{
if (this.head.Next != null)
{
listElement tmp = this.head.Next;
while (tmp != null)
{
if (tmp.Info.Name == sName)
return tmp.Info;
tmp = tmp.Next;
}
}
return null;
}
#endregion
#region Static Functions
/// <summary>
/// Encrypts a string
/// </summary>
/// <param name="plainText">Text to be encrypted</param>
/// <param name="password">Password to encrypt with</param>
/// <param name="salt">Salt to encrypt with</param>
/// <param name="hashAlgorithm">Can be either SHA1 or MD5</param>
/// <param name="passwordIterations">Number of iterations to do</param>
/// <param name="initialVector">Needs to be 16 ASCII characters long</param>
/// <param name="keySize">Can be 128, 192, or 256</param>
/// <returns>An encrypted string</returns>
public string Encrypt(string plainText, string password,
string salt = "Kosher", string hashAlgorithm = "SHA1",
int passwordIterations = 2, string initialVector = "OFRna73m*aze01xY",
int keySize = 256)
{
if (string.IsNullOrEmpty(plainText))
return "";
byte[] initialVectorBytes = Encoding.ASCII.GetBytes(initialVector);
byte[] saltValueBytes = Encoding.ASCII.GetBytes(salt);
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
PasswordDeriveBytes derivedPassword = new PasswordDeriveBytes(password, saltValueBytes, hashAlgorithm, passwordIterations);
byte[] keyBytes = derivedPassword.GetBytes(keySize / 8);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
byte[] cipherTextBytes = null;
using (ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initialVectorBytes))
{
using (MemoryStream memStream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream(memStream, encryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
cipherTextBytes = memStream.ToArray();
memStream.Close();
cryptoStream.Close();
}
}
}
symmetricKey.Clear();
return Convert.ToBase64String(cipherTextBytes);
}
/// <summary>
/// Decrypts a string
/// </summary>
/// <param name="cipherText">Text to be decrypted</param>
/// <param name="password">Password to decrypt with</param>
/// <param name="salt">Salt to decrypt with</param>
/// <param name="hashAlgorithm">Can be either SHA1 or MD5</param>
/// <param name="passwordIterations">Number of iterations to do</param>
/// <param name="initialVector">Needs to be 16 ASCII characters long</param>
/// <param name="keySize">Can be 128, 192, or 256</param>
/// <returns>A decrypted string</returns>
public string Decrypt(string cipherText, string password,
string salt = "Kosher", string hashAlgorithm = "SHA1",
int passwordIterations = 2, string initialVector = "OFRna73m*aze01xY",
int keySize = 256)
{
if (string.IsNullOrEmpty(cipherText))
return "";
byte[] initialVectorBytes = Encoding.ASCII.GetBytes(initialVector);
byte[] saltValueBytes = Encoding.ASCII.GetBytes(salt);
byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
PasswordDeriveBytes derivedPassword = new PasswordDeriveBytes(password, saltValueBytes, hashAlgorithm, passwordIterations);
byte[] keyBytes = derivedPassword.GetBytes(keySize / 8);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
byte[] plainTextBytes = new byte[cipherTextBytes.Length];
int byteCount = 0;
using (ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initialVectorBytes))
{
using (MemoryStream memStream = new MemoryStream(cipherTextBytes))
{
using (CryptoStream cryptoStream = new CryptoStream(memStream, decryptor, CryptoStreamMode.Read))
{
byteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
memStream.Close();
cryptoStream.Close();
}
}
}
symmetricKey.Clear();
return Encoding.UTF8.GetString(plainTextBytes, 0, byteCount);
}
#endregion
}
}
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using HotKeysLibrary;
namespace курсовая_2курс
{
internal partial class Form1 : Form
{
private Container container;
private int RowIndex = 0, ColumnIndex;
private bool after, click, file = false, changed = false;
HotKeysManager manager = new HotKeysManager();
#region Конструктор Form1
public Form1()
{
InitializeComponent();
OpenFileDialogInit();
SaveFileDialogInit();
this.container = new Container();
this.container.show(this.dataGridView1);
}
#endregion
#region Инициализация диалога открытия файла
public void OpenFileDialogInit()
{
this.openFileDialog = new OpenFileDialog();
this.openFileDialog.Filter = "All files (*.d3g) | *.d3g";
this.openFileDialog.Multiselect = false;
this.openFileDialog.Title = "Выберите файл";
}
#endregion
#region Инициализация диалога сохранения файла
public void SaveFileDialogInit()
{
this.saveFileDialog = new SaveFileDialog();
this.saveFileDialog.Filter = "All files (*.d3g) | *.d3g";
this.saveFileDialog.Title = "Сохранение";
}
#endregion
#region Меню - Создать
private void onMenuClick_Create(object sender, EventArgs e)
{
userForm UserForm = new userForm();
UserForm.ShowInTaskbar = false;
UserForm.StartPosition = FormStartPosition.CenterScreen;
UserForm.ShowDialog(this);
click = true;
}
#endregion
#region Меню - Открыть
private void onMenuClick_Open(object sender, EventArgs e)
{
if (this.openFileDialog.ShowDialog() == DialogResult.OK)
{
this.container.readFromFile(this.openFileDialog.FileName);
this.container.show(this.dataGridView1);
this.file = true;
this.changed = false;
this.closeToolStripMenuItem.Enabled = true;
this.saveAsToolStripMenuItem.Enabled = true;
}
}
#endregion
#region Меню - Сохранить
private void onMenuSaveButton_Click(object sender, EventArgs e)
{
this.Save();
}
private void Save()
{
this.container.saveToFile(this.openFileDialog.FileName);
this.saveToolStripMenuItem.Enabled = false;
this.closeToolStripMenuItem.Enabled = true;
this.changed = false;
}
#endregion
#region Меню - Сохранить как
private void onMenuSaveAsButton_Click(object sender, EventArgs e)
{
this.SaveAs();
}
private void SaveAs()
{
if (this.saveFileDialog.ShowDialog() == DialogResult.OK)
{
this.container.saveToFile(this.saveFileDialog.FileName);
this.saveToolStripMenuItem.Enabled = false;
this.closeToolStripMenuItem.Enabled = true;
this.file = true;
this.changed = false;
}
}
#endregion
#region Меню - Закрыть
private void onMenuClick_Close(object sender, EventArgs e)
{
if (this.changed)
{
DialogResult dialogResult = MessageBox.Show("Данные файла были изменены.\nСохранить изменения в файле?", "Изменения", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information);
if (dialogResult != DialogResult.Cancel)
{
if (dialogResult == DialogResult.Yes)
this.container.saveToFile(this.openFileDialog.FileName);
this.clearTable();
}
}
else
this.clearTable();
}
#endregion
#region Меню - Выход
private void onMenuExitButton_Click(object sender, EventArgs e)
{
this.Close();
}
#endregion
#region Очистка полей таблицы
private void clearTable()
{
while (dataGridView1.Rows.Count != 0)
dataGridView1.Rows.Remove(dataGridView1.Rows[dataGridView1.Rows.Count - 1]);
this.file = false;
this.changed = false;
this.openFileDialog.FileName = null;
this.closeToolStripMenuItem.Enabled = false;
this.saveToolStripMenuItem.Enabled = false;
this.saveAsToolStripMenuItem.Enabled = false;
}
#endregion
#region Создание пользователя. Обработка параметров из userForm
public void onUserCreate(string userType, string userName, string userRights, string userPassword)
{
user newUser = null;
switch (userType)
{
case "Гость":
newUser = new guest(userName, userRights);
break;
case "Пользователь":
newUser = new defUser(userName, userRights, userPassword);
break;
case "Администратор":
newUser = new admin(userName, userRights, userPassword);
break;
}
if (!this.click)
{
if (this.after)
{
this.dataGridView1.Rows.Insert(this.RowIndex + 1, userType, userName, userPassword, userRights);
user tmpUser = this.container.search(dataGridView1[this.ColumnIndex, this.RowIndex].Value.ToString());
this.container.addUserAfter(newUser, tmpUser);
}
else
{
this.dataGridView1.Rows.Insert(this.RowIndex, userType, userName, userPassword, userRights);
user tmpUser = this.container.search(dataGridView1[this.ColumnIndex, this.RowIndex].Value.ToString());
this.container.addUserBefore(newUser, tmpUser);
}
}
else
{
this.dataGridView1.Rows.Add(userType, userName, userPassword, userRights);
this.container.addUserAfter(newUser, null);
}
if (this.file)
{
this.changed = true;
this.saveToolStripMenuItem.Enabled = true;
}
else
this.saveAsToolStripMenuItem.Enabled = true;
}
#endregion
#region Клик "добавить до"
private void addBefore_Click(object sender, EventArgs e)
{
this.after = false;
this.click = false;
userForm UserForm = new userForm();
UserForm.ShowInTaskbar = false;
UserForm.StartPosition = FormStartPosition.CenterScreen;
UserForm.ShowDialog(this);
}
#endregion
#region Клик "добавить после"
private void addAfter_Click(object sender, EventArgs e)
{
this.after = true;
this.click = false;
userForm UserForm = new userForm();
UserForm.ShowInTaskbar = false;
UserForm.StartPosition = FormStartPosition.CenterScreen;
UserForm.ShowDialog(this);
}
#endregion
#region Клик "удалить пользователя"
private void delete_Click(object sender, EventArgs e)
{
DialogResult dialogResult = MessageBox.Show("Вы уверены, что хотите удалить пользователя?", "Удаление", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
if (dialogResult == DialogResult.OK)
{
user tmpUser = this.container.search(dataGridView1[this.ColumnIndex, this.RowIndex].Value.ToString());
if (this.container.deleteUser(tmpUser))
{
this.dataGridView1.Rows.RemoveAt(this.RowIndex);
if (this.file)
{
this.changed = true;
this.saveToolStripMenuItem.Enabled = true;
}
}
}
}
#endregion
#region Обработка клика правой мышкой по ячейке таблицы
private void context_Opening(object sender, CancelEventArgs e)
{
ContextMenuStrip tContextMenu = (ContextMenuStrip)sender;
Point tLocation = new Point(tContextMenu.Left, tContextMenu.Top);
tLocation = dataGridView1.PointToClient(Cursor.Position);
DataGridView.HitTestInfo tHitTestInfo = dataGridView1.HitTest(tLocation.X, tLocation.Y);
if (tHitTestInfo.Type == DataGridViewHitTestType.Cell)
{
this.ColumnIndex = 1;
this.RowIndex = tHitTestInfo.RowIndex;
dataGridView1[tHitTestInfo.ColumnIndex, this.RowIndex].Selected = true;
}
else
{
e.Cancel = true;
}
}
#endregion
#region Закрытие формы
private void FormClosing_Form1(object sender, FormClosingEventArgs e)
{
#region Если был открыт файл и изменены данные
if (this.file && this.changed)
{
DialogResult dialogResult = MessageBox.Show("Сохранить данные?", "Изменения", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information);
if (dialogResult == DialogResult.Yes)
{
this.container.saveToFile(this.openFileDialog.FileName);
}
else if (dialogResult == DialogResult.Cancel)
e.Cancel = true;
}
#endregion
#region Если файл не был открыт и внесены какие-то данные
else if (dataGridView1.Rows.Count != 0 && !this.file)
{
DialogResult dialogResult = MessageBox.Show("Сохранить данные?", "Изменения", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information);
if (dialogResult == DialogResult.Yes)
{
DialogResult dialogResultSave = this.saveFileDialog.ShowDialog();
if (dialogResultSave == DialogResult.OK)
{
this.container.saveToFile(this.saveFileDialog.FileName);
this.clearTable();
}
else if (dialogResultSave == DialogResult.Cancel)
e.Cancel = true;
}
else if (dialogResult == DialogResult.Cancel)
e.Cancel = true;
}
#endregion
}
#endregion
#region Справка
private void Help_Click(object sender, EventArgs e)
{
MessageBox.Show("Данное программное обеспечение является частью курсовой работы.\nОно может быть использовано только в ознакомительных и учебных целях!\n\nВыполнил работу студент группы 4212 - Гарифуллин Ильшат.\nПринял доцент к.т.н.: Козин А.Н.\nKazan © 2013 год", "Справка", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
#endregion
}
}
userForm.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace курсовая_2курс
{
public partial class userForm : Form
{
public userForm()
{
InitializeComponent();
}
private void onCreateButton_Click(object sender, EventArgs e)
{
((Form1)this.Owner).onUserCreate(this.userTypeComboBox.Text, this.userNameTextBox.Text, this.userRightsComboBox.Text, this.userPasswordTextBox.Text);
this.Close();
}
private void userType_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.userTypeComboBox.Text == "Пользователь" || this.userTypeComboBox.Text == "Администратор")
{
this.userPasswordLabel.Visible = true;
this.userPasswordTextBox.Visible = true;
}
else
{
this.userPasswordLabel.Visible = false;
this.userPasswordTextBox.Visible = false;
}
this.checkButton();
}
private void userRights_SelectedIndexChanged(object sender, EventArgs e)
{
this.checkButton();
}
private void userName_TextChanged(object sender, EventArgs e)
{
this.checkButton();
}
private void onKeyPress_passwordField(object sender, KeyPressEventArgs e)
{
this.checkButton();
}
private void checkButton()
{
if (this.userRightsComboBox.Text.Length != 0 && this.userNameTextBox.Text.Length != 0)
{
this.userButton.Visible = false;
if ((this.userTypeComboBox.Text == "Пользователь" || this.userTypeComboBox.Text == "Администратор") && this.userPasswordTextBox.Text.Length != 0)
this.userButton.Visible = true;
if (this.userTypeComboBox.Text == "Гость")
this.userButton.Visible = true;
}
else
this.userButton.Visible = false;
}
private void onKeyPress_ComboBox(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == '\b')
return;
e.Handled = true;
}
private void userType_TextUpdate(object sender, EventArgs e)
{
switch (this.userTypeComboBox.Text)
{
case "Гость":
case "Пользователь":
case "Администратор":
break;
default:
this.userTypeComboBox.Text = "";
break;
}
this.checkButton();
}
private void userRights_TextUpdate(object sender, EventArgs e)
{
switch (this.userRightsComboBox.Text)
{
case "Чтение":
case "Чтение/Запись":
case "Чтение/Запись/Редактирование":
break;
default:
this.userRightsComboBox.Text = "";
break;
}
this.checkButton();
}
}
}
Form1.Designer.cs
namespace курсовая_2курс
{
partial class Form1
{
/// <summary>
/// Требуется переменная конструктора.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Код, автоматически созданный конструктором форм Windows
/// <summary>
/// Обязательный метод для поддержки конструктора - не изменяйте
/// содержимое данного метода при помощи редактора кода.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.файлToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.createToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveAsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.closeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.справкаToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.dataGridView1 = new System.Windows.Forms.DataGridView();
this.contextMenuStrip = new System.Windows.Forms.ContextMenuStrip(this.components);
this.добавитьДоToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.добавитьПослеToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.удалитьToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
this.userType = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnName = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnPassword = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnRights = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.menuStrip1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
this.contextMenuStrip.SuspendLayout();
this.SuspendLayout();
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.файлToolStripMenuItem,
this.справкаToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(651, 24);
this.menuStrip1.TabIndex = 0;
this.menuStrip1.Text = "menuStrip1";
//
// файлToolStripMenuItem
//
this.файлToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.createToolStripMenuItem,
this.openToolStripMenuItem,
this.saveToolStripMenuItem,
this.saveAsToolStripMenuItem,
this.closeToolStripMenuItem,
this.exitToolStripMenuItem});
this.файлToolStripMenuItem.Name = "файлToolStripMenuItem";
this.файлToolStripMenuItem.Size = new System.Drawing.Size(48, 20);
this.файлToolStripMenuItem.Text = "Файл";
//
// createToolStripMenuItem
//
this.createToolStripMenuItem.Name = "createToolStripMenuItem";
this.createToolStripMenuItem.Size = new System.Drawing.Size(162, 22);
this.createToolStripMenuItem.Text = "Создать";
this.createToolStripMenuItem.Click += new System.EventHandler(this.onMenuClick_Create);
//
// openToolStripMenuItem
//
this.openToolStripMenuItem.Name = "openToolStripMenuItem";
this.openToolStripMenuItem.Size = new System.Drawing.Size(162, 22);
this.openToolStripMenuItem.Text = "Открыть...";
this.openToolStripMenuItem.Click += new System.EventHandler(this.onMenuClick_Open);
//
// saveToolStripMenuItem
//
this.saveToolStripMenuItem.Enabled = false;
this.saveToolStripMenuItem.Name = "saveToolStripMenuItem";
this.saveToolStripMenuItem.Size = new System.Drawing.Size(162, 22);
this.saveToolStripMenuItem.Text = "Сохранить...";
this.saveToolStripMenuItem.Click += new System.EventHandler(this.onMenuSaveButton_Click);
//
// saveAsToolStripMenuItem
//
this.saveAsToolStripMenuItem.Enabled = false;
this.saveAsToolStripMenuItem.Name = "saveAsToolStripMenuItem";
this.saveAsToolStripMenuItem.Size = new System.Drawing.Size(162, 22);
this.saveAsToolStripMenuItem.Text = "Сохранить как...";
this.saveAsToolStripMenuItem.Click += new System.EventHandler(this.onMenuSaveAsButton_Click);
//
// closeToolStripMenuItem
//
this.closeToolStripMenuItem.Enabled = false;
this.closeToolStripMenuItem.Name = "closeToolStripMenuItem";
this.closeToolStripMenuItem.Size = new System.Drawing.Size(162, 22);
this.closeToolStripMenuItem.Text = "Закрыть";
this.closeToolStripMenuItem.Click += new System.EventHandler(this.onMenuClick_Close);
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
this.exitToolStripMenuItem.Size = new System.Drawing.Size(162, 22);
this.exitToolStripMenuItem.Text = "Выход";
this.exitToolStripMenuItem.Click += new System.EventHandler(this.onMenuExitButton_Click);
//
// справкаToolStripMenuItem
//
this.справкаToolStripMenuItem.Name = "справкаToolStripMenuItem";
this.справкаToolStripMenuItem.Size = new System.Drawing.Size(65, 20);
this.справкаToolStripMenuItem.Text = "Справка";
this.справкаToolStripMenuItem.Click += new System.EventHandler(this.Help_Click);
//
// dataGridView1
//
this.dataGridView1.AllowUserToAddRows = false;
this.dataGridView1.AllowUserToDeleteRows = false;
this.dataGridView1.AllowUserToResizeRows = false;
this.dataGridView1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.dataGridView1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
this.dataGridView1.BackgroundColor = System.Drawing.SystemColors.Control;
this.dataGridView1.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.Raised;
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.userType,
this.ColumnName,
this.ColumnPassword,
this.ColumnRights});
this.dataGridView1.EditMode = System.Windows.Forms.DataGridViewEditMode.EditProgrammatically;
this.dataGridView1.EnableHeadersVisualStyles = false;
this.dataGridView1.GridColor = System.Drawing.SystemColors.ActiveCaptionText;
this.dataGridView1.Location = new System.Drawing.Point(0, 27);
this.dataGridView1.MinimumSize = new System.Drawing.Size(534, 298);
this.dataGridView1.MultiSelect = false;
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.ReadOnly = true;
this.dataGridView1.RowHeadersWidth = 30;
this.dataGridView1.RowTemplate.ContextMenuStrip = this.contextMenuStrip;
this.dataGridView1.RowTemplate.ReadOnly = true;
this.dataGridView1.ShowEditingIcon = false;
this.dataGridView1.Size = new System.Drawing.Size(651, 305);
this.dataGridView1.TabIndex = 1;
//
// contextMenuStrip
//
this.contextMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.добавитьДоToolStripMenuItem,
this.добавитьПослеToolStripMenuItem,
this.удалитьToolStripMenuItem});
this.contextMenuStrip.Name = "contextMenuStrip";
this.contextMenuStrip.Size = new System.Drawing.Size(172, 70);
this.contextMenuStrip.Opening += new System.ComponentModel.CancelEventHandler(this.context_Opening);
//
// добавитьДоToolStripMenuItem
//
this.добавитьДоToolStripMenuItem.Name = "добавитьДоToolStripMenuItem";
this.добавитьДоToolStripMenuItem.Size = new System.Drawing.Size(171, 22);
this.добавитьДоToolStripMenuItem.Text = "Добавить до...";
this.добавитьДоToolStripMenuItem.TextAlign = System.Drawing.ContentAlignment.BottomLeft;
this.добавитьДоToolStripMenuItem.Click += new System.EventHandler(this.addBefore_Click);
//
// добавитьПослеToolStripMenuItem
//
this.добавитьПослеToolStripMenuItem.Name = "добавитьПослеToolStripMenuItem";
this.добавитьПослеToolStripMenuItem.Size = new System.Drawing.Size(171, 22);
this.добавитьПослеToolStripMenuItem.Text = "Добавить после...";
this.добавитьПослеToolStripMenuItem.TextAlign = System.Drawing.ContentAlignment.BottomLeft;
this.добавитьПослеToolStripMenuItem.Click += new System.EventHandler(this.addAfter_Click);
//
// удалитьToolStripMenuItem
//
this.удалитьToolStripMenuItem.Name = "удалитьToolStripMenuItem";
this.удалитьToolStripMenuItem.Size = new System.Drawing.Size(171, 22);
this.удалитьToolStripMenuItem.Text = "Удалить";
this.удалитьToolStripMenuItem.Click += new System.EventHandler(this.delete_Click);
//
// openFileDialog
//
this.openFileDialog.FileName = "openFileDialog";
//
// userType
//
this.userType.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None;
this.userType.FillWeight = 125.8883F;
this.userType.Frozen = true;
this.userType.HeaderText = "Тип пользователя";
this.userType.Name = "userType";
this.userType.ReadOnly = true;
this.userType.Resizable = System.Windows.Forms.DataGridViewTriState.False;
this.userType.Width = 158;
//
// ColumnName
//
this.ColumnName.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None;
this.ColumnName.FillWeight = 91.37055F;
this.ColumnName.Frozen = true;
this.ColumnName.HeaderText = "Имя";
this.ColumnName.Name = "ColumnName";
this.ColumnName.ReadOnly = true;
this.ColumnName.Resizable = System.Windows.Forms.DataGridViewTriState.False;
this.ColumnName.Width = 115;
//
// ColumnPassword
//
this.ColumnPassword.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None;
this.ColumnPassword.FillWeight = 91.37055F;
this.ColumnPassword.Frozen = true;
this.ColumnPassword.HeaderText = "Пароль";
this.ColumnPassword.Name = "ColumnPassword";
this.ColumnPassword.ReadOnly = true;
this.ColumnPassword.Resizable = System.Windows.Forms.DataGridViewTriState.False;
this.ColumnPassword.Width = 114;
//
// ColumnRights
//
this.ColumnRights.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None;
this.ColumnRights.FillWeight = 91.37055F;
this.ColumnRights.Frozen = true;
this.ColumnRights.HeaderText = "Права доступа";
this.ColumnRights.Name = "ColumnRights";
this.ColumnRights.ReadOnly = true;
this.ColumnRights.Resizable = System.Windows.Forms.DataGridViewTriState.False;
this.ColumnRights.Width = 115;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(651, 331);
this.Controls.Add(this.dataGridView1);
this.Controls.Add(this.menuStrip1);
this.KeyPreview = true;
this.MainMenuStrip = this.menuStrip1;
this.Name = "Form1";
this.Text = "Пользователи";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.FormClosing_Form1);
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
this.contextMenuStrip.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem файлToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem createToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.DataGridView dataGridView1;
private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem saveToolStripMenuItem;
private System.Windows.Forms.ContextMenuStrip contextMenuStrip;
private System.Windows.Forms.ToolStripMenuItem добавитьДоToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem добавитьПослеToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem удалитьToolStripMenuItem;
private System.Windows.Forms.OpenFileDialog openFileDialog;
private System.Windows.Forms.ToolStripMenuItem saveAsToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem closeToolStripMenuItem;
private System.Windows.Forms.SaveFileDialog saveFileDialog;
private System.Windows.Forms.ToolStripMenuItem справкаToolStripMenuItem;
private System.Windows.Forms.DataGridViewTextBoxColumn userType;
private System.Windows.Forms.DataGridViewTextBoxColumn ColumnName;
private System.Windows.Forms.DataGridViewTextBoxColumn ColumnPassword;
private System.Windows.Forms.DataGridViewTextBoxColumn ColumnRights;
}
}
userForm.Designer.cs
namespace курсовая_2курс
{
partial class userForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.userLabel = new System.Windows.Forms.Label();
this.userTypeLabel = new System.Windows.Forms.Label();
this.userTypeComboBox = new System.Windows.Forms.ComboBox();
this.userRightsLabel = new System.Windows.Forms.Label();
this.userRightsComboBox = new System.Windows.Forms.ComboBox();
this.userPasswordLabel = new System.Windows.Forms.Label();
this.userPasswordTextBox = new System.Windows.Forms.TextBox();
this.userButton = new System.Windows.Forms.Button();
this.userNameLabel = new System.Windows.Forms.Label();
this.userNameTextBox = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// userLabel
//
this.userLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 14F, System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.userLabel.Location = new System.Drawing.Point(60, 9);
this.userLabel.Name = "userLabel";
this.userLabel.Size = new System.Drawing.Size(154, 24);
this.userLabel.TabIndex = 0;
this.userLabel.Text = "Пользователь";
//
// userTypeLabel
//
this.userTypeLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.userTypeLabel.Location = new System.Drawing.Point(12, 69);
this.userTypeLabel.Name = "userTypeLabel";
this.userTypeLabel.Size = new System.Drawing.Size(137, 23);
this.userTypeLabel.TabIndex = 3;
this.userTypeLabel.Text = "Тип пользователя:";
this.userTypeLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// userTypeComboBox
//
this.userTypeComboBox.FormattingEnabled = true;
this.userTypeComboBox.Items.AddRange(new object[] {
"Гость",
"Пользователь",
"Администратор"});
this.userTypeComboBox.Location = new System.Drawing.Point(155, 71);
this.userTypeComboBox.Name = "userTypeComboBox";
this.userTypeComboBox.Size = new System.Drawing.Size(121, 21);
this.userTypeComboBox.TabIndex = 2;
this.userTypeComboBox.SelectedIndexChanged += new System.EventHandler(this.userType_SelectedIndexChanged);
this.userTypeComboBox.TextUpdate += new System.EventHandler(this.userType_TextUpdate);
this.userTypeComboBox.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.onKeyPress_ComboBox);
//
// userRightsLabel
//
this.userRightsLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.userRightsLabel.Location = new System.Drawing.Point(12, 95);
this.userRightsLabel.Name = "userRightsLabel";
this.userRightsLabel.Size = new System.Drawing.Size(137, 23);
this.userRightsLabel.TabIndex = 5;
this.userRightsLabel.Text = "Права доступа:";
this.userRightsLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// userRightsComboBox
//
this.userRightsComboBox.FormattingEnabled = true;
this.userRightsComboBox.Items.AddRange(new object[] {
"Чтение",
"Чтение/Запись",
"Чтение/Запись/Редактирование"});
this.userRightsComboBox.Location = new System.Drawing.Point(155, 97);
this.userRightsComboBox.Name = "userRightsComboBox";
this.userRightsComboBox.Size = new System.Drawing.Size(121, 21);
this.userRightsComboBox.TabIndex = 3;
this.userRightsComboBox.SelectedIndexChanged += new System.EventHandler(this.userRights_TextUpdate);
this.userRightsComboBox.TextUpdate += new System.EventHandler(this.userRights_TextUpdate);
this.userRightsComboBox.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.onKeyPress_ComboBox);
//
// userPasswordLabel
//
this.userPasswordLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.userPasswordLabel.Location = new System.Drawing.Point(12, 121);
this.userPasswordLabel.Name = "userPasswordLabel";
this.userPasswordLabel.Size = new System.Drawing.Size(137, 23);
this.userPasswordLabel.TabIndex = 8;
this.userPasswordLabel.Text = "Пароль:";
this.userPasswordLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.userPasswordLabel.Visible = false;
//
// userPasswordTextBox
//
this.userPasswordTextBox.Location = new System.Drawing.Point(155, 124);
this.userPasswordTextBox.Name = "userPasswordTextBox";
this.userPasswordTextBox.Size = new System.Drawing.Size(121, 20);
this.userPasswordTextBox.TabIndex = 4;
this.userPasswordTextBox.Visible = false;
this.userPasswordTextBox.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.onKeyPress_passwordField);
//
// userButton
//
this.userButton.Location = new System.Drawing.Point(155, 159);
this.userButton.Name = "userButton";
this.userButton.Size = new System.Drawing.Size(121, 23);
this.userButton.TabIndex = 5;
this.userButton.Text = "Создать";
this.userButton.UseVisualStyleBackColor = true;
this.userButton.Visible = false;
this.userButton.Click += new System.EventHandler(this.onCreateButton_Click);
//
// userNameLabel
//
this.userNameLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.userNameLabel.Location = new System.Drawing.Point(12, 43);
this.userNameLabel.Name = "userNameLabel";
this.userNameLabel.Size = new System.Drawing.Size(137, 23);
this.userNameLabel.TabIndex = 1;
this.userNameLabel.Text = "Имя пользователя:";
this.userNameLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// userNameTextBox
//
this.userNameTextBox.Location = new System.Drawing.Point(155, 46);
this.userNameTextBox.Name = "userNameTextBox";
this.userNameTextBox.Size = new System.Drawing.Size(121, 20);
this.userNameTextBox.TabIndex = 1;
this.userNameTextBox.TextChanged += new System.EventHandler(this.userName_TextChanged);
//
// userForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(295, 194);
this.Controls.Add(this.userNameTextBox);
this.Controls.Add(this.userNameLabel);
this.Controls.Add(this.userButton);
this.Controls.Add(this.userPasswordTextBox);
this.Controls.Add(this.userPasswordLabel);
this.Controls.Add(this.userRightsComboBox);
this.Controls.Add(this.userRightsLabel);
this.Controls.Add(this.userTypeComboBox);
this.Controls.Add(this.userTypeLabel);
this.Controls.Add(this.userLabel);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "userForm";
this.Text = "Добавление пользователя";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label userLabel;
private System.Windows.Forms.Label userTypeLabel;
private System.Windows.Forms.ComboBox userTypeComboBox;
private System.Windows.Forms.Label userRightsLabel;
private System.Windows.Forms.ComboBox userRightsComboBox;
private System.Windows.Forms.Label userPasswordLabel;
private System.Windows.Forms.TextBox userPasswordTextBox;
private System.Windows.Forms.Button userButton;
private System.Windows.Forms.Label userNameLabel;
private System.Windows.Forms.TextBox userNameTextBox;
}
}
Список использованной литературы.
А. Н. Козин «Структуры и алгоритмы обработки данных» учебно-методическое пособие, 2003.
Эндрю Троелсон «С# и платформа .NET», 2005.