Browse Source

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

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

54
eCompanies/App.xaml.cs

@ -1,4 +1,5 @@
using System.Collections.Generic; using System;
using System.Collections.Generic;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using System.Data; using System.Data;
using System.Linq; using System.Linq;
@ -11,15 +12,6 @@ namespace eCompanies
/// </summary> /// </summary>
public partial class App : Application public partial class App : Application
{ {
private void addCompany(Company c)
{
using (var db = new CompaniesDBContext())
{
db.Company.Add(c);
var count = db.SaveChanges();
}
}
public static ObservableCollection<Company> getCompanies() public static ObservableCollection<Company> getCompanies()
{ {
using (var db = new CompaniesDBContext()) using (var db = new CompaniesDBContext())
@ -32,6 +24,15 @@ namespace eCompanies
return new HashSet<Users>(db.Users.Where(b => b.CompanyId.Equals(id))); 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);
db.SaveChanges();
}
}
public static void updateCompany(Company c) public static void updateCompany(Company c)
{ {
using (var db = new CompaniesDBContext()) using (var db = new CompaniesDBContext())
@ -41,11 +42,25 @@ namespace eCompanies
} }
} }
public static void removeCompany(Company c) public static void removeCompany(int id)
{
using (var db = new CompaniesDBContext())
{
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(List<int> idList)
{ {
using (var db = new CompaniesDBContext()) using (var db = new CompaniesDBContext())
{ {
db.Company.Remove(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(); db.SaveChanges();
} }
} }
@ -54,11 +69,24 @@ namespace eCompanies
{ {
using (var db = new CompaniesDBContext()) using (var db = new CompaniesDBContext())
{ {
var x = db.Users.Where(s => s.UserId.Equals(id)); var x = db.Users.Where(i => i.UserId.Equals(id));
foreach (Users u in x) db.Users.Remove(u); foreach (Users u in x) db.Users.Remove(u);
db.SaveChanges(); db.SaveChanges();
} }
} }
public static void removeUser(List<int> idList)
{
using (var db = new CompaniesDBContext())
{
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); contract = new Contract(this);
} }
public Contract contract { get; set; } public Contract contract { get; set; }
public int CompanyId { get; set; } public int CompanyId { get; set; }
public string Name { get; set; } public string Name { get; set; }

7
eCompanies/MainWindow.xaml

@ -5,9 +5,10 @@
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:eCompanies" xmlns:local="clr-namespace:eCompanies"
mc:Ignorable="d" mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800"> Title="MainWindow" Height="450" Width="800" Closing="Window_Closing">
<Grid> <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> <DataGrid.Resources>
<ContextMenu x:Key="RowMenu" <ContextMenu x:Key="RowMenu"
DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}"> DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}">
@ -16,7 +17,7 @@
</ContextMenu> </ContextMenu>
</DataGrid.Resources> </DataGrid.Resources>
<DataGrid.RowStyle> <DataGrid.RowStyle>
<Style TargetType="DataGridRow" > <Style TargetType="DataGridRow">
<Setter Property="ContextMenu" Value="{StaticResource RowMenu}" /> <Setter Property="ContextMenu" Value="{StaticResource RowMenu}" />
</Style> </Style>
</DataGrid.RowStyle> </DataGrid.RowStyle>

87
eCompanies/MainWindow.xaml.cs

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

3
eCompanies/UsersWindow.xaml

@ -11,7 +11,8 @@
<ColumnDefinition/> <ColumnDefinition/>
<ColumnDefinition Width="0*"/> <ColumnDefinition Width="0*"/>
</Grid.ColumnDefinitions> </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> <DataGrid.Columns>
<DataGridTextColumn Header="ID" IsReadOnly="True" Binding="{Binding UserId}"/> <DataGridTextColumn Header="ID" IsReadOnly="True" Binding="{Binding UserId}"/>
<DataGridTextColumn Header="Имя пользователя" Width="*" Binding="{Binding Name}" /> <DataGridTextColumn Header="Имя пользователя" Width="*" Binding="{Binding Name}" />

65
eCompanies/UsersWindow.xaml.cs

@ -1,8 +1,8 @@
using System; using System;
using System.Collections.Generic;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using System.Linq; using System.Linq;
using System.Windows; using System.Windows;
using System.Windows.Controls;
using System.Windows.Input; using System.Windows.Input;
namespace eCompanies namespace eCompanies
@ -13,53 +13,80 @@ namespace eCompanies
public partial class UsersWindow : Window public partial class UsersWindow : Window
{ {
Company currentCompany; Company currentCompany;
UpdateCompanyGridDelegate updateCompanyGrid; UpdateCompanyGridDelegate updateCompanyItem;
List<int> deletingUsersList = new List<int>();
public UsersWindow(Company c, UpdateCompanyGridDelegate d) public UsersWindow(Company c, UpdateCompanyGridDelegate d)
{ {
InitializeComponent(); InitializeComponent();
currentCompany = c; currentCompany = c;
updateCompanyGrid = d; updateCompanyItem = d;
updateUsersGrid(); updateUsersGrid(c);
} }
private void updateUsersGrid() private void updateUsersGrid(Company c)
{ {
currentCompany.Users = App.getUsers(currentCompany.CompanyId); companyNameBox.Text = c.Name;
companyNameBox.Text = currentCompany.Name; contractStatusComboBox.SelectedIndex = c.ContractStatus;
contractStatusComboBox.SelectedIndex = currentCompany.ContractStatus; currentCompany.Users = App.getUsers(c.CompanyId);
usersGrid.DataContext = new ObservableCollection<Users>(currentCompany.Users.AsEnumerable()); usersGrid.DataContext = new ObservableCollection<Users>(c.Users.AsEnumerable());
} }
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{ {
MessageBoxResult mbr = MessageBox.Show("Вы закрываете окно с компанией. Хотите сохранить результаты?", "Сохранение изменений", MessageBoxButton.YesNo); MessageBoxResult mbr = MessageBox.Show("Вы закрываете окно с компанией. Хотите сохранить результаты?", "Сохранение изменений", MessageBoxButton.YesNo);
if (mbr == MessageBoxResult.No) if (mbr == MessageBoxResult.No)
return; return;
currentCompany.Users.Clear();
foreach (Users u in (ObservableCollection<Users>)usersGrid.DataContext) 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.CompanyId = currentCompany.CompanyId;
u.Company = currentCompany; u.Company = currentCompany;
currentCompany.Users.Add(u); currentCompany.Users.Add(u);
} }
currentCompany.ContractStatus = contractStatusComboBox.SelectedIndex; currentCompany.ContractStatus = contractStatusComboBox.SelectedIndex;
currentCompany.Name = companyNameBox.Text; currentCompany.Name = companyNameBox.Text;
App.updateCompany(currentCompany); updateCompanyItem(currentCompany);
updateCompanyGrid();
} }
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) private void RowDelete_Click(object sender, RoutedEventArgs e)
{ {
App.removeUser(((Users)usersGrid.CurrentItem).UserId); deleteUserFromGrid();
updateUsersGrid();
} }
} }
} }

2
eCompanies/eCompanies.csproj

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

Loading…
Cancel
Save