бесплатные рефераты

База даних "Телефонний довідник"

Додаток 1: Вихідний код програми

Головна форма:

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 Phonebook.Classes;

using System.Diagnostics;

using System.IO;

using System.Xml.Linq;

using System.Globalization;

namespace Phonebook

{

public partial class MainForm: Form

{

float FontSize = 10.0f;

public MainForm()

{

InitializeComponent();

}

#region Buttons

void buttonNew_Click(object sender, EventArgs e)

{

try

{

ItemForm newForm = new ItemForm(true, false);

newForm.Font = new Font(this.Font.Name, this.FontSize, this.Font.Style, this.Font.Unit, this.Font.GdiCharSet, this.Font.GdiVerticalFont);

newForm.Text = "Додати новий запис";

newForm.lableRegDate.Text = christianToolStripMenuItem.Checked ? DateTime.Now.ToString(): ConvertToPersianDate(DateTime.Now.ToString());

newForm.ShowDialog();

LoadPhoneBookItems();

int contactsNumbers = Variables.xDocument.Descendants("Item").Where(q => q.Attribute("UserID").Value == Variables.CurrentUserID).Count();

this.Text = Variables.Caption + Variables.CurrentUserName + ": " + contactsNumbers.ToString() + " Contacts";

}

catch (Exception ex)

{

StackFrame file_info = new StackFrame(true);

Messages.error(ref file_info, ex.Message, this);

}

}

void buttonClearSearchTextBox_Click(object sender, EventArgs e)

{

textBoxSearch.Text = "";

LoadPhoneBookItems();

}

void buttonEdit_Click(object sender, EventArgs e)

{

try

{

if (listView1.SelectedItems.Count < 1) return;

string id = listView1.SelectedItems[0].Name.Replace("Item", "");

var item = (from q in Variables.xDocument.Descendants("Item")

where q.Attribute("UserID").Value == Variables.CurrentUserID && q.Attribute("ID").Value == id

select q).First();

if (item == null) return;

ItemForm editForm = new ItemForm(false, true);

editForm.Font = new Font(this.Font.Name, this.FontSize, this.Font.Style, this.Font.Unit, this.Font.GdiCharSet, this.Font.GdiVerticalFont);

editForm.Text = "Edit Item";

editForm.textBoxAddress.Text = item.Attribute("Address").Value;

editForm.textBoxEMail.Text = item.Attribute("Email").Value;

editForm.textBoxMobile.Text = item.Attribute("Mobile").Value;

editForm.textBoxName.Text = item.Attribute("Name").Value;

editForm.textBoxPhone.Text = item.Attribute("Phone").Value;

editForm.lableRegDate.Text = christianToolStripMenuItem.Checked ? item.Attribute("RegDate").Value: ConvertToPersianDate(item.Attribute("RegDate").Value);

editForm.ItemID = id;

editForm.ShowDialog();

LoadPhoneBookItems();

}

catch (Exception ex)

{

StackFrame file_info = new StackFrame(true);

Messages.error(ref file_info, ex.Message, this);

}

}

void buttonDelete_Click(object sender, EventArgs e)

{

try

{

if (listView1.SelectedItems.Count < 1) return;

if (MessageBox.Show("Ви впевнені, що хочете видалити запис,його потім не відновиш?", "Попередження", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No) return;

string id = listView1.SelectedItems[0].Name.Replace("Item", "");

var item = (from q in Variables.xDocument.Descendants("Item")

where q.Attribute("UserID").Value == Variables.CurrentUserID && q.Attribute("ID").Value == id

select q).First();

item.Remove();

TripleDES.EncryptToFile(Variables.xDocument.ToString(SaveOptions.DisableFormatting), Variables.DBFile, TripleDES.ByteKey, TripleDES.IV);

//Variables.xDocument.Save("debug.xml");

LoadPhoneBookItems();

int contactsNumbers = Variables.xDocument.Descendants("Item").Where(q => q.Attribute("UserID").Value == Variables.CurrentUserID).Count();

this.Text = Variables.Caption + Variables.CurrentUserName + ": " + contactsNumbers.ToString() + " Contacts";

}

catch (Exception ex)

{

StackFrame file_info = new StackFrame(true);

Messages.error(ref file_info, ex.Message, this);

}

}

#endregion

#region Menu Strip Events

#region Settings

void rightToLeftToolStripMenuItem_Click(object sender, EventArgs e)

{

try

{

rightToLeftToolStripMenuItem.Checked = true;

leftToRightToolStripMenuItem.Checked = false;

textBoxSearch.RightToLeft = RightToLeft.Yes;

listView1.RightToLeft = RightToLeft.Yes;

var query = (from q in Variables.xDocument.Descendants("Setting")

where q.Attribute("UserID").Value == Variables.CurrentUserID

select q).First();

query.Attribute("RightToLeft").Value = "Yes";

TripleDES.EncryptToFile(Variables.xDocument.ToString(SaveOptions.DisableFormatting), Variables.DBFile, TripleDES.ByteKey, TripleDES.IV);

//Variables.xDocument.Save("debug.xml");

}

catch { }

}

void leftToRightToolStripMenuItem_Click(object sender, EventArgs e)

{

try

{

leftToRightToolStripMenuItem.Checked = true;

rightToLeftToolStripMenuItem.Checked = false;

textBoxSearch.RightToLeft = RightToLeft.No;

listView1.RightToLeft = RightToLeft.No;

var query = (from q in Variables.xDocument.Descendants("Setting")

where q.Attribute("UserID").Value == Variables.CurrentUserID

select q).First();

query.Attribute("RightToLeft").Value = "NO";

TripleDES.EncryptToFile(Variables.xDocument.ToString(SaveOptions.DisableFormatting), Variables.DBFile, TripleDES.ByteKey, TripleDES.IV);

}

catch { }

}

void toolStripMenuItemFontSize_Click(object sender, EventArgs e)

{

try

{

toolStripMenuItemFontSize8.Checked = toolStripMenuItemFontSize10.Checked = toolStripMenuItemFontSize12.Checked = toolStripMenuItemFontSize14.Checked = toolStripMenuItemFontSize16.Checked = toolStripMenuItemFontSize18.Checked = false;

ToolStripMenuItem menuItem = sender as ToolStripMenuItem;

menuItem.Checked = true;

this.FontSize = float.Parse(menuItem.Text.Trim());

if (this.Font.Size!= this.FontSize)

{

this.Font = new Font(this.Font.Name, this.FontSize, this.Font.Style, this.Font.Unit, this.Font.GdiCharSet, this.Font.GdiVerticalFont);

var query = (from q in Variables.xDocument.Descendants("Setting")

where q.Attribute("UserID").Value == Variables.CurrentUserID

select q).First();

query.Attribute("FontSize").Value = this.FontSize.ToString();

TripleDES.EncryptToFile(Variables.xDocument.ToString(SaveOptions.DisableFormatting), Variables.DBFile, TripleDES.ByteKey, TripleDES.IV);

//Variables.xDocument.Save("debug.xml");

}

}

catch { }

}

void christianToolStripMenuItem_Click(object sender, EventArgs e)

{

christianToolStripMenuItem.Checked = true;

persianToolStripMenuItem.Checked = false;

var query = (from q in Variables.xDocument.Descendants("Setting")

where q.Attribute("UserID").Value == Variables.CurrentUserID

select q).First();

query.Attribute("Dates").Value = "Christian";

TripleDES.EncryptToFile(Variables.xDocument.ToString(SaveOptions.DisableFormatting), Variables.DBFile, TripleDES.ByteKey, TripleDES.IV);

//Variables.xDocument.Save("debug.xml");

}

void persianToolStripMenuItem_Click(object sender, EventArgs e)

{

christianToolStripMenuItem.Checked = false;

persianToolStripMenuItem.Checked = true;

var query = (from q in Variables.xDocument.Descendants("Setting")

where q.Attribute("UserID").Value == Variables.CurrentUserID

select q).First();

query.Attribute("Dates").Value = "Persian";

TripleDES.EncryptToFile(Variables.xDocument.ToString(SaveOptions.DisableFormatting), Variables.DBFile, TripleDES.ByteKey, TripleDES.IV);

//Variables.xDocument.Save("debug.xml");

}

#endregion

void exitToolStripMenuItem_Click(object sender, EventArgs e)

{

this.Close();

}

void newUserToolStripMenuItem_Click(object sender, EventArgs e)

{

try

{

UserForm newUserForm = new UserForm(true, false, false);

newUserForm.Font = new Font(this.Font.Name, this.FontSize, this.Font.Style, this.Font.Unit, this.Font.GdiCharSet, this.Font.GdiVerticalFont);

newUserForm.ShowDialog();

ApplySettings();

LoadPhoneBookItems();

if (Variables.CurrentUserName!= "" && Variables.CurrentUserID!= "")

{

int contactsNumbers = Variables.xDocument.Descendants("Item").Where(q => q.Attribute("UserID").Value == Variables.CurrentUserID).Count();

this.Text = Variables.Caption + Variables.CurrentUserName + ": " + contactsNumbers.ToString() + " Contacts";

DisableEnableControls(true);

}

else

DisableEnableControls(false);

}

catch (Exception ex)

{

DisableEnableControls(false);

StackFrame file_info = new StackFrame(true);

Messages.error(ref file_info, ex.Message, this);

}

}

void changeUserToolStripMenuItem_Click(object sender, EventArgs e)

{

try

{

UserForm userForm = new UserForm(false, true, false);

userForm.Font = new Font(this.Font.Name, this.FontSize, this.Font.Style, this.Font.Unit, this.Font.GdiCharSet, this.Font.GdiVerticalFont);

userForm.ShowDialog();

ApplySettings();

LoadPhoneBookItems();

if (Variables.CurrentUserName!= "" && Variables.CurrentUserID!= "")

{

int contactsNumbers = Variables.xDocument.Descendants("Item").Where(q => q.Attribute("UserID").Value == Variables.CurrentUserID).Count();

this.Text = Variables.Caption + Variables.CurrentUserName + ": " + contactsNumbers.ToString() + " Contacts";

DisableEnableControls(true);

}

else

DisableEnableControls(false);

}

catch (Exception ex)

{

DisableEnableControls(false);

StackFrame file_info = new StackFrame(true);

Messages.error(ref file_info, ex.Message, this);

}

}

void changeInfoToolStripMenuItem_Click(object sender, EventArgs e)

{

try

{

UserForm changeInfoForm = new UserForm(false, false, true);

changeInfoForm.Font = new Font(this.Font.Name, this.FontSize, this.Font.Style, this.Font.Unit, this.Font.GdiCharSet, this.Font.GdiVerticalFont);

var userElement = from q in Variables.xDocument.Descendants("User")

where q.Attribute("ID").Value == Variables.CurrentUserID

select q;

string username = userElement.First().Attribute("UserName").Value;

string email = userElement.First().Attribute("Email").Value;

changeInfoForm.textBoxUsername.Text = username;

changeInfoForm.textBoxEmail.Text = email;

changeInfoForm.ShowDialog();

if (Variables.CurrentUserName!= "" && Variables.CurrentUserID!= "")

{

int contactsNumbers = Variables.xDocument.Descendants("Item").Where(q => q.Attribute("UserID").Value == Variables.CurrentUserID).Count();

this.Text = Variables.Caption + Variables.CurrentUserName + ": " + contactsNumbers.ToString() + " Contacts";

DisableEnableControls(true);

}

else

DisableEnableControls(false);

}

catch (Exception ex)

{

DisableEnableControls(false);

StackFrame file_info = new StackFrame(true);

Messages.error(ref file_info, ex.Message, this);

}

}

void aboutProgrammerToolStripMenuItem_Click(object sender, EventArgs e)

{

System.Diagnostics.Process.Start("http://vkontakte.ru/id2688556");

}

#endregion

void LoadPhoneBookItems()

{

try

{

listView1.Items.Clear();

var items = from q in Variables.xDocument.Descendants("Item")

where q.Attribute("UserID").Value == Variables.CurrentUserID

select q;

if (items.Count() < 1)

return;

foreach (var item in items)

{

ListViewItem listViewItems;

if (christianToolStripMenuItem.Checked)

listViewItems = new ListViewItem(new string[]

{ item.Attribute("Name").Value,

item.Attribute("Phone").Value,

item.Attribute("Mobile").Value,

item.Attribute("Email").Value,

item.Attribute("Address").Value,

item.Attribute("RegDate").Value});

else

listViewItems = new ListViewItem(new string[]

{ item.Attribute("Name").Value,

item.Attribute("Phone").Value,

item.Attribute("Mobile").Value,

item.Attribute("Email").Value,

item.Attribute("Address").Value,

ConvertToPersianDate(item.Attribute("RegDate").Value)});

listViewItems.Name = "Item" + item.Attribute("ID").Value;

listView1.Items.Add(listViewItems);

}

}

catch (Exception ex)

{

DisableEnableControls(false);

StackFrame file_info = new StackFrame(true);

Messages.error(ref file_info, ex.Message, this);

}

}

void ApplySettings()

{

try

{

if (Variables.xDocument == null)

{

DisableEnableControls(false);

return;

}

var Settings = (from q in Variables.xDocument.Descendants("Setting")

where q.Attribute("UserID").Value == Variables.CurrentUserID

select q).First();

if (Settings.Attribute("RightToLeft").Value == "Yes")

rightToLeftToolStripMenuItem_Click(null, null);

else

leftToRightToolStripMenuItem_Click(null, null);

if (Settings.Attribute("Dates").Value == "Persian")

{

persianToolStripMenuItem.Checked = true;

christianToolStripMenuItem.Checked = false;

}

else

{

persianToolStripMenuItem.Checked = false;

christianToolStripMenuItem.Checked = true;

}

this.FontSize = float.Parse(Settings.Attribute("FontSize").Value);

this.Font = new Font(this.Font.Name, this.FontSize, this.Font.Style, this.Font.Unit, this.Font.GdiCharSet, this.Font.GdiVerticalFont);

if (this.FontSize == 8)

{

toolStripMenuItemFontSize8.Checked = true;

toolStripMenuItemFontSize10.Checked = false;

toolStripMenuItemFontSize12.Checked = false;

toolStripMenuItemFontSize14.Checked = false;

toolStripMenuItemFontSize16.Checked = false;

toolStripMenuItemFontSize18.Checked = false;

}

else if (this.FontSize == 10)

{

toolStripMenuItemFontSize8.Checked = false;

toolStripMenuItemFontSize10.Checked = true;

toolStripMenuItemFontSize12.Checked = false;

toolStripMenuItemFontSize14.Checked = false;

toolStripMenuItemFontSize16.Checked = false;

toolStripMenuItemFontSize18.Checked = false;

}

else if (this.FontSize == 12)

{

toolStripMenuItemFontSize8.Checked = false;

toolStripMenuItemFontSize10.Checked = false;

toolStripMenuItemFontSize12.Checked = true;

toolStripMenuItemFontSize14.Checked = false;

toolStripMenuItemFontSize16.Checked = false;

toolStripMenuItemFontSize18.Checked = false;

}

else if (this.FontSize == 14)

{

toolStripMenuItemFontSize8.Checked = false;

toolStripMenuItemFontSize10.Checked = false;

toolStripMenuItemFontSize12.Checked = false;

toolStripMenuItemFontSize14.Checked = true;

toolStripMenuItemFontSize16.Checked = false;

toolStripMenuItemFontSize18.Checked = false;

}

else if (this.FontSize == 16)

{

toolStripMenuItemFontSize8.Checked = false;

toolStripMenuItemFontSize10.Checked = false;

toolStripMenuItemFontSize12.Checked = false;

toolStripMenuItemFontSize14.Checked = false;

toolStripMenuItemFontSize16.Checked = true;

toolStripMenuItemFontSize18.Checked = false;

}

else if (this.FontSize == 18)

{

toolStripMenuItemFontSize8.Checked = false;

toolStripMenuItemFontSize10.Checked = false;

toolStripMenuItemFontSize12.Checked = false;

toolStripMenuItemFontSize14.Checked = false;

toolStripMenuItemFontSize16.Checked = false;

toolStripMenuItemFontSize18.Checked = true;

}

}

catch (Exception ex)

{

DisableEnableControls(false);

StackFrame file_info = new StackFrame(true);

Messages.error(ref file_info, ex.Message, this);

}

}

void MainForm_Shown(object sender, EventArgs e)

{

try

{

if (!File.Exists(Variables.DBFile))

{

newUserToolStripMenuItem_Click(null, null);

return;

}

Variables.xDocument = XDocument.Parse(TripleDES.DecryptFromFile(Variables.DBFile, TripleDES.ByteKey, TripleDES.IV));

var users = from q in Variables.xDocument.Descendants("User")

select q;

if (users.Count() < 1)//No user exist

{

newUserToolStripMenuItem_Click(null, null);

return;

}

else//More than one user exist

{

changeUserToolStripMenuItem_Click(null, null);

}

}

catch (Exception ex)

{

DisableEnableControls(false);

StackFrame file_info = new StackFrame(true);

Messages.error(ref file_info, ex.Message, this);

try

{

File.Delete(Variables.DBFile);

}

catch

{

MessageBox.Show("Будь-ласка, видаліть файл бази даних", "Критична помилка", MessageBoxButtons.OK, MessageBoxIcon.Error);

}

}

}

void DisableEnableControls(bool enable)

{

if (enable)

{

changeInfoToolStripMenuItem.Enabled = settingsToolStripMenuItem.Enabled = true;

textBoxSearch.Enabled = listView1.Enabled = true;

buttonNew.Enabled = true;

}

else

{

changeInfoToolStripMenuItem.Enabled = settingsToolStripMenuItem.Enabled = false;

textBoxSearch.Enabled = listView1.Enabled = false;

buttonNew.Enabled = false;

}

}

string ConvertToPersianDate(string stringDate)

{

try

{

DateTime dateTime = DateTime.Parse(stringDate);

PersianCalendar persianCalendar = new PersianCalendar();

var str = persianCalendar.GetYear(dateTime).ToString() + " / " +

persianCalendar.GetMonth(dateTime).ToString() + " / " +

persianCalendar.GetDayOfMonth(dateTime).ToString() + " " +

persianCalendar.GetHour(dateTime).ToString() + ":" +

persianCalendar.GetMinute(dateTime).ToString() + ":" +

persianCalendar.GetSecond(dateTime).ToString();

return str;

}

catch (Exception ex)

{

StackFrame file_info = new StackFrame(true);

Messages.error(ref file_info, ex.Message, this);

return "";

}

}

#region listview

void textBoxSearch_TextChanged(object sender, EventArgs e)

{

try

{

if (textBoxSearch.Text.Trim() == "")

{

LoadPhoneBookItems();

return;

}

listView1.Items.Clear();

var query = from q in Variables.xDocument.Descendants("Item")

where q.Attribute("UserID").Value == Variables.CurrentUserID &&

(q.Attribute("Name").Value.ToLower().Contains(textBoxSearch.Text.Trim().ToLower())

q.Attribute("Phone").Value.ToLower().Contains(textBoxSearch.Text.Trim().ToLower())

q.Attribute("Mobile").Value.ToLower().Contains(textBoxSearch.Text.Trim().ToLower())

q.Attribute("Email").Value.ToLower().Contains(textBoxSearch.Text.Trim().ToLower())

q.Attribute("Address").Value.ToLower().Contains(textBoxSearch.Text.Trim().ToLower()))

select q;

if (query.Count() < 1) return;

foreach (var item in query)

{

ListViewItem listViewItems = new ListViewItem(new string[]

{ item.Attribute("Name").Value,

item.Attribute("Phone").Value,

item.Attribute("Mobile").Value,

item.Attribute("Email").Value,

item.Attribute("Address").Value,

item.Attribute("RegDate").Value});

listViewItems.Name = "Item" + item.Attribute("ID").Value;

listView1.Items.Add(listViewItems);

}

}

catch (Exception ex)

{

StackFrame file_info = new StackFrame(true);

Messages.error(ref file_info, ex.Message, this);

}

}

void listView1_MouseDoubleClick(object sender, MouseEventArgs e)

{

//var item = listView1.GetItemAt(e.X, e.Y);

buttonEdit_Click(null, null);

}

#endregion

}

}

Форма введення запису про абонентів:

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 System.Diagnostics;

using Phonebook.Classes;

using System.Xml.Linq;

using System.IO;

using System.Drawing.Imaging;

namespace Phonebook

{

public partial class ItemForm: Form

{

public string ItemID = "";

bool NewItem = false;

bool EditItem = false;

public ItemForm(bool newItem, bool editItem)

{

InitializeComponent();

this.tableLayoutPanel1.CellPaint += new TableLayoutCellPaintEventHandler(tableLayoutPanel1_CellPaint);

//////////////////////

this.NewItem = newItem;

this.EditItem = editItem;

if (NewItem)

this.Text = "Додати новий запис";

else if (EditItem)

this.Text = "Редагувати запис";

}

void tableLayoutPanel1_CellPaint(object sender, TableLayoutCellPaintEventArgs e)

{

try

{

if (e.Row % 2 == 0)

{

Graphics g = e.Graphics;

Rectangle r = e.CellBounds;

g.FillRectangle(new SolidBrush(Color.FromArgb(225, 225, 225)), r);

}

}

catch (Exception ex)

{

StackFrame file_info = new StackFrame(true);

Messages.error(ref file_info, ex.Message, this);

}

}

private void buttonSubmit_Click(object sender, EventArgs e)

{

try

{

errorProvider1.Clear();

#region add new item

if (NewItem)

{

if (textBoxName.Text.Trim() == "")

{

errorProvider1.SetError(textBoxName, "Будь-ласка, введіть ім'я");

return;

}

int maxID = 0;

try

{

maxID = (from q in Variables.xDocument.Descendants("Item")

where q.Attribute("UserID").Value == Variables.CurrentUserID

select (int)q.Attribute("ID")).Max();

}

catch { }

maxID++;

XElement newItem = new XElement("Item", new XAttribute("ID", maxID),

new XAttribute("UserID", Variables.CurrentUserID),

new XAttribute("Name", textBoxName.Text.Trim()),

new XAttribute("Mobile", textBoxMobile.Text.Trim()),

new XAttribute("Phone", textBoxPhone.Text.Trim()),

new XAttribute("Email", textBoxEMail.Text.Trim()),

new XAttribute("Address", textBoxAddress.Text.Trim()),

new XAttribute("RegDate", DateTime.Now.ToString()));

var ItemsElement = (from q in Variables.xDocument.Descendants("Items")

select q).First();

ItemsElement.Add(newItem);

}

#endregion

#region edit item

else if (EditItem)

{

if (textBoxName.Text.Trim() == "")

{

errorProvider1.SetError(textBoxName, "Будь-ласка, введіть ім'я");

return;

}

var theItem = (from q in Variables.xDocument.Descendants("Item")

where q.Attribute("ID").Value == this.ItemID

select q).First();

theItem.Attribute("Name").Value = textBoxName.Text.Trim();

theItem.Attribute("Mobile").Value = textBoxMobile.Text.Trim();

theItem.Attribute("Phone").Value = textBoxPhone.Text.Trim();

theItem.Attribute("Email").Value = textBoxEMail.Text.Trim();

theItem.Attribute("Address").Value = textBoxAddress.Text.Trim();

}

#endregion

TripleDES.EncryptToFile(Variables.xDocument.ToString(SaveOptions.DisableFormatting), Variables.DBFile, TripleDES.ByteKey, TripleDES.IV);

//Variables.xDocument.Save("debug.xml");

this.Close();

}

catch (Exception ex)

{

StackFrame file_info = new StackFrame(true);

Messages.error(ref file_info, ex.Message, this);

}

}

#region

Image ResizeImage(Image FullsizeImage, int NewWidth, int MaxHeight, bool OnlyResizeIfWider)

{

// Prevent using images internal thumbnail

FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);

FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);

if (OnlyResizeIfWider)

{

if (FullsizeImage.Width <= NewWidth)

{

NewWidth = FullsizeImage.Width;

}

}

int NewHeight = FullsizeImage.Height * NewWidth / FullsizeImage.Width;

if (NewHeight > MaxHeight)

{

// Resize with height instead

NewWidth = FullsizeImage.Width * MaxHeight / FullsizeImage.Height;

NewHeight = MaxHeight;

}

System.Drawing.Image NewImage = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero);

// Clear handle to original file so that we can overwrite it if necessary

FullsizeImage.Dispose();

// Save resized picture

return NewImage;

}

string ImageToBase64String(Image image, ImageFormat format)

{

MemoryStream memory = new MemoryStream();

image.Save(memory, format);

string base64 = Convert.ToBase64String(memory.ToArray());

memory.Close();

return base64;

}

Image ImageFromBase64String(string base64)

{

MemoryStream memory = new MemoryStream(Convert.FromBase64String(base64));

Image result = Image.FromStream(memory);

memory.Close();

return result;

}

#endregion

}

}

Форма користувача:

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 System.IO;

using System.Xml.Linq;

using Phonebook.Classes;

using System.Diagnostics;

using System.Net.Mail;

using System.Net;

namespace Phonebook

{

public partial class UserForm: Form

{

bool NewUser = false;

bool ChangeUser = false;

bool ChangeInfo = false;

public UserForm(bool newUser, bool changeUser, bool changeInfo)

{

InitializeComponent();

/////////////////////

this.NewUser = newUser;

this.ChangeInfo = changeInfo;

this.ChangeUser = changeUser;

if (NewUser)

{

this.Text = "Додати нового користувача";

labelPass1.Text = "Пароль:";

labelPass2.Text = "Підтвердити пароль:";

checkBoxForgetPass.Enabled = false;

}

else if (ChangeUser)

{

this.Text = "Обрати користувача";

labelPass1.Text = "Пароль:";

labelPass2.Text = "Новий пароль:";

labelPass2.Enabled = textBoxPassword2.Enabled = false;

labelEmail.Enabled = textBoxEmail.Enabled = false;

}

else if (ChangeInfo)

{

this.Text = "Змінити інформацію користувача";

labelPass1.Text = "Старий пароль:";

labelPass2.Text = "Новий пароль:";

}

}

private void buttonSubmit_Click(object sender, EventArgs e)

{

try

{

errorProvider1.Clear();

#region Forgets the password

if (checkBoxForgetPass.Enabled && checkBoxForgetPass.Checked)

{

if (textBoxUsername.Text.Trim() == "")

{

errorProvider1.SetError(this.textBoxUsername, "Будь-ласка, введіть ім'я користувача");

textBoxUsername.Focus();

return;

}

errorProvider1.Clear();

var user = Variables.xDocument.Descendants("User").Where(q => q.Attribute("UserName").Value.ToLower() == textBoxUsername.Text.Trim().ToLower());

if (user.Count() < 1)

{

errorProvider1.SetError(this.textBoxUsername, "Таке ім'я користувача відсутнє у базі даних!!!!");

return;

}

string password = user.First().Attribute("Password").Value;

try

{

NetworkCredential loginInfo = new NetworkCredential("username", "password");

MailMessage msg = new MailMessage();

msg.From = new MailAddress("CyberkillerPS@gmail.ru");

msg.To.Add(new MailAddress(user.First().Attribute("Email").Value));

msg.Subject = "Phonebook Password";

msg.Body = "Yours Password = " + password;

msg.IsBodyHtml = true;

SmtpClient client = new SmtpClient("smtp.gmail.ru");

client.EnableSsl = true;

client.UseDefaultCredentials = false;

client.Credentials = loginInfo;

client.Send(msg);

MessageBox.Show("Ваш пароль був відісланий вам на email", "Відправка пароля", MessageBoxButtons.OK, MessageBoxIcon.Information);

}

catch (Exception ex)

{

MessageBox.Show(ex.Message, "Помилка", MessageBoxButtons.OK, MessageBoxIcon.Error);

}

return;

}

#endregion

#region add new user

else if (this.NewUser)

{

if (textBoxUsername.Text.Trim() == "" && textBoxUsername.Enabled)

{

errorProvider1.SetError(this.textBoxUsername, "Будь-ласка, введіть ім'я користувача");

return;

}

else if (textBoxPassword1.Text.Trim() == "" && textBoxPassword1.Enabled)

{

errorProvider1.SetError(this.textBoxPassword1, "Будь-ласка, введіть пароль");

return;

}

else if (textBoxPassword2.Text.Trim() == "" && textBoxPassword2.Enabled)

{

errorProvider1.SetError(this.textBoxPassword2, "Будь-ласка, введіть підтвердження пароля");

return;

}

else if (textBoxPassword2.Text.Trim()!= textBoxPassword1.Text.Trim())

{

errorProvider1.SetError(this.textBoxPassword1, "Ваші паролі повинні співпадати");

errorProvider1.SetError(this.textBoxPassword2, "Ваші паролі повинні співпадати");

return;

}

else if (textBoxEmail.Text.Trim() == "" && textBoxEmail.Enabled)

{

errorProvider1.SetError(this.textBoxEmail, "Будь-ласка, введіть правельний Email");

return;

}

if (!File.Exists(Variables.DBFile))

{

Variables.xDocument = new XDocument(

new XComment("\n Don't edit manually \n"),

new XElement("PhoneBook",

new XElement("Users",

new XElement("User",

new XAttribute("ID", "01"),

new XAttribute("UserName", textBoxUsername.Text.Trim()),

new XAttribute("Password", textBoxPassword1.Text.Trim()),

new XAttribute("Email", textBoxEmail.Text.Trim()),

new XAttribute("RegDate", DateTime.Now.ToString()))),

new XElement("Settings",

new XElement("Setting",

new XAttribute("UserID", "01"),

new XAttribute("RightToLeft", "NO"),

new XAttribute("Dates", "Persian"),

new XAttribute("FontSize", "10"))),

new XElement("Items")));

Variables.CurrentUserID = "01";

}

else

{

Variables.xDocument = XDocument.Parse(TripleDES.DecryptFromFile(Variables.DBFile, TripleDES.ByteKey, TripleDES.IV));

var SameUserQuery = from q in Variables.xDocument.Descendants("User")

where q.Attribute("UserName").Value.ToLower() == textBoxUsername.Text.Trim().ToLower()

select q;

if (SameUserQuery.Count() >= 1)

{

errorProvider1.SetError(this.textBoxUsername, "Таке ім'я користувача вже існує, Будь-ласка, оберіть інше");

return;

}

int maxID = 0;

try

{

maxID = (from q in Variables.xDocument.Descendants("User")

select (int)q.Attribute("ID")).Max();

}

catch { }

maxID++;

Variables.CurrentUserID = maxID.ToString();

XElement xElement = new XElement("User",

new XAttribute("ID", maxID),

new XAttribute("UserName", textBoxUsername.Text.Trim()),

new XAttribute("Password", textBoxPassword1.Text.Trim()),

new XAttribute("Email", textBoxEmail.Text.Trim()),

new XAttribute("RegDate", DateTime.Now.ToString()));

var usersElement = (from q in Variables.xDocument.Descendants("Users")

select q).First();

usersElement.Add(xElement);

xElement = new XElement("Setting",

new XAttribute("UserID", maxID),

new XAttribute("RightToLeft", "NO"),

new XAttribute("Dates", "Persian"),

new XAttribute("FontSize", "10"));

var settingsElement = (from q in Variables.xDocument.Descendants("Settings")

select q).First();

settingsElement.Add(xElement);

}

Variables.CurrentUserName = textBoxUsername.Text.Trim();

TripleDES.EncryptToFile(Variables.xDocument.ToString(SaveOptions.DisableFormatting), Variables.DBFile, TripleDES.ByteKey, TripleDES.IV);

//Variables.xDocument.Save("debug.xml");

}

#endregion

#region change user

else if (this.ChangeUser)

{

if (Variables.xDocument == null)

{

MessageBox.Show("Ваше ім'я користувача та пароль невірні", "Помилка", MessageBoxButtons.OK, MessageBoxIcon.Error);

return;

}

if (textBoxUsername.Text.Trim() == "")

{

errorProvider1.SetError(this.textBoxUsername, "Будь-ласка, введіть ім'я користувача");

return;

}

else if (textBoxPassword1.Text.Trim() == "" && textBoxPassword1.Enabled)

{

errorProvider1.SetError(this.textBoxPassword1, "Будь-ласка, введіть пароль");

return;

}

var query = from q in Variables.xDocument.Descendants("User")

where textBoxUsername.Text.Trim().ToLower() == q.Attribute("UserName").Value.ToLower()

&& textBoxPassword1.Text.Trim().ToLower() == q.Attribute("Password").Value.ToLower()

select q;

if (query.Count() == 1)

{

Variables.CurrentUserID = query.First().Attribute("ID").Value;

Variables.CurrentUserName = textBoxUsername.Text.Trim();

}

else

{

Variables.CurrentUserID = "";

Variables.CurrentUserName = "";

MessageBox.Show("Ваше ім'я користувача та пароль невірні", "Помилка", MessageBoxButtons.OK, MessageBoxIcon.Error);

return;

}

}

#endregion

#region change info

else if (this.ChangeInfo)

{

bool changePassword = true;

if (textBoxUsername.Text.Trim() == "" && textBoxUsername.Enabled)

{

errorProvider1.SetError(this.textBoxUsername, "Ваше ім'я користувача та пароль невірні");

return;

}

else if (textBoxEmail.Text.Trim() == "" && textBoxEmail.Enabled)

{

errorProvider1.SetError(this.textBoxEmail, "Будь-ласка, введіть вірний Email");

return;

}

else if (textBoxPassword1.Text.Trim() == textBoxPassword2.Text.Trim() && textBoxPassword2.Text.Trim() == "")

{

changePassword = false;

}

else if (textBoxPassword1.Text.Trim() == "" && textBoxPassword1.Enabled)

{

errorProvider1.SetError(this.textBoxPassword1, "Будь-ласка, введіть старий пароль");

return;

}

else if (textBoxPassword2.Text.Trim() == "" && textBoxPassword2.Enabled)

{

errorProvider1.SetError(this.textBoxPassword2, "Будь-ласка, введіть новий пароль");

return;

}

errorProvider1.Clear();

var query = (from q in Variables.xDocument.Descendants("User")

where q.Attribute("ID").Value == Variables.CurrentUserID

select q).First();

string oldPassword = query.Attribute("Password").Value;

if (oldPassword.ToLower()!= textBoxPassword1.Text.Trim().ToLower() && changePassword)

{

errorProvider1.SetError(this.textBoxPassword1, "Старий пароль невірний");

return;

}

else if (oldPassword == textBoxPassword1.Text.Trim() && changePassword)

{

query.Attribute("UserName").Value = textBoxUsername.Text.Trim();

query.Attribute("Password").Value = textBoxPassword2.Text.Trim();

query.Attribute("Email").Value = textBoxEmail.Text.Trim();

}

else if (!changePassword)

{

query.Attribute("UserName").Value = textBoxUsername.Text.Trim();

query.Attribute("Email").Value = textBoxEmail.Text.Trim();

}

Variables.CurrentUserID = query.Attribute("ID").Value;

Variables.CurrentUserName = textBoxUsername.Text.Trim();

TripleDES.EncryptToFile(Variables.xDocument.ToString(SaveOptions.DisableFormatting), Variables.DBFile, TripleDES.ByteKey, TripleDES.IV);

//Variables.xDocument.Save("debug.xml");

}

#endregion

this.Close();

}

catch (Exception ex)

{

Variables.CurrentUserID = Variables.CurrentUserName = "";

StackFrame file_info = new StackFrame(true);

Messages.error(ref file_info, ex.Message, this);

}

}

}

}

Додаток 2: Головне вікно програми

Додаток 3: Форма користувача БД

Додаток 4: Форма створення нового запису в БД

Страницы: 1, 2


© 2010 РЕФЕРАТЫ