Browse Source

Почти вся логика обновления данных в БД изменена таким образом, чтобы сначала юзер изменял данные в окне, и только после завершения работы с окном, данные обновлялись в БД. И немножко рефакторинга Сompanies -> Company

master
Никита 6 years ago
parent
commit
99c347109a
  1. 52
      eCompanies/App.xaml.cs
  2. 1
      eCompanies/Company.cs
  3. 5
      eCompanies/MainWindow.xaml
  4. 81
      eCompanies/MainWindow.xaml.cs
  5. 3
      eCompanies/UsersWindow.xaml
  6. 63
      eCompanies/UsersWindow.xaml.cs
  7. 2
      eCompanies/eCompanies.csproj

52
eCompanies/App.xaml.cs

@ -1,4 +1,5 @@
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Linq;
@ -11,51 +12,78 @@ namespace eCompanies
/// </summary>
public partial class App : Application
{
public static ObservableCollection<Company> getCompanies()
{
using (var db = new CompaniesDBContext())
return new ObservableCollection<Company>(db.Company.AsEnumerable());
}
public static HashSet<Users> getUsers(int id)
{
using (var db = new CompaniesDBContext())
return new HashSet<Users>(db.Users.Where(b => b.CompanyId.Equals(id)));
}
private void addCompany(Company c)
{
using (var db = new CompaniesDBContext())
{
db.Company.Add(c);
var count = db.SaveChanges();
db.SaveChanges();
}
}
public static ObservableCollection<Company> getCompanies()
public static void updateCompany(Company c)
{
using (var db = new CompaniesDBContext())
return new ObservableCollection<Company>(db.Company.AsEnumerable());
{
db.Company.Update(c);
db.SaveChanges();
}
}
public static HashSet<Users> getUsers(int id)
public static void removeCompany(int id)
{
using (var db = new CompaniesDBContext())
return new HashSet<Users>(db.Users.Where(b => b.CompanyId.Equals(id)));
{
var x = db.Company.Where(i => i.CompanyId.Equals(id));
foreach (Company c in x) db.Company.Remove(c);
db.SaveChanges();
}
}
public static void updateCompany(Company c)
public static void removeCompany(List<int> idList)
{
using (var db = new CompaniesDBContext())
{
db.Company.Update(c);
foreach (int id in idList)
{
var x = db.Company.Where(i => i.CompanyId.Equals(id));
foreach (Company c in x) db.Company.Remove(c);
}
db.SaveChanges();
}
}
public static void removeCompany(Company c)
public static void removeUser(int id)
{
using (var db = new CompaniesDBContext())
{
db.Company.Remove(c);
var x = db.Users.Where(i => i.UserId.Equals(id));
foreach (Users u in x) db.Users.Remove(u);
db.SaveChanges();
}
}
public static void removeUser(int id)
public static void removeUser(List<int> idList)
{
using (var db = new CompaniesDBContext())
{
var x = db.Users.Where(s => s.UserId.Equals(id));
foreach (int id in idList)
{
var x = db.Users.Where(i => i.UserId.Equals(id));
foreach (Users u in x) db.Users.Remove(u);
}
db.SaveChanges();
}
}

1
eCompanies/Companies.cs → eCompanies/Company.cs

@ -11,7 +11,6 @@ namespace eCompanies
contract = new Contract(this);
}
public Contract contract { get; set; }
public int CompanyId { get; set; }
public string Name { get; set; }

5
eCompanies/MainWindow.xaml

@ -5,9 +5,10 @@
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:eCompanies"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
Title="MainWindow" Height="450" Width="800" Closing="Window_Closing">
<Grid>
<DataGrid x:Name="companyGrid" HorizontalAlignment="Left" Height="399" Margin="10,10,0,0" VerticalAlignment="Top" Width="772" ItemsSource="{Binding}" AutoGenerateColumns="False">
<DataGrid x:Name="companyGrid" HorizontalAlignment="Left" Height="399" Margin="10,10,0,0" VerticalAlignment="Top"
Width="772" ItemsSource="{Binding}" AutoGenerateColumns="False">
<DataGrid.Resources>
<ContextMenu x:Key="RowMenu"
DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}">

81
eCompanies/MainWindow.xaml.cs

@ -19,42 +19,97 @@ namespace eCompanies
/// <summary>
/// Логика взаимодействия для MainWindow.xaml
/// </summary>
public delegate void UpdateCompanyGridDelegate();
public delegate void UpdateCompanyGridDelegate(Company updatingCompany);
public partial class MainWindow : Window
{
List<int> deletingCompanyList = new List<int>();
List<int> updatingCompanyList = new List<int>();
UsersWindow usersWindowInstance = null;
public MainWindow()
{
InitializeComponent();
updateCompanyGrid();
companyGrid.DataContext = App.getCompanies();
}
private void updateCompanyGrid()
private void updateCompanyItem(Company updatingCompany)
{
companyGrid.DataContext = App.getCompanies();
if (updatingCompany == null) return;
updatingCompanyList.Add(updatingCompany.CompanyId);
var context = ((ObservableCollection<Company>)companyGrid.DataContext).ToList<Company>();
for (int i = 0; i < context.Count; i++)
{
if (context[i].CompanyId.Equals(updatingCompany.CompanyId))
{
context[i] = updatingCompany;
companyGrid.DataContext = new ObservableCollection<Company>(context);
updatingCompanyList.Add(updatingCompany.CompanyId);
return;
}
}
}
private void RowEdit_Click(object sender, RoutedEventArgs e)
{
try
{
UpdateCompanyGridDelegate d = updateCompanyGrid;
UpdateCompanyGridDelegate d = updateCompanyItem;
Company company = (Company)companyGrid.CurrentItem;
if (usersWindowInstance != null) usersWindowInstance.Close();
usersWindowInstance = new UsersWindow(company, d);
usersWindowInstance.Show();
}
catch { }
}
private void RowDelete_Click(object sender, RoutedEventArgs e)
{
try
deleteCompanyFromGrid();
}
private void deleteCompanyFromGrid()
{
Company company = (Company)companyGrid.CurrentItem;
App.removeCompany(company);
var companies = (ObservableCollection<Company>)companyGrid.DataContext;
foreach (Company c in companies)
{
int deletingUser = ((Company)companyGrid.CurrentItem).CompanyId;
if (Equals(c.CompanyId, deletingUser))
{
deletingCompanyList.Add(((Company)companyGrid.CurrentItem).CompanyId);
companies.Remove(c);
companyGrid.DataContext = companies;
return;
}
catch { }
}
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
MessageBoxResult mbr = MessageBox.Show("Вы закрываете приложение. Хотите сохранить результаты?", "Сохранение изменений", MessageBoxButton.YesNo);
if (mbr == MessageBoxResult.No)
return;
foreach (Company c in (ObservableCollection<Company>)companyGrid.DataContext)
{
if (c.Name == null)
{
mbr = MessageBox.Show("Вы не заполнили поле [Название компании]! " +
"Вернуться к форме для исправления? (При ответе Нет все данные будут потеряны!)",
"Поле [Название компании] не может быть пустым!",
MessageBoxButton.YesNo);
if (mbr == MessageBoxResult.Yes)
{
e.Cancel = true;
return;
}
else if (mbr == MessageBoxResult.No)
return;
}
if (deletingCompanyList != null)
App.removeCompany(deletingCompanyList);
deletingCompanyList = null;
// TODO: реализация обновления старых компаний и добавления новых
}
}
}
}

3
eCompanies/UsersWindow.xaml

@ -11,7 +11,8 @@
<ColumnDefinition/>
<ColumnDefinition Width="0*"/>
</Grid.ColumnDefinitions>
<DataGrid x:Name="usersGrid" HorizontalAlignment="Left" Height="354" Margin="10,55,0,0" VerticalAlignment="Top" Width="772" ItemsSource="{Binding}" AutoGenerateColumns="False" RowEditEnding="usersGrid_RowEditEnding" AddingNewItem="usersGrid_AddingNewItem">
<DataGrid x:Name="usersGrid" HorizontalAlignment="Left" Height="354" Margin="10,55,0,0" VerticalAlignment="Top"
Width="772" ItemsSource="{Binding}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="ID" IsReadOnly="True" Binding="{Binding UserId}"/>
<DataGridTextColumn Header="Имя пользователя" Width="*" Binding="{Binding Name}" />

63
eCompanies/UsersWindow.xaml.cs

@ -1,8 +1,8 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace eCompanies
@ -13,53 +13,80 @@ namespace eCompanies
public partial class UsersWindow : Window
{
Company currentCompany;
UpdateCompanyGridDelegate updateCompanyGrid;
UpdateCompanyGridDelegate updateCompanyItem;
List<int> deletingUsersList = new List<int>();
public UsersWindow(Company c, UpdateCompanyGridDelegate d)
{
InitializeComponent();
currentCompany = c;
updateCompanyGrid = d;
updateUsersGrid();
updateCompanyItem = d;
updateUsersGrid(c);
}
private void updateUsersGrid()
private void updateUsersGrid(Company c)
{
currentCompany.Users = App.getUsers(currentCompany.CompanyId);
companyNameBox.Text = currentCompany.Name;
contractStatusComboBox.SelectedIndex = currentCompany.ContractStatus;
usersGrid.DataContext = new ObservableCollection<Users>(currentCompany.Users.AsEnumerable());
companyNameBox.Text = c.Name;
contractStatusComboBox.SelectedIndex = c.ContractStatus;
currentCompany.Users = App.getUsers(c.CompanyId);
usersGrid.DataContext = new ObservableCollection<Users>(c.Users.AsEnumerable());
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
MessageBoxResult mbr = MessageBox.Show("Вы закрываете окно с компанией. Хотите сохранить результаты?", "Сохранение изменений", MessageBoxButton.YesNo);
if (mbr == MessageBoxResult.No)
return;
currentCompany.Users.Clear();
foreach (Users u in (ObservableCollection<Users>)usersGrid.DataContext)
{
if (u.Login == null || u.Password == null || u.Name == null)
{
mbr = MessageBox.Show("Вы не полностью заполнили поле одного из пользователей! " +
"Вернуться к форме для исправления? (При ответе Нет все данные будут потеряны!)",
"Поле Логин/Пароль не может быть пустым!",
MessageBoxButton.YesNo);
if (mbr == MessageBoxResult.Yes)
{
e.Cancel = true;
return;
} else if (mbr == MessageBoxResult.No)
return;
}
if (deletingUsersList != null)
App.removeUser(deletingUsersList);
u.CompanyId = currentCompany.CompanyId;
u.Company = currentCompany;
currentCompany.Users.Add(u);
}
currentCompany.ContractStatus = contractStatusComboBox.SelectedIndex;
currentCompany.Name = companyNameBox.Text;
App.updateCompany(currentCompany);
updateCompanyGrid();
updateCompanyItem(currentCompany);
}
private void usersGrid_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
private void deleteUserFromGrid()
{
}
private void usersGrid_AddingNewItem(object sender, AddingNewItemEventArgs e)
var users = (ObservableCollection<Users>)usersGrid.DataContext;
foreach (Users u in users)
{
int deletingUser = ((Users)usersGrid.CurrentItem).UserId;
if (Equals(u.UserId, deletingUser))
{
deletingUsersList.Add(((Users)usersGrid.CurrentItem).UserId);
users.Remove(u);
usersGrid.DataContext = users;
return;
}
}
}
private void RowDelete_Click(object sender, RoutedEventArgs e)
{
App.removeUser(((Users)usersGrid.CurrentItem).UserId);
updateUsersGrid();
deleteUserFromGrid();
}
}
}

2
eCompanies/eCompanies.csproj

@ -154,7 +154,7 @@
<DependentUpon>App.xaml</DependentUpon>
<SubType>Code</SubType>
</Compile>
<Compile Include="Companies.cs" />
<Compile Include="Company.cs" />
<Compile Include="MainWindow.xaml.cs">
<DependentUpon>MainWindow.xaml</DependentUpon>
<SubType>Code</SubType>

Loading…
Cancel
Save