Диплом: Автоматизация управления персоналом ТОО "КАЗЦИНК ТЕМИР-ТРАНС"

Внимание! Если размещение файла нарушает Ваши авторские права, то обязательно сообщите нам
132
Продолжение приложения 3
{
if (FamilyCollect == null)
FamilyCollect = new ObservableCollection<Family>();
FamilyCollect.Add(new Family
{
Id = 0,
WorkerId = (GWin.DataContext as Model.WorkersPartial).Id,
DegreeOfRelatednessId =
(int)win.CbDegreeOfRelatedness.SelectedValue,
Surname = win.TxtSurname.Text,
Name = win.TxtName.Text,
Patronymic = win.TxtPatronymic.Text,
DateOfBirth = win.DpDateOfBirth.SelectedDate.Value
});
}
}
}
private void BntEdit_Click(object sender, RoutedEventArgs e)
{
int index;
if (DgFamily.SelectedIndex == -1)
{
MessageBox.Show("Не выбрана ни одна запись", "Вопрос",
MessageBoxButton.OK, MessageBoxImage.Warning);
DgFamily.Focus();
return;
}
else
index = DgFamily.SelectedIndex;
if (FamilyCollect != null && FamilyCollect.Count > 0)
{
Family family = FamilyCollect[index];
FamilyBox win = new FamilyBox
{
Owner = this
};
win.CbDegreeOfRelatedness.SelectedValue = family.DegreeOfRelatednessId;
win.TxtSurname.Text = family.Surname;
win.TxtName.Text = family.Name;
win.TxtPatronymic.Text = family.Patronymic;
win.DpDateOfBirth.SelectedDate = family.DateOfBirth;
if (win.ShowDialog().Value)
{
family.DegreeOfRelatednessId =
(int)win.CbDegreeOfRelatedness.SelectedValue;
family.Surname = win.TxtSurname.Text;
family.Name = win.TxtName.Text;
family.Patronymic = win.TxtPatronymic.Text;
family.DateOfBirth = win.DpDateOfBirth.SelectedDate.Value;
DgFamily.Items.Refresh();
}
}
}
private async void BntDelete_Click(object sender, RoutedEventArgs e)
{
int index;
int id;
if (DgFamily.SelectedIndex == -1)
{
MessageBox.Show("Не выбрана ни одна запись", "Вопрос",
MessageBoxButton.OK, MessageBoxImage.Warning);
DgFamily.Focus();
133
Продолжение приложения 3
return;
}
else
index = DgFamily.SelectedIndex;
switch (MessageBox.Show("Удаление может привести к каскадному удалению
данных. Вы уверены что хотите удалить запись?",
"Вопрос", MessageBoxButton.YesNo, MessageBoxImage.Question))
{
case MessageBoxResult.Yes:
bool b = true;
System.Data.SqlClient.SqlException exc;
id = FamilyCollect[index].Id;
if (id != 0)
{
if (_familyRepository == null)
_familyRepository = new FamilyRepository(_db);
try
{
b = await _familyRepository.DeleteAsync(id);
}
catch (Exception ex)
{
b = false;
if (ex.GetType() ==
typeof(System.Data.Entity.Infrastructure.DbUpdateException))
{
while (!(ex is System.Data.SqlClient.SqlException) &&
ex.InnerException != null)
ex = ex.InnerException;
if (ex is System.Data.SqlClient.SqlException)
{
exc = ex as System.Data.SqlClient.SqlException;
if (exc.Number == 547)
MessageBox.Show("Нельзя удалить эту запись, с
начало нужно удалить связанные с ней записи",
"Ошибка", MessageBoxButton.OK,
MessageBoxImage.Error);
else
MessageBox.Show("Ошибка базы данных", "Ошибка",
MessageBoxButton.OK, MessageBoxImage.Error);
}
else
MessageBox.Show("Ошибка базы данных", "Ошибка",
MessageBoxButton.OK, MessageBoxImage.Error);
}
else
MessageBox.Show("Ошибка базы данных", "Ошибка",
MessageBoxButton.OK, MessageBoxImage.Error);
}
if (b)
{
FamilyCollect.RemoveAt(index);
}
}
else
{
FamilyCollect.RemoveAt(index);
}
break;
case MessageBoxResult.No:
default:
break;
134
Продолжение приложения 3
}
}
private void CreateButton_Click(object sender, RoutedEventArgs e)
{ }
private void CbFamilyStatus_SelectionChanged(object sender,
SelectionChangedEventArgs e)
{
if (CbFamilyStatus.IsDropDownOpen)
{
if (CbFamilyStatus.SelectedIndex < 2)
FamilyCollect.Clear();
}
}
internal void SetImage(Stream stream)
{
if (stream == null)
{
MessageBox.Show("Ошибка сохранения изображения", "Ошибка",
MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
BitmapImage bmp = new BitmapImage();
try
{
bmp.BeginInit();
bmp.StreamSource = stream;
bmp.CacheOption = BitmapCacheOption.OnLoad;
bmp.EndInit();
ImgWorker.Source = bmp;
}
catch
{
MessageBox.Show("Ошибка сохранения изображения", "Ошибка",
MessageBoxButton.OK, MessageBoxImage.Error);
}
finally
{
if (stream != null)
{
stream.Close();
stream.Dispose();
}
}
}
private async Task SetDataContext(Model.WorkersPartial workersPartial)
{
if (workersPartial != null)
{
GWin.DataContext = workersPartial;
if (workersPartial.Id != 0)
{
GEducation.DataContext = await
_db.DiplomInfs.FindAsync(workersPartial.Id);
GMilitaries.DataContext = await
_db.MilitaryDuties.FindAsync(workersPartial.Id);
if (GMilitaries.DataContext != null)
CbMilitaryRank.SelectedValue =
((MilitaryDuties)GMilitaries.DataContext).MilitaryRankId;
if (FamilyCollect == null)
FamilyCollect = new
ObservableCollection<Family>(workersPartial.Families);
else
135
Продолжение приложения 3
{
FamilyCollect.Clear();
foreach (var item in workersPartial.Families)
FamilyCollect.Add(item);
}
}
else
{
GEducation.DataContext = null;
GMilitaries.DataContext = null;
if (FamilyCollect != null)
FamilyCollect.Clear();
}
NadExperience.Value = workersPartial.Experience;
NadVacation.Value = workersPartial.Vacation;
if (!String.IsNullOrEmpty(workersPartial.Sex))
{
for (int i = 0; i < CbSex.Items.Count; i++)
{
if ((string)((ComboBoxItem)CbSex.Items[i]).Content ==
workersPartial.Sex)
{
CbSex.SelectedIndex = i;
break;
}
}
}
else
CbSex.SelectedIndex = -1;
if (!String.IsNullOrEmpty(workersPartial.FamilyStatus))
{
for (int i = 0; i < CbFamilyStatus.Items.Count; i++)
{
if ((string)((ComboBoxItem)CbFamilyStatus.Items[i]).Content ==
workersPartial.FamilyStatus)
{
CbFamilyStatus.SelectedIndex = i;
break;
}
}
}
else
CbFamilyStatus.SelectedIndex = -1;
if (workersPartial.Foto != null && workersPartial.Foto.Length > 0)
{
BitmapImage bmp = new BitmapImage();
using (MemoryStream ms = new MemoryStream(workersPartial.Foto))
{
try
{
bmp.BeginInit();
bmp.StreamSource = ms;
bmp.CacheOption = BitmapCacheOption.OnLoad;
bmp.EndInit();
ImgWorker.Source = bmp;
}
catch
{
MessageBox.Show("Ошибка сохранения изображения", "Ошибка",
MessageBoxButton.OK, MessageBoxImage.Error);
}
136
Продолжение приложения 3
}
}
else
ImgWorker.Source = foto;
}
else
{
GWin.DataContext = null;
GMilitaries.DataContext = null;
GEducation.DataContext = null;
CbSex.SelectedIndex = -1;
CbMilitaryRank.SelectedIndex = -1;
CbFamilyStatus.SelectedIndex = -1;
CbProfession.SelectedIndex = -1;
ImgWorker.Source = foto;
}
}
private async Task<Model.WorkersPartial> GetWorkersPartial(int index)
{
Model.WorkersPartial res = null;
if (index > -1)
{
if (_dictionary.Count > 0)
res = _dictionary.Where(x => x.Key == index).Select(x =>
x.Value).FirstOrDefault();
if (res == null)
{
res = await _workersRepository.Items.Include(x =>
x.Dismissals).Where(x => x.SweatshopId == sweatshopId && x.Dismissals.Dismissing ==
"Принят")
.OrderBy(x => x.Id).Skip(index).Take(1).Select(x => new
Model.WorkersPartial
{
Id = x.Id,
DocumentId = x.DocumentId,
ProfessionId = x.ProfessionId,
NationalityId = x.NationalityId,
CitizenshipId = x.CitizenshipId,
DepartmentId = x.DepartmentId,
EducationId = x.EducationId,
MilitaryId = x.MilitaryId,
DismissingId = x.DismissingId,
SweatshopId = x.SweatshopId,
Surname = x.Surname,
Name = x.Name,
Patronymic = x.Patronymic,
Sex = x.Sex,
Age = x.Age,
FamilyStatus = x.FamilyStatus,
DateOfBirth = x.DateOfBirth,
DocumentNambe = x.DocumentNambe,
IIN = x.IIN,
DateOfIssue = x.DateOfIssue,
Address = x.Address,
Rank = x.Rank,
Proficiency = x.Proficiency,
Foto = x.Foto,
Phone = x.Phone,
MPhone = x.MPhone,
DeviceDate = x.DeviceDate,
TrialPeriod = x.TrialPeriod,
Experience = x.Experience,
137
Продолжение приложения 3
Vacation = x.Vacation,
Ecology = x.Ecology,
PersonnelNumber = x.PersonnelNumber,
Families = x.Families
}).FirstOrDefaultAsync();
if (res != null)
_dictionary.Add(myNavigator.Index, res);
}
}
return res;
}
public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj)
where T : DependencyObject
{
if (depObj != null)
{
int count = VisualTreeHelper.GetChildrenCount(depObj);
for (int i = 0; i < count; i++)
{
var child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
yield return (T)child;
foreach (T current in FindVisualChildren<T>(child))
yield return current;
}
}
}
internal bool IsFamilyEyas(int hash)
{
return FamilyCollect.Where(x => (x.DegreeOfRelatednessId.GetHashCode() +
x.Surname.GetHashCode() + x.Name.GetHashCode() + x.Patronymic.GetHashCode()
+ x.DateOfBirth.GetHashCode()) == hash).Any();
}
private async Task<bool> SaveData()
{
bool res = false;
if (GWin.DataContext != null)
{
Model.WorkersPartial workersPartial =
(Model.WorkersPartial)GWin.DataContext;
workersPartial.SweatshopId = sweatshopId;
workersPartial.Sex = (string)((ComboBoxItem)CbSex.SelectedItem).Content;
workersPartial.FamilyStatus =
(string)((ComboBoxItem)CbFamilyStatus.SelectedItem).Content;
if (CbFamilyStatus.SelectedIndex > 1)
{
if (FamilyCollect != null && FamilyCollect.Count > 0)
{
foreach (var item in FamilyCollect)
workersPartial.Families.Add(item);
}
else
workersPartial.Families.Clear();
}
if (ImgWorker.Source is BitmapImage)
{
BitmapImage bmp = ImgWorker.Source as BitmapImage;
try
{
byte[] bFoto = Helper.Helper.ImageToByte(bmp);
if (!foto.IsEquals(bFoto))
workersPartial.Foto = bFoto;
138
Окончание приложения 3
}
catch { }
}
if (_dismissalsRepository == null)
_dismissalsRepository = new DismissalsRepository(_db);
workersPartial.DismissingId = await _dismissalsRepository.Items.Where(x
=> x.Dismissing == "Принят").Select(x => x.Id).FirstAsync();
Model.ProfessionsAndRolesPartial professionsAndRolesPartial =
(Model.ProfessionsAndRolesPartial)CbProfession.SelectedItem;
foreach (Roles role in
((Model.ProfessionsAndRolesPartial)CbProfession.SelectedItem).Roles)
workersPartial.Roles.Add(role);
using (DbContextTransaction transaction =
_db.Database.BeginTransaction())
{
try
{
int id = await
_workersRepository.SaveItemPartialAsync(workersPartial);
if (id != 0)
{
if (GMilitaries.DataContext != null)
{
if
(((Model.Display)CbMilitaries.SelectedItem).DisplayPatch != "Невоеннообязанный")
{
MilitaryDuties militaryDuties =
(MilitaryDuties)GMilitaries.DataContext;
if (militaryDuties.Id == 0)
militaryDuties.Id = id;
await
_militaryDutiesRepository.SaveItemAsync(militaryDuties);
}
}
if (GEducation.DataContext != null)
{
if
(((Model.Display)CbEducation.SelectedItem).DisplayPatch != "Среднее")
{
DiplomInf diplomInf =
(DiplomInf)GEducation.DataContext;
if (diplomInf.Id == 0)
diplomInf.Id = id;
await _diplomInfRepository.SaveItemAsync(diplomInf);
}
}
transaction.Commit();
res = true;
}
}
catch
{
transaction.Rollback();
res = false;
}
}
}
return res;
}

Смотрите также:

"Автоматизация обработки заявок ООО "Проектно-Строительная Компания"
"Автоматизация процесса аттестации персонала для ООО "Нэт Бай Нэт Холдинг"
"Анализ интернет-активности конкурентов ( на примере конкурентов "Газпром нефть")
"Бухгалтерский учёт и аудит расчётов с подотчётними лицами в организации на примере ООО "ЛОЦ 10""
«Психологическое сопровождение персонала в организации на примере ООО «Крокус»
Cовершенствование деловой оценки персонала в организации (на примере ООО "Даймонд кейтеринг развитие")
IPO - инструмент финансирования деятельности организации. На примере ПАО «Нефтяная компания «Лукойл»
PR как средство продвижения организации (на примере ПАО "Тамбовский завод "Комсомолец им. Н.С. Артемова")
PR-коммуникации в сфере общественного питания (на примере кафе-кондитерской «Cream Cheese»)
SMM как средство повышения эффективности работы учреждений социокультурной сферы (на примере Малого театра)