Лапина 23Б отчет
.pdfthis.Text = row[DisplayValues].ToString();
}
}
///<summary>
///Записывает в строку редактирования данные из TextBox
///</summary>
///<param name="row">строка редактирования</param> public void SetValue(DataRow row)
{
row[DisplayValues] = this.Text; //throw new NotImplementedException();
}
#endregion
///<summary>
///Проверяет правильно ли заполнен компонент
///</summary>
///<returns>Возвращает значение типа bool, показывающее правильно ли заполнен компонент или нет. </returns>
public bool CorrectFilling()
{
return !string.IsNullOrEmpty(this.Text);
}
}
класс InterfaceDB
public interface InterfaceDB
{
string DisplayValues { get; set; }
void GetValue(DataRow row); void SetValue(DataRow row); bool CorrectFilling();
}
SQLConnect: Нужен для получения данных с сервера.
Чтобы получить строку подключения, необходимо на панели управления в меню «Данные» выбрать пункт «Добавить новый источник данных…».
В окне «Мастер настройки источника данных» выбрать источник данных «База данных».
Далее выбрать тип «Набор данных», «Создать подключение…» появившемся окне выбрать источник данных «SQL Server», нажать кнопку «Продолжить».
В появившемся окне, выбрать необходимое имя сервера и в разделе «Подключение к базе данных» выбрать необходимую базу данных, нажать кнопку «Дополнительно» и, в появившемся окне, скопировать строку подключения в поле
using System;
using System.Collections.Generic; using System.Linq;
using System.Text;
using System.Data.SqlClient;
namespace Proekt.SQL
{
public static class SQLConnect
{
//static SqlConnection newConnect;
public static SqlConnection _connect = new SqlConnection("Data Source=PINGWIN-PC;Initial Catalog=Infiniti-service;Integrated Security=True");
public static SqlConnection GetConnect()
{
return _connect;
}
internal static SqlConnection I()
{
throw new NotImplementedException();
}
internal static SqlConnection Infiniti()
{
throw new NotImplementedException();
}
}
}
Класс SQLCommandor: предназначен для обмена данных с помощью передачи имени хранимых процедур и параметров.
using System;
using System.Collections.Generic; using System.Linq;
using System.Text;
using System.Data.SqlClient; using System.Data;
namespace Proekt.SQL
{
public static class SQLCommandor
{
static SqlCommand _cmd = new SqlCommand();
public static DataTable SelectData(string CommandText, CommandType Type, params SqlParameter [] values)
{
SqlCommand command = new SqlCommand(); command.CommandType = Type; command.CommandText = CommandText; command.Connection = SQLConnect.GetConnect(); foreach (SqlParameter param in values)
{
command.Parameters.Add(param);
}
return SelectData(command);
}
public static DataTable SelectData(SqlCommand _Command) { DataTable tbl = new DataTable();
SqlDataAdapter _adapter = new SqlDataAdapter(); _adapter.SelectCommand = _Command; _adapter.Fill(tbl);
return tbl;
}
public static void ExecuteCommand(SqlCommand _Command)
{
if (_Command.Connection.State != ConnectionState.Open)
{
_Command.Connection.Open();
}
_Command.ExecuteNonQuery();
}
public static void ExecuteCommand(string CommandText, CommandType Type, params SqlParameter[] values)
{
SqlCommand command = new SqlCommand(); command.CommandType = Type; command.CommandText = CommandText; command.Connection = SQLConnect.Infiniti(); foreach (SqlParameter param in values)
{
command.Parameters.Add(param);
}
ExecuteCommand(command);
}
public static void AddRow(string TableName, DataRow Row)
{
GenericCommand("SPU_"+TableName+"_ADD", Row);
}
public static void EditRow(string TableName, DataRow Row)
{
GenericCommand("SPU_" + TableName + "_EDIT", Row);
}
public static void DelRow(string TableName, DataRow Row)
{
GenericCommand("SPU_" + TableName + "_DEL", Row);
}
private static DataTable SelectParamStoredProcedure(string StoredProcedureName)
{
return SelectData("SELECTEDPARAM", CommandType.StoredProcedure, new SqlParameter ("@StoredProcedureName",StoredProcedureName));
}
private static void GenericCommand(string StoredProcedurName, DataRow Row)
{
SqlCommand cmd = new SqlCommand(); cmd.Connection = SQLConnect.GetConnect(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = StoredProcedurName.ToUpper();
DataTable Params = SelectParamStoredProcedure(StoredProcedurName); foreach (DataRow _param in Params.Rows)
{
cmd.Parameters.Add(new SqlParameter(_param["PARAMETER_NAME"].ToString(), Row[_param["PARAMETER_NAME"].ToString().Replace("@", "").Trim()]));
}
ExecuteCommand(cmd);
}
}
}
Класс Access: помогает разграничить доступ к базе, путем блокировки кнопок (по правам доступа).
using System;
using System.Collections.Generic; using System.Linq;
using System.Text; using System.Data;
using System.Windows.Forms; using Proekt.Controls;
namespace Proekt
{
public static class Access
{
//todo:Убрать после написания переменные public enum UsersType { Ghost, Admin, Seller };
static public bool Add = true, Edit = true, Delete = true;
// static int UserId;
public static string login = string.Empty;
static public void SetAccess(DataRow row)
{
Add = (bool)row["Post_Access1"]; Edit = (bool)row["Post_Access2"]; Delete = (bool)row["Post_Access3"];
}
static public UsersType GetAccess()
{
int i = 0; if (Add)
{i++; } if (Edit)
{i++; } if (Delete)
{i++; }
if (i > 2)
{
return UsersType.Admin;
}
if ((i <= 2) && (i > 0))
{
return UsersType.Seller;
}
return UsersType.Ghost;
}
static public void GetAccess(Form CurrentForm)
{
foreach (Control component in CurrentForm.Controls)
{
if (component is ButtonAccess)
{
if (((ButtonAccess)component).AccessName == ButtonAccess.Type.Add)
{
((ButtonAccess)component).Enabled = Add;
}
if (((ButtonAccess)component).AccessName == ButtonAccess.Type.Del)
{
((ButtonAccess)component).Enabled = Delete;
}
if (((ButtonAccess)component).AccessName == ButtonAccess.Type.Edit)
{
((ButtonAccess)component).Enabled = Edit;
}
}
}
}
}
}
Создание форм
Форма — это объект базы данных, который можно использовать для ввода, изменения или отображения данных из таблицы или запроса. Формы могут применяться для управления доступом к данным: с их помощью можно определять, какие поля или строки данных будут отображаться. Формы можно рассматривать как окна, через которые пользователи могут просматривать и изменять базу данных.
Форма создается в Microsoft Visual Studio с помощью «Панели элементов»
1. На форму добавляются элементы в данном случае мы создаем форму «авторизации» и нам понадобиться: textBox, label, groupBox
2. Затем прописывается код, необходимый для работы этих элементов.
using System;
using System.Collections.Generic; using System.ComponentModel; using System.Windows.Forms; using System.Drawing;
using System.Linq; using System.Text; using System.Data;
using System.Data.SqlClient; using Proekt.SQL;
namespace Proekt
{
public partial class Autorisation : Form
{
public Main MF; public Autorisation()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(textBoxLogin.Text))
{
if (!String.IsNullOrEmpty(textBoxPassword.Text))
{
SqlCommand _cmd = new SqlCommand();
_cmd.CommandType = System.Data.CommandType.StoredProcedure; ; _cmd.Connection = SQLConnect.GetConnect();
_cmd.CommandText = "SPU_Login_SEL"; _cmd.Parameters.Add("@Login_Login", textBoxLogin.Text); _cmd.Parameters.Add("@Password_Password", textBoxPassword.Text);
SqlDataAdapter adap = new SqlDataAdapter(); adap.SelectCommand = _cmd;
DataTable tbl = new DataTable(); adap.Fill(tbl);
if (tbl.Rows.Count != 0)
{
Access.SetAccess(tbl.Rows[0]); Access.login = textBoxLogin.ToString();
MessageBox.Show("Вход под логином: " + textBoxLogin.Text);
MF = new Main(); this.Visible = false; MF.ShowDialog();
}
else
{
MessageBox.Show("Ошибка");
}
}
else
{
MessageBox.Show("Введите Пароль");
}
}
else
{
MessageBox.Show("Введите Логин");
}
}
public void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void Autorisation_Load(object sender, EventArgs e)
{
}
}
}
Создания формы меню
Для основной формы меню (где в выпадающих вкладках будут наши основные формы, права доступа и справочники) используем элемент menuStrip
В коде мы прописываем права доступа по группам, все основные формы и справочники:
namespace Proekt
{
public partial class Main : Form
{
public Main()
{
InitializeComponent();
}
private void Main_Load(object sender, EventArgs e)
{
настройкиToolStripMenuItem1.Visible = true; добавитьНовогоПользователяToolStripMenuItem1.Visible = true; изменитьПраваДоступаToolStripMenuItem1.Visible = true;
if (Access.GetAccess() == Access.UsersType.Admin)
{
добавитьНовогоПользователяToolStripMenuItem1.Visible = true; изменитьПраваДоступаToolStripMenuItem1.Visible = true;
}
if (Access.GetAccess() == Access.UsersType.Ghost)
{
настройкиToolStripMenuItem1.Visible = false;
}
if (Access.GetAccess() == Access.UsersType.Seller)
{
добавитьНовогоПользователяToolStripMenuItem1.Visible = false; изменитьПраваДоступаToolStripMenuItem1.Visible = false;
}
}
private void районыToolStripMenuItem_Click(object sender, EventArgs e)
{
SprDistrict sprDis = new SprDistrict(); sprDis.Show();
}
private void типУлицToolStripMenuItem_Click(object sender, EventArgs e)
{
StreetSign StS = new StreetSign(); StS.Show();
}
private void модельToolStripMenuItem_Click(object sender, EventArgs e)
{
SprModel SprMod = new SprModel(); SprMod.Show();
}
private void типКузоваToolStripMenuItem_Click(object sender, EventArgs e)
{
SprType SprTyp = new SprType(); SprTyp.Show();
}
private void улициToolStripMenuItem_Click(object sender, EventArgs e)
{
SprStreet SprStr = new SprStreet(); SprStr.Show();
}
private void начальствоToolStripMenuItem_Click(object sender, EventArgs e)
{
SprChief SprChf = new SprChief(); SprChf.Show();
}
private void изменитьПраваДоступаToolStripMenuItem1_Click(object sender, EventArgs e)
{
Post Pr = new Post(); Pr.Show();
}
private void сменаПользователяToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Restart();
Autorisation aut = new Autorisation(); aut.Show();
}
private void выходToolStripMenuItem1_Click(object sender, EventArgs e)
{
Environment.Exit(0);
}
private void добавитьНовогоПользователяToolStripMenuItem1_Click(object sender, EventArgs e)
{
User AU = new User(); AU.Show();
}
private void автомобилиToolStripMenuItem_Click(object sender, EventArgs e)
{
Avto Av = new Avto(); Av.Show();
}
private void филиалыToolStripMenuItem_Click(object sender, EventArgs e)
{