Классы для авторизации и перехода с одного гуи в другое.
Этот класс отвечает за соединение с БД
using MySql.Data.MySqlClient;
using System.Security.Principal;namespace Game
{
public static class DbHelper
{
// строка подключения к БД
const string connStr = "server=localhost; user=root; database=gamesql; password=issuria;";public static GameUser GetUser(string login, string password)
{
GameUser user = null;
if (!string.IsNullOrWhiteSpace(login) && !string.IsNullOrWhiteSpace(password))
{
using (MySqlConnection conn = new MySqlConnection(connStr))
{
// запрос
string sql = "SELECT * FROM User WHERE Login=@Login AND Password=@Password";
// объект для выполнения SQL-запроса
MySqlCommand command = new MySqlCommand(sql, conn);
command.Parameters.AddWithValue("@Login", login);
command.Parameters.AddWithValue("@Password", password);// устанавливаем соединение с БД
conn.Open();// объект для чтения ответа сервера
using (MySqlDataReader reader = command.ExecuteReader())
{
// читаем результат
if (reader.Read())
{
//если пароль верный то
user = new GameUser
{
Id = (int)reader["id"],
Login = (string)reader["Login"],
};
}
}
}
}
return user;
}
}
}
Наследование полученных переменных:
using MySql.Data.MySqlClient;
namespace Game
{
public class GameUser
{
public int Id { get; set; }
public string Login { get; set; }
}
}
Класс GUI меню для входа:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Drawing;
using Engine;
using Engine.FileSystem;
using Engine.UISystem;
using Engine.EntitySystem;
using Engine.MapSystem;
using Engine.MathEx;
using Engine.Renderer;
using Engine.SoundSystem;
using System.Net;
using Engine.Networking;
using ProjectCommon;
using ProjectEntities;
using MySql.Data.MySqlClient;
using System.Security.Principal;namespace Game
{
public class MenuSQL : Control
{
//Объявленине
Control window;
static string login;
static string password;
static string id;
EditBox editBoxLogin;
EditBox editBoxPassword;
EditBox editBoxId;
//========================================
enum DrawAreaModes
{
Triangles,
Quads,
Lines,
Text,
}
//protected override void OnAttach()
{
//Вызов родительского метода
base.OnAttach();
window = ControlDeclarationManager.Instance.CreateControl("MyGUI\\Menu.gui");
//==========================================
editBoxLogin = (EditBox)window.Controls[ "Login" ];
editBoxLogin.TextChange += editBoxLogin_TextChange;
//==========================================
editBoxPassword = (EditBox)window.Controls[ "Password" ];
editBoxPassword.TextChange += editBoxPassword_TextChange;
//==========================================
//Загрузка пользовательского интерфейса
//
//пароль
{
EditBox editBox = window.Controls[ "Password" ] as EditBox;
if( editBox != null )
{
//password *
editBox.UpdatingTextControl = delegate( EditBox sender, ref string text )
{
text = new string( '*', sender.Text.Length );
if( sender.Focused )
text += "_";
};
editBox.TextChange += editBoxPassword_TextChange;
}
}
//логин
{
EditBox editBox = window.Controls[ "Login" ] as EditBox;
if( editBox != null )
{
editBox.TextChange += editBoxLogin_TextChange;
}
}//фоновая музыка
GameMusic.MusicPlay( "GameMenu\\Menu.ogg", true );
//Добавление GUI к окну
Controls.Add(window);
//специфика кнопки выхода
if( window.Controls[ "Exit" ] != null )
( (Button)window.Controls[ "Exit" ] ).Click += Exit_Click;
//специфика кнопки конекта к БД
if( window.Controls[ "SQL" ] != null )
( (Button)window.Controls[ "SQL" ] ).Click += Conn_SQL;
}
void editBoxLogin_TextChange( Control sender )
{
login = editBoxLogin.Text.Trim();
Control control = window.Controls[ "Login" ];
if( control != null )
control.Text = sender.Text;
}
void editBoxPassword_TextChange( Control sender )
{
password = editBoxPassword.Text.Trim();
Control control = window.Controls[ "Password" ];
if( control != null )
control.Text = sender.Text;
}
// void editBoxId_TextChange( Control sender )
// {
// id = editBoxId.Text.Trim();
//
// Control control = window.Controls[ "id" ];
// if( control != null )
// control.Text = sender.Text;
// }
//кнопка выхода
void Exit_Click( Button sender )
{
GameEngineApp.Instance.SetFadeOutScreenAndExit();
}
//==================ИНФОРМАЦИЯ
void SetInfo( string text, bool error )
{
TextBox textBoxInfo = (TextBox)window.Controls[ "Info" ];textBoxInfo.Text = text;
textBoxInfo.TextColor = error ? new ColorValue( 1, 0, 0 ) : new ColorValue( 1, 1, 1 );
}
//это кнопка конекта к базе данных
void Conn_SQL(Button sender)
{
GameUser user = DbHelper.GetUser(editBoxLogin.Text, editBoxPassword.Text);
if (user != null)
{
//если пароль верный то открываем новое меню
GameEngineApp.Instance.ControlManager.Controls.Add(new LK(user));
//закрываем предыдущее меню
SetShouldDetach();
}
else
{
SetInfo("Неверный логин или пароль", true);
}
}
}
}
GUI2 получаем результат ID и Имя
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Drawing;
using Engine;
using Engine.FileSystem;
using Engine.UISystem;
using Engine.EntitySystem;
using Engine.MapSystem;
using Engine.MathEx;
using Engine.Renderer;
using Engine.SoundSystem;
using System.Net;
using Engine.Networking;
using ProjectCommon;
using ProjectEntities;
using MySql.Data.MySqlClient;
using System.Security.Principal;namespace Game
{
public class LK : Control
{
GameUser user;public LK(GameUser user)
{
this.user = user;
user.Login = Name;
}
//Объявленине
Control window;
static string Name;
EditBox EditBoxName;
//========================================
enum DrawAreaModes
{
Triangles,
Quads,
Lines,
Text,
}protected override void OnAttach()
{
//Вызов родительского метода
base.OnAttach();
window = ControlDeclarationManager.Instance.CreateControl("MyGUI\\LK.gui");
//фоновая музыка
GameMusic.MusicPlay( "GameMenu\\MenuLK.ogg", true );
//Добавление GUI к окну
Controls.Add(window);}
//==================Информация об ошибках или что то не верно
void SetInfoError( string text, bool error )
{
TextBox textBoxInfo = (TextBox)window.Controls[ "InfoERROR" ];
textBoxInfo.Text = text;
textBoxInfo.TextColor = error ? new ColorValue( 1, 0, 0 ) : new ColorValue( 1, 1, 1 );
}
}
}