ConnectSqlWpfNuget.Package
1.0.11
dotnet add package ConnectSqlWpfNuget.Package --version 1.0.11
NuGet\Install-Package ConnectSqlWpfNuget.Package -Version 1.0.11
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="ConnectSqlWpfNuget.Package" Version="1.0.11" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="ConnectSqlWpfNuget.Package" Version="1.0.11" />
<PackageReference Include="ConnectSqlWpfNuget.Package" />
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add ConnectSqlWpfNuget.Package --version 1.0.11
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
#r "nuget: ConnectSqlWpfNuget.Package, 1.0.11"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package ConnectSqlWpfNuget.Package@1.0.11
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=ConnectSqlWpfNuget.Package&version=1.0.11
#tool nuget:?package=ConnectSqlWpfNuget.Package&version=1.0.11
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
//////////
Процедура ПередЗаписью(Отказ)
СсылкаПользователя = Справочники.Пользователи.НайтиПоНаименованию(ЭтотОбъект.Наименование, Истина);
Если НЕ СсылкаПользователя.Пустая() И СсылкаПользователя <> ЭтотОбъект.Ссылка Тогда
Отказ = Истина;
Сообщить("Пользователь с таким именем уже существует");
КонецЕсли;
КонецПроцедуры
/////////////////
&НаСервере
функция ВойтиНаСервере()
ПользовательНайден = Справочники.Пользователи.ПустаяСсылка();
Если НЕ Справочники.Пользователи.НайтиПоНаименованию(Логин, Истина).Пустая() Тогда
ПользовательНайден = Справочники.Пользователи.НайтиПоНаименованию(Логин, Истина).Ссылка;
Если ПользовательНайден.Пароль = Пароль Тогда
Если НЕ ПользовательНайден.ДатаВхода = Дата("01.01.001 0:00:00") Тогда
Если ТекущаяДата()>ДобавитьМесяц(НачалоМесяца(ПользовательНайден.ДатаВхода),1)Тогда
ИзменитьДанныеНаСервере(ПользовательНайден,"Активность",Ложь);
Сообщить("Вы заблокированы , Обратитесь к администратору");
КонецЕсли;
КонецЕсли;
Возврат ПользовательНайден.Роль;
Иначе
УстановитьКоличествоПопыток(ПользовательНайден);
Возврат Неопределено;
КонецЕсли;
Иначе
Возврат Неопределено;
КонецЕсли;
Конецфункции
&НаКлиенте
Процедура Войти(Команда)
Роль = ВойтиНаСервере();
Если НЕ Роль = Неопределено Тогда
Если АктивностьПользователя(ПользовательНайден) = Истина Тогда
ИзменитьданныеНаСервере(ПользовательНайден,"КоличествоПопыток",0);
Если ВходПользователя(ПользовательНайден) = Дата ("01.01.001 0:00:00") Тогда
Открытьформу("ОбщаяФорма.ФормаСменыПароля", Новый Структура("ПараметрПользователь", ПользовательНайден));
Сообщить("Изменить пароль при первом входе");
Иначе
ИзменитьДанныеНаСервере(ПользовательНайден,"ДатаВхода",ТекущаяДата());
Если Роль = ПредопределенноеЗначение("Перечисление.Роли.Пользователь") Тогда
Открытьформу("ОбщаяФорма.ФормаПользователя");
Сообщить("Вы успешно авторизовались");
КонецЕсли;
Если Роль = ПредопределенноеЗначение("Перечисление.Роли.Администратор") Тогда
Открытьформу("Справочник.Пользователи.ФормаСписка");
Сообщить("Вы успешно авторизовались");
КонецЕсли;
КонецЕсли;
Этаформа.Закрыть();
Иначе
ИзменитьДанныеНаСервере(ПользовательНайден,"Активность",Ложь);
Сообщить("Вы заблокированы , Обратитесь к администратору");
КонецЕсли;
Иначе
Если (ПопыткиПользователя(ПользовательНайден)>3) Тогда
ИзменитьДанныеНаСервере(ПользовательНайден,"Активность",Ложь);
Сообщить("Вы заблокированы , Обратитесь к администратору");
Иначе
Сообщить("Вы ввели неверный лоигн или пароль");
КонецЕсли;
КонецЕсли;
КонецПроцедуры
&НаСервере
функция АктивностьПользователя(ПользовательНайден)
Возврат ПользовательНайден.Активность;
Конецфункции
&НаСервере
функция ПопыткиПользователя(ПользовательНайден)
Возврат ПользовательНайден.КоличествоПопыток;
Конецфункции
&НаСервере
функция ВходПользователя(ПользовательНайден)
Возврат ПользовательНайден.ДатаВхода;
Конецфункции
&НаСервере
Процедура ИзменитьДанныеНаСервере(Пользователь, ИмяРеквизита, ЗначениеРеквизита)
ПользовательОбъект = Пользователь.ПолучитьОбъект();
ПользовательОбъект[ИмяРеквизита]=ЗначениеРеквизита;
ПользовательОбъект.Записать();
КонецПроцедуры
&НаСервере
Процедура УстановитьКоличествоПопыток(Пользователь)
ПользовательОбъект = Пользователь.ПолучитьОбъект();
ПользовательОбъект.КоличествоПопыток = ПользовательОбъект.КоличествоПопыток+1;
ПользовательОбъект.Записать();
КонецПроцедуры
//////////////////
&НаСервере
функция ИзменитьПарольНаСервере()
Если ТекущийПароль = Параметры.ПараметрПользователь.Пароль И НовыйПароль = ПодтверждениеНовогоПароля Тогда
ПользовательОбъект = Параметры.ПараметрПользователь.ПолучитьОбъект();
ПользовательОбъект.Пароль = НовыйПароль;
ПользовательОбъект.ДатаВхода = ТекущаяДата();
ПользовательОбъект.Записать();
Возврат Истина
Иначе
Сообщить("Пароли не совпадают!");
Возврат Ложь
КонецЕсли;
Конецфункции
&НаКлиенте
Процедура ИзменитьПароль(Команда)
Если ИзменитьПарольНаСервере() = Истина Тогда
Если Роль = ПредопределенноеЗначение("Перечисление.Роли.Пользователь") Тогда
Открытьформу("ОбщаяФорма.ФормаПользователя");
Сообщить("Вы успешно авторизовались");
КонецЕсли;
Если Роль = ПредопределенноеЗначение("Перечисление.Роли.Администратор") Тогда
Открытьформу("Справочник.Пользователи.ФормаСписка");
Сообщить("Вы успешно авторизовались");
КонецЕсли;
Этаформа.Закрыть();
КонецЕсли;
КонецПроцедуры
&НаСервере
Процедура ПриОткрытииНаСервере()
Роль = Параметры.ПараметрПользователь.Роль;
КонецПроцедуры
&НаКлиенте
Процедура ПриОткрытии(Отказ)
ПриОткрытииНаСервере();
КонецПроцедуры
DemoContext
using demo.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
namespace demo.Data;
public partial class DemoContext : DbContext
{
public DemoContext()
{
Database.EnsureCreated();
}
public DemoContext(DbContextOptions<DemoContext> options)
: base(options)
{
}
public virtual DbSet<Category> Categories { get; set; }
public virtual DbSet<Manufacturer> Manufacturers { get; set; }
public virtual DbSet<Order> Orders { get; set; }
public virtual DbSet<OrderArticle> OrderArticles { get; set; }
public virtual DbSet<PickupPoint> PickupPoints { get; set; }
public virtual DbSet<Product> Products { get; set; }
public virtual DbSet<ProductName> ProductNames { get; set; }
public virtual DbSet<Role> Roles { get; set; }
public virtual DbSet<Status> Statuses { get; set; }
public virtual DbSet<Supplier> Suppliers { get; set; }
public virtual DbSet<User> Users { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder.UseSqlServer("Data Source=DESKTOP-18MSOBJ;Initial Catalog=dem3;Integrated Security=True;Connect Timeout=30;Encrypt=True;Trust Server Certificate=True;Application Intent=ReadWrite;Multi Subnet Failover=False");
}
Models
Category.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace demo.Models;
public class Category
{
[Key]
public int Id { get; set; }
public string? Name { get; set; }
public ICollection<Product> Products { get; set; }
}
Manufacturer.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace demo.Models;
public class Category
{
[Key]
public int Id { get; set; }
public string? Name { get; set; }
public ICollection<Product> Products { get; set; }
}
Order.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace demo.Models;
public class Order
{
[Key]
public int Id { get; set; }
public double? Number { get; set; }
public DateTime? OrderDate { get; set; }
public DateTime? DeliveryDate { get; set; }
[ForeignKey("PickupPointId")]
public int? PickupPointId { get; set; }
[ForeignKey("UserId")]
public int? UserId { get; set; }
public double? Code { get; set; }
[ForeignKey("StatusId")]
public int? StatusId { get; set; }
public ICollection<OrderArticle> OrderArticles { get; set; }
public PickupPoint? PickupPoint { get; set; }
public Status? Status { get; set; }
public User? User { get; set; }
}
OrderArticle.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace demo.Models;
public class OrderArticle
{
[Key]
public int Id { get; set; }
[ForeignKey("OrderId")]
public int? OrderId { get; set; }
public double? Count { get; set; }
[ForeignKey("ProductId")]
public int? ProductId { get; set; }
public Order? Order { get; set; }
public Product? Product { get; set; }
}
PickupPoint.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace demo.Models;
public class PickupPoint
{
[Key]
public int Id { get; set; }
public string? Adress { get; set; }
public ICollection<Order> Orders { get; set; }
}
Product.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace demo.Models;
public class Product
{
[Key]
public int Id { get; set; }
public string? Article { get; set; }
[ForeignKey("ProductNameId")]
public int? ProductNameId { get; set; }
public string? Unit { get; set; }
public double? Price { get; set; }
[ForeignKey("SupplierId")]
public int? SupplierId { get; set; }
[ForeignKey("ManufacturerId")]
public int? ManufacturerId { get; set; }
[ForeignKey("Catуgory")]
public int? CategoryId { get; set; }
public double? Discount { get; set; }
public double? Count { get; set; }
public string? Description { get; set; }
public string? ImagePath { get; set; }
public Category? Category { get; set; }
public Manufacturer? Manufacturer { get; set; }
public ProductName? ProductName { get; set; }
public ICollection<OrderArticle> OrderArticles { get; set; }
public Supplier? Supplier { get; set; }
}
ProductName.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace demo.Models;
public class ProductName
{
[Key]
public int Id { get; set; }
public string? Name { get; set; }
public ICollection<Product> Products { get; set; }
}
Role.cs
using System.ComponentModel.DataAnnotations;
namespace demo.Models;
public class Role
{
[Key]
public int Id { get; set; }
public string? Name { get; set; }
public ICollection<User> Users { get; set; }
}
Status.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace demo.Models;
public partial class Status
{
[Key]
public int Id { get; set; }
public string? Name { get; set; }
public ICollection<Order> Orders { get; set; }
}
Supplier.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace demo.Models;
public class Supplier
{
[Key]
public int Id { get; set; }
public string? Name { get; set; }
public ICollection<Product> Products { get; set; }
}
User.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace demo.Models;
public class User
{
[Key]
public int Id { get; set; }
public string? FullName { get; set; }
public string? Login { get; set; }
public string? Password { get; set; }
[ForeignKey("RoleId")]
public int? RoleId { get; set; }
public ICollection<Order> Orders { get; set; }
public Role? Role { get; set; }
}
UserControllers
ItemProduct.xaml
<UserControl x:Class="demo.UserControllers.ItemProduct"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:demo.UserControllers"
mc:Ignorable="d"
d:DesignHeight="200" d:DesignWidth="1200"
Background="White">
<DockPanel>
<Border BorderBrush="Black" BorderThickness="1" Background="White">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="300"/>
<ColumnDefinition Width="600"/>
<ColumnDefinition Width="300"/>
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="0">
<Border BorderBrush="Black" BorderThickness="1" Name="BoxDiscount">
<TextBlock HorizontalAlignment="Center" FontSize="16" >
<Run Text="Скидка"/>
<Run Text="{Binding Discount}"/>
<Run Text="%"/>
</TextBlock>
</Border>
<TextBlock FontSize="16">
<Run Text="{Binding ProductName.Name}"/>
<Run Text="|"/>
<Run Text="{Binding Category.Name}"/>
</TextBlock>
<TextBlock FontSize="16">
<Run Text="Производитель:"/>
<Run Text="{Binding Manufacturer.Name}"/>
</TextBlock>
<TextBlock FontSize="16">
<Run Text="Поставщик"/>
<Run Text="{Binding Supplier.Name}"/>
</TextBlock>
<TextBlock FontSize="16" Name="BoxCount">
<Run Text="Количество на складе:"/>
<Run Text="{Binding Count}"/>
</TextBlock>
<TextBlock FontSize="16" TextWrapping="Wrap">
<Run Text="Описание:"/>
<Run Text="{Binding Description}"/>
</TextBlock>
</StackPanel>
<StackPanel Grid.Column="2">
<Border BorderBrush="Black" BorderThickness="1">
<TextBlock HorizontalAlignment="Center" FontSize="16">
<Run Text="Цена:"/>
<Run Text="{Binding Price}" Name="BoxPrice"/>
<Run Name="NewPrice"/>
</TextBlock>
</Border>
<Border Margin="0 5 0 0">
<Image Width="300" Height="200" Name="BoxImage"/>
</Border>
</StackPanel>
</Grid>
</Border>
</DockPanel>
</UserControl>
ItemProduct.xaml.cs
using demo.Data;
using demo.Models;
using Microsoft.EntityFrameworkCore;
using System.IO;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace demo.UserControllers
{
public partial class ItemProduct : UserControl
{
private string projPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
public double discount { get; set; } = 0;
public Product Product { get; set; }
public ItemProduct(Product product)
{
InitializeComponent();
using (var db = new DemoContext())
{
Product = db.Products
.Include(e => e.Manufacturer)
.Include(e => e.Supplier)
.Include(e => e.Category)
.Include(e => e.ProductName)
.FirstOrDefault(e => e.Id == product.Id);
}
DataContext = Product;
string path = product.ImagePath == null ? Path.Combine(projPath, "Images", "Defaults", "picture.png") : Path.Combine(projPath, "Images", product.ImagePath);
Uri uri = new Uri(path);
try
{
BitmapImage bitmap = new(uri);
BoxImage.Source = bitmap;
}
catch (Exception ex)//любая ошибка с изобращением
{
Console.WriteLine(ex.Message);
BitmapImage bitmap = new(new Uri(Path.Combine(projPath, "Images", "Defaults", "picture.png")));
BoxImage.Source = bitmap;
}
if (product.Discount >= 15)
{
BoxDiscount.Background = new BrushConverter().ConvertFrom("#2E8B57") as SolidColorBrush;
}
if (product.Discount > 0)
{
BoxPrice.Foreground = Brushes.Red;
BoxPrice.TextDecorations.Add(TextDecorations.Strikethrough);
NewPrice.Text = (product.Price * (1 - product.Discount / 100.0)).ToString();
}
if (product.Count == 0)
{
BoxCount.Foreground = Brushes.Blue;
}
}
}
}
Windows
Products
AddProduct.xaml
<Window x:Class="demo.Windows.Products.AddProduct"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:demo.Windows.Products"
WindowStartupLocation="CenterScreen"
mc:Ignorable="d"
Title="Добавление продукта" Height="450" Width="800">
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center"
Orientation="Horizontal">
<StackPanel>
<StackPanel Orientation="Horizontal"
Margin="5">
<TextBox Width="120"
Name="BoxName"/>
<Label Content="Название"/>
</StackPanel>
<StackPanel Orientation="Horizontal"
Margin="5">
<ComboBox Width="120"
Name="BoxCategory"
SelectedIndex="0"
DisplayMemberPath="Name"/>
<Label Content="Категория товара"/>
</StackPanel>
<StackPanel Orientation="Horizontal"
Margin="5">
<TextBox Width="120"
Name="BoxDescription"/>
<Label Content="Описание"/>
</StackPanel>
<StackPanel Orientation="Horizontal"
Margin="5">
<ComboBox Width="120"
Name="BoxManufacturer"
SelectedIndex="0"
DisplayMemberPath="Name"/>
<Label Content="Производитель"/>
</StackPanel>
<StackPanel Orientation="Horizontal"
Margin="5">
<ComboBox Width="120"
Name="BoxSupplier"
SelectedIndex="0"
DisplayMemberPath="Name"/>
<Label Content="Поставщик"/>
</StackPanel>
<StackPanel Orientation="Horizontal"
Margin="5">
<TextBox Width="120"
Name="BoxPrice"/>
<Label Content="Цена"/>
</StackPanel>
<StackPanel Orientation="Horizontal"
Margin="5">
<TextBox Width="120"
Name="BoxUnit"/>
<Label Content="единица измерения,"/>
</StackPanel>
<StackPanel Orientation="Horizontal"
Margin="5">
<TextBox Width="120"
Name="BoxCount"/>
<Label Content="количество на складе"/>
</StackPanel>
<StackPanel Orientation="Horizontal"
Margin="5">
<TextBox Width="120"
Name="BoxDiscount"/>
<Label Content="скидка"/>
</StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
<Button Content=" Добавить продукт "
Click="ButtonAddProduct"
Margin="5"/>
<Button Content="Отмена"
Click="ButtonExit"
Margin="5"/>
</StackPanel>
</StackPanel>
<StackPanel>
<Image Name="BoxImage" Height="200" Width="200"/>
<Button Content="добавить изображение" Margin="5"
Click="ButtonLoadImage"/>
</StackPanel>
</StackPanel>
</Window>
AddProduct.xaml.cs
using demo.Data;
using demo.Models;
using Microsoft.Win32;
using System.IO;
using System.Reflection;
using System.Windows;
using System.Windows.Media.Imaging;
namespace demo.Windows.Products
{
public partial class AddProduct : Window
{
private readonly string projPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
private string? imageName = null;
private BitmapImage selectImage;
private DemoContext context;
public AddProduct()
{
InitializeComponent();
context = new DemoContext();
selectImage = new BitmapImage(new Uri(Path.Combine(projPath, "Images", "Defaults", "picture.png")));
BoxImage.Source = selectImage;
BoxCategory.ItemsSource = context.Categories.ToList();
BoxManufacturer.ItemsSource = context.Manufacturers.ToList();
BoxSupplier.ItemsSource = context.Suppliers.ToList();
}
private void ButtonAddProduct(object sender, RoutedEventArgs e)
{
if (string.IsNullOrWhiteSpace(BoxDescription.Text) ||
string.IsNullOrWhiteSpace(BoxDiscount.Text) ||
string.IsNullOrWhiteSpace(BoxName.Text) ||
string.IsNullOrWhiteSpace(BoxPrice.Text) ||
string.IsNullOrWhiteSpace(BoxUnit.Text))
{
MessageBox.Show("Заполните все поля");
return;
}
try
{
double price = double.Parse(BoxPrice.Text);
double count = double.Parse(BoxCount.Text);
double discount = double.Parse(BoxDiscount.Text);
// Проверка на отрицательные значения
if (price < 0)
{
MessageBox.Show("Цена не может быть отрицательной");
return;
}
if (count < 0)
{
MessageBox.Show("Количество не может быть отрицательным");
return;
}
if (discount < 0)
{
MessageBox.Show("Скидка не может быть отрицательной");
return;
}
if (discount > 100)
{
MessageBox.Show("Скидка не может превышать 100%");
return;
}
var name = context.ProductNames.FirstOrDefault(q => q.Name == BoxName.Text);
if (name == null)
{
context.ProductNames.Add(new ProductName() { Name = BoxName.Text });
context.SaveChanges();
name = context.ProductNames.FirstOrDefault(q => q.Name == BoxName.Text);
}
Product newProduct = new Product()
{
ProductName = name,
CategoryId = ((Category)BoxCategory.SelectedItem).Id,
Description = BoxDescription.Text,
ManufacturerId = ((Manufacturer)BoxManufacturer.SelectedItem).Id,
SupplierId = ((Supplier)BoxSupplier.SelectedItem).Id,
Price = price,
Unit = BoxUnit.Text,
Count = count,
Discount = discount,
ImagePath = imageName,
};
context.Products.Add(newProduct);
context.SaveChanges();
DialogResult = true;
}
catch (FormatException)
{
MessageBox.Show("Пожалуйста, введите корректные числовые значения в поля Цена, Количество и Скидка");
}
catch (Exception ex)
{
MessageBox.Show($"Ошибка: {ex.Message}");
}
}
private void ButtonExit(object sender, RoutedEventArgs e)
{
DialogResult = false;
}
private void ButtonLoadImage(object sender, RoutedEventArgs e)
{
OpenFileDialog openFile = new OpenFileDialog();
if (openFile.ShowDialog() == true)
{
Uri uri = new Uri(openFile.FileName);
BitmapImage select = new(uri);
//if (select.Width > 400 || select.Height > 300)
//{
// MessageBox.Show("Размеры изображения имеют не верный формат");
// return;
//}
selectImage = select;
imageName = openFile.SafeFileName;
BoxImage.Source = selectImage;
}
}
}
}
EditProduct.xaml
<Window x:Class="demo.Windows.Products.EditProduct"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:demo.Windows.Products"
WindowStartupLocation="CenterScreen"
mc:Ignorable="d"
Title="Изменение продукта" Height="450" Width="800">
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center"
Orientation="Horizontal">
<StackPanel>
<StackPanel Orientation="Horizontal"
Margin="5">
<TextBox Width="120"
Name="BoxName"/>
<Label Content="Название"/>
</StackPanel>
<StackPanel Orientation="Horizontal"
Margin="5">
<ComboBox Width="120"
Name="BoxCategory"
SelectedIndex="0"
DisplayMemberPath="Name"/>
<Label Content="Категория товара"/>
</StackPanel>
<StackPanel Orientation="Horizontal"
Margin="5">
<TextBox Width="120"
Name="BoxDescription"/>
<Label Content="Описание"/>
</StackPanel>
<StackPanel Orientation="Horizontal"
Margin="5">
<ComboBox Width="120"
Name="BoxManufacturer"
SelectedIndex="0"
DisplayMemberPath="Name"/>
<Label Content="Производитель"/>
</StackPanel>
<StackPanel Orientation="Horizontal"
Margin="5">
<ComboBox Width="120"
Name="BoxSupplier"
SelectedIndex="0"
DisplayMemberPath="Name"/>
<Label Content="Поставщик"/>
</StackPanel>
<StackPanel Orientation="Horizontal"
Margin="5">
<TextBox Width="120"
Name="BoxPrice"/>
<Label Content="Цена"/>
</StackPanel>
<StackPanel Orientation="Horizontal"
Margin="5">
<TextBox Width="120"
Name="BoxUnit"/>
<Label Content="единица измерения,"/>
</StackPanel>
<StackPanel Orientation="Horizontal"
Margin="5">
<TextBox Width="120"
Name="BoxCount"/>
<Label Content="количество на складе"/>
</StackPanel>
<StackPanel Orientation="Horizontal"
Margin="5">
<TextBox Width="120"
Name="BoxDiscount"/>
<Label Content="скидка"/>
</StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
<Button Content=" Сохранить изменения "
Click="ButtonSaveProduct"
Margin="5"/>
<Button Content="Отмена"
Click="ButtonExit"
Margin="5"/>
</StackPanel>
</StackPanel>
<StackPanel>
<Image Name="BoxImage" Height="200" Width="200"/>
<Button Content="Изменить изображение" Margin="5"
Click="ButtonLoadImage"/>
</StackPanel>
</StackPanel>
</Window>
EditProduct.xaml.cs
using demo.Data;
using demo.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Win32;
using System.IO;
using System.Reflection;
using System.Windows;
using System.Windows.Media.Imaging;
namespace demo.Windows.Products
{
public partial class EditProduct : Window
{
private readonly string projPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
DemoContext context;
private Product product;
private BitmapImage selectImage;
private string? imageName = null;
public EditProduct(Product product)
{
InitializeComponent();
context = new DemoContext();
//Добавииииить
this.product = context.Products
.Include(p => p.Category)
.Include(p => p.Manufacturer)
.Include(p => p.Supplier)
.Include(p => p.ProductName)
.FirstOrDefault(p => p.Id == product.Id);
Load();
}
private void Load()
{
BoxCategory.ItemsSource = context.Categories.ToList();
BoxCategory.SelectedItem = product.Category;
BoxSupplier.ItemsSource = context.Suppliers.ToList();
BoxSupplier.SelectedItem = product.Supplier;
BoxManufacturer.ItemsSource = context.Manufacturers.ToList();
BoxManufacturer.SelectedItem = product.Manufacturer;
BoxName.Text = product.ProductName?.Name ?? ""; // ← ИСПРАВИТЬ
BoxDescription.Text = product.Description ?? ""; // ← ИСПРАВИТЬ
BoxDiscount.Text = product.Discount?.ToString() ?? "0"; // ← ИСПРАВИТЬ
BoxPrice.Text = product.Price?.ToString() ?? "0"; // ← ИСПРАВИТЬ
BoxUnit.Text = product.Unit ?? ""; // ← ИСПРАВИТЬ
BoxCount.Text = product.Count?.ToString() ?? "0"; // ← ИСПРАВИТЬ
//Добавилииии
if (!string.IsNullOrEmpty(product.ImagePath))
{
string imagePath = Path.Combine(projPath, "Images", product.ImagePath);
if (File.Exists(imagePath))
{
try
{
BoxImage.Source = new BitmapImage(new Uri(imagePath));
}
catch (Exception ex)
{
Console.WriteLine($"Ошибка загрузки: {ex.Message}");
}
}
}
}
private void ButtonSaveProduct(object sender, RoutedEventArgs e)
{
if (string.IsNullOrWhiteSpace(BoxDescription.Text) ||
string.IsNullOrWhiteSpace(BoxDiscount.Text) ||
string.IsNullOrWhiteSpace(BoxName.Text) ||
string.IsNullOrWhiteSpace(BoxPrice.Text) ||
string.IsNullOrWhiteSpace(BoxUnit.Text))
{
MessageBox.Show("Заполните все поля");
return;
}
try
{
//Добавилиииииии
product.ProductName = context.ProductNames.FirstOrDefault(q => q.Name == BoxName.Text) ?? new ProductName() { Name = BoxName.Text };
// ← ИСПРАВИТЬ ЭТИ 3 СТРОКИ (добавить проверки)
if (BoxCategory.SelectedItem is Category cat) product.CategoryId = cat.Id;
if (BoxManufacturer.SelectedItem is Manufacturer man) product.ManufacturerId = man.Id;
if (BoxSupplier.SelectedItem is Supplier sup) product.SupplierId = sup.Id;
product.Description = BoxDescription.Text;
product.Price = int.Parse(BoxPrice.Text);
product.Unit = BoxUnit.Text;
product.Count = int.Parse(BoxCount.Text);
product.Discount = int.Parse(BoxDiscount.Text);
if (imageName != null)
{
product.ImagePath = imageName;
}
context.Entry(product).State = EntityState.Modified;
context.SaveChanges();
DialogResult = true;
}
catch (Exception ex)
{
MessageBox.Show($"не верный формат ввода {ex.Message}");
}
}
private void ButtonExit(object sender, RoutedEventArgs e)
{
DialogResult = false;
}
private void ButtonLoadImage(object sender, RoutedEventArgs e)
{
OpenFileDialog openFile = new OpenFileDialog();
if (openFile.ShowDialog() == true)
{
Uri uri = new Uri(openFile.FileName);
BitmapImage select = new(uri);
//if (select.Width > 400 || select.Height > 300)
//{
// MessageBox.Show("Размеры изображения имеют не верный формат");
// return;
//}
//добавлииииииии
string imagesFolder = Path.Combine(projPath, "Images");
string fileName = Guid.NewGuid().ToString() + Path.GetExtension(openFile.FileName);
string destPath = Path.Combine(imagesFolder, fileName);
File.Copy(openFile.FileName, destPath, true);
selectImage = select;
imageName = openFile.SafeFileName;
BoxImage.Source = selectImage;
}
}
}
}
RequestWin
AddRequest.xaml
<Window x:Class="demo.Windows.RequestWin.AddRequest"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:demo.Windows.RequestWin"
WindowStartupLocation="CenterScreen"
mc:Ignorable="d"
Title="Добавление заявки" Height="450" Width="800">
<StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">
<StackPanel>
<StackPanel Orientation="Horizontal"
Margin="4">
<TextBox Name="BoxArc"
Width="120"/>
<TextBlock Text="Ариткул"
Margin="5 0 0 0"/>
</StackPanel>
<StackPanel Orientation="Horizontal"
Margin="4">
<ComboBox Name="BoxStatus"
Width="120"
SelectedIndex="0"
DisplayMemberPath="Name"/>
<TextBlock Text="Статус заказа"
Margin="5 0 0 0"/>
</StackPanel>
<StackPanel Orientation="Horizontal"
Margin="4">
<ComboBox Name="BoxDelivary"
Width="120"
SelectedIndex="0"
DisplayMemberPath="Adress"/>
<TextBlock Text="Адрес"
Margin="5 0 0 0"/>
</StackPanel>
<StackPanel Orientation="Horizontal"
Margin="4">
<TextBox Name="BoxDateOrder"
Width="120"/>
<TextBlock Text="дата заказа"
Margin="5 0 0 0"/>
</StackPanel>
<StackPanel Orientation="Horizontal"
Margin="4">
<TextBox Name="BoxDateDelivery"
Width="120"/>
<TextBlock Text="дата выдачи"
Margin="5 0 0 0"/>
</StackPanel>
</StackPanel>
<StackPanel Orientation="Horizontal">
<Button Content="Добавить" Width="80" Click="Button_add" Margin="5"/>
<Button Content="Отмена" Width="80" Click="Button_exit" Margin="5"/>
</StackPanel>
</StackPanel>
</Window>
AddRequest.xaml.cs
using demo.Data;
using demo.Models;
using System.Windows;
namespace demo.Windows.RequestWin
{
public partial class AddRequest : Window
{
private DemoContext context;
public AddRequest()
{
InitializeComponent();
context = new DemoContext();
// Загружаем статусы
BoxStatus.ItemsSource = context.Statuses.ToList();
// Загружаем пункты выдачи
BoxDelivary.ItemsSource = context.PickupPoints.ToList();
}
private void Button_add(object sender, RoutedEventArgs e)
{
if (!string.IsNullOrWhiteSpace(BoxDateDelivery.Text) &&
!string.IsNullOrWhiteSpace(BoxDateOrder.Text) &&
!string.IsNullOrWhiteSpace(BoxArc.Text) &&
BoxDelivary.SelectedItem != null &&
BoxStatus.SelectedItem != null)
{
try
{
PickupPoint pickup = BoxDelivary.SelectedItem as PickupPoint;
Status status = BoxStatus.SelectedItem as Status;
Order order = new Order()
{
OrderDate = DateTime.Parse(BoxDateOrder.Text),
DeliveryDate = DateTime.Parse(BoxDateDelivery.Text),
Code = double.Parse(BoxArc.Text),
// Связи
PickupPointId = pickup.Id,
StatusId = status.Id
};
context.Orders.Add(order);
context.SaveChanges();
MessageBox.Show("Заказ успешно добавлен");
DialogResult = true;
}
catch (Exception ex)
{
MessageBox.Show($"Ошибка: {ex.Message}");
}
}
else
{
MessageBox.Show("Заполните все поля");
}
}
private void Button_exit(object sender, RoutedEventArgs e)
{
DialogResult = false;
}
}
}
EditRequest.xaml
<Window x:Class="demo.Windows.RequestWin.EditRequest"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:demo.Windows.RequestWin"
WindowStartupLocation="CenterScreen"
mc:Ignorable="d"
Title="Изменение заявки" Height="350" Width="400">
<StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">
<StackPanel Name="PanelOrder">
<StackPanel Orientation="Horizontal"
Margin="4">
<TextBox Name="BoxArc"
Text="{Binding Code}"
Width="120"/>
<TextBlock Text="Ариткул"
Margin="5 0 0 0"/>
</StackPanel>
<StackPanel Orientation="Horizontal"
Margin="4">
<ComboBox Name="BoxStatus"
Width="120"
SelectedIndex="0"
DisplayMemberPath="Name"/>
<TextBlock Text="Статус заказа"
Margin="5 0 0 0"/>
</StackPanel>
<StackPanel Orientation="Horizontal"
Margin="4">
<ComboBox x:Name="BoxDelivary"
Width="120"
SelectedIndex="0"
DisplayMemberPath="Adress"/>
<TextBlock Text="Пункс выдачи"
Margin="5 0 0 0"/>
</StackPanel>
<StackPanel Orientation="Horizontal"
Margin="4">
<TextBox Name="BoxDateOrder"
Width="120"
Text="{Binding OrderDate, StringFormat='dd.MM.yyyy'}"/>
<TextBlock Text="дата заказа"
Margin="5 0 0 0"/>
</StackPanel>
<StackPanel Orientation="Horizontal"
Margin="4">
<TextBox Name="BoxDateDelivery"
Width="120"
Text="{Binding DeliveryDate, StringFormat='dd.MM.yyyy'}"/>
<TextBlock Text="дата выдачи"
Margin="5 0 0 0"/>
</StackPanel>
</StackPanel>
<StackPanel Orientation="Horizontal">
<Button Content="Сохранить" Width="80" Click="Button_save" Margin="5"/>
<Button Content="Отмена" Width="80" Click="Button_exit" Margin="5"/>
</StackPanel>
</StackPanel>
</Window>
EditRequest.xaml.cs
using demo.Data;
using demo.Models;
using Microsoft.EntityFrameworkCore;
using System.Windows;
namespace demo.Windows.RequestWin
{
public partial class EditRequest : Window
{
private DemoContext context;
private Order order;
public EditRequest(Order order)
{
InitializeComponent();
context = new DemoContext();
PanelOrder.DataContext = order;
this.order = order;
BoxStatus.ItemsSource = context.Statuses.ToList();
BoxStatus.SelectedItem = order.Status;
BoxDelivary.ItemsSource = context.PickupPoints.ToList();
BoxDelivary.SelectedItem = order.PickupPoint;
}
private void Button_save(object sender, RoutedEventArgs e)
{
if (!string.IsNullOrWhiteSpace(BoxDateDelivery.Text) &&
!string.IsNullOrWhiteSpace(BoxDateOrder.Text) &&
!string.IsNullOrWhiteSpace(BoxArc.Text))
{
try
{
order.OrderDate = DateTime.Parse(BoxDateOrder.Text);
order.DeliveryDate = DateTime.Parse(BoxDateDelivery.Text);
order.Code = double.Parse(BoxArc.Text);
order.PickupPoint = BoxDelivary.SelectedItem as PickupPoint;
order.Status = BoxStatus.SelectedItem as Status;
context.Entry(order).State = EntityState.Modified;
context.SaveChanges();
DialogResult = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private void Button_exit(object sender, RoutedEventArgs e)
{
DialogResult = false;
}
}
}
RequestWindow.xaml
<Window x:Class="demo.Windows.RequestWin.RequestWindows"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:demo.Windows.RequestWin"
WindowStartupLocation="CenterScreen"
mc:Ignorable="d"
Title="Заявки" Height="600" Width="830">
<DockPanel>
<DockPanel DockPanel.Dock="Top" Margin="5">
<Button Content=" Назад " Click="Button_exit" DockPanel.Dock="Left"/>
<StackPanel>
</StackPanel>
</DockPanel>
<StackPanel Name="PanelBottomButton" Orientation="Horizontal" DockPanel.Dock="Bottom">
<Button Content="Добавить" Width="80" Margin="5" Click="Button_add_reques"/>
<Button Content="Удалить" Width="80" Margin="5" Click="Buutton_delite_reques"/>
</StackPanel>
<StackPanel>
<ListBox Name="BoxOrder"
Height="500"
PreviewMouseDoubleClick="BoxOrder_PreviewMouseDoubleClick"
>
<ListBox.ItemTemplate>
<DataTemplate>
<DockPanel Height="100">
<Border DockPanel.Dock="Right"
BorderBrush="Black"
BorderThickness="1"
Margin="5"
MinWidth="120">
<TextBlock Text="{Binding DeliveryDate, StringFormat='dd.MM.yyyy'}"
VerticalAlignment="Center"
HorizontalAlignment="Center"/>
</Border>
<Border BorderBrush="Black"
BorderThickness="1"
Margin="5"
Width="640">
<StackPanel>
<TextBlock Text="{Binding Code}" FontWeight="Bold"/>
<TextBlock Text="{Binding Status.Name}"/>
<TextBlock Text="{Binding PickupPoint.Adress}" />
<TextBlock Text="{Binding OrderDate, StringFormat='dd.MM.yyyy'}"/>
</StackPanel>
</Border>
</DockPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</DockPanel>
</Window>
RequestWindow.xaml.cs
using demo.Data;
using demo.Models;
using demo.UserControllers;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
namespace demo.Windows.RequestWin
{
public partial class RequestWindows : Window
{
private User user;
private DemoContext Context;
public RequestWindows(User user)
{
InitializeComponent();
this.user = user;
Context = new DemoContext();
List<Order> orders = Context.Orders
.Include(q => q.PickupPoint)
.Include(q => q.Status)
.ToList();
BoxOrder.ItemsSource = orders;
switch (user.RoleId)
{
case 2:
{
PanelBottomButton.Visibility = Visibility.Visible;
BoxOrder.MouseDoubleClick += BoxOrder_PreviewMouseDoubleClick;
break;
}
case 3:
{
PanelBottomButton.Visibility = Visibility.Collapsed;
break;
}
}
}
private void Buutton_delite_reques(object sender, RoutedEventArgs e)
{
Order prod = BoxOrder.SelectedItem as Order;
if (prod != null)
{
try
{
// Очищаем трекер контекста
Context.ChangeTracker.Clear();
// Загружаем заказ заново
var order = Context.Orders
.Include(o => o.OrderArticles)
.FirstOrDefault(o => o.Id == prod.Id);
if (order != null)
{
// Удаляем связанные записи
if (order.OrderArticles != null && order.OrderArticles.Any())
{
Context.OrderArticles.RemoveRange(order.OrderArticles);
}
// Удаляем заказ
Context.Orders.Remove(order);
Context.SaveChanges();
// Обновляем список
BoxOrder.ItemsSource = Context.Orders
.Include(q => q.PickupPoint)
.Include(q => q.Status)
.ToList();
MessageBox.Show("Заказ успешно удален", "Успех",
MessageBoxButton.OK, MessageBoxImage.Information);
}
}
catch (Exception ex)
{
MessageBox.Show($"Ошибка при удалении: {ex.Message}", "Ошибка",
MessageBoxButton.OK, MessageBoxImage.Error);
}
}
else
{
MessageBox.Show("Выберите заказ для удаления", "Предупреждение",
MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
private void Button_exit(object sender, RoutedEventArgs e)
{
DialogResult = false;
}
private void BoxOrder_PreviewMouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
e.Handled = true;
Order order = BoxOrder.SelectedItem as Order;
if (order != null)
{
EditRequest edit = new EditRequest(order);
if (edit.ShowDialog() == true)
{
BoxOrder.ItemsSource = Context.Orders.ToList();
}
}
}
private void Button_add_reques(object sender, RoutedEventArgs e)
{
AddRequest add = new AddRequest();
if (add.ShowDialog() == true)
{
BoxOrder.ItemsSource = Context.Orders
.Include(q => q.PickupPoint)
.Include(q => q.Status)
.ToList();
}
}
}
}
Authorization.xaml
<Window x:Class="demo.Windows.Authorization"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:demo.Windows"
WindowStartupLocation="CenterScreen"
mc:Ignorable="d"
Title="Авторизация" Height="250" Width="300">
<StackPanel VerticalAlignment="Center" HorizontalAlignment="Center">
<StackPanel Orientation="Horizontal" Margin=" 5">
<TextBox Width="120" Name="BoxLogin" Text="94d5ous@gmail.com"/>
<TextBlock Text="Логин" Margin="5 0 0 0"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin=" 5">
<TextBox Width="120" Name="BoxPassword" Text="uzWC67"/>
<TextBlock Text="Пароль" Margin="5 0 0 0"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin=" 5">
<Button Content=" Войти " Click="Button_authorization"/>
<Button Content="Войти как гость" Click="Button_authorization_gouest"
Margin=" 5 0 0 0"/>
</StackPanel>
</StackPanel>
</Window>
Authorization.xaml.cs
using demo.Data;
using demo.Models;
using Microsoft.EntityFrameworkCore;
using System.Windows;
namespace demo.Windows
{
public partial class Authorization : Window
{
public Authorization()
{
InitializeComponent();
}
private void Button_authorization(object sender, RoutedEventArgs e)
{
if(!string.IsNullOrWhiteSpace(BoxLogin.Text) && !string.IsNullOrWhiteSpace(BoxPassword.Text))
{
using (var db = new DemoContext())
{
var user = db.Users.FirstOrDefault(e => e.Login == BoxLogin.Text || e.Password == BoxPassword.Text);
if (user != null)
{
Main main = new Main(user);
main.Show();
this.Close();
}
}
}
else
{
MessageBox.Show("Заполните все поля");
}
}
private void Button_authorization_gouest(object sender, RoutedEventArgs e)
{
Main main = new Main();
main.Show();
this.Close();
}
}
}
Main.xaml
<Window x:Class="demo.Windows.Main"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:demo.Windows"
WindowStartupLocation="CenterScreen"
mc:Ignorable="d"
Title="Приложение" Height="900" Width="1300">
<DockPanel>
<DockPanel DockPanel.Dock="Top" Margin="5">
<Button Content=" Выход " Click="Button_exit_user" DockPanel.Dock="Left"/>
<TextBlock DockPanel.Dock="Right">
<Run Text="Добро пожаловать: "/>
<Run Name="RunUserName"/>
<Run Text="Роль"/>
<Run Name="RunUserRole"/>
</TextBlock>
<StackPanel>
</StackPanel>
</DockPanel>
<StackPanel Name="PanelBottomButton" Orientation="Horizontal" DockPanel.Dock="Bottom">
<StackPanel Name="PanelBottomAdmin" Orientation="Horizontal">
<Button Content="Добавить" Width="80" Margin="5" Click="Button_add_product"/>
<Button Content="Удалить" Width="80" Margin="5" Click="Buutton_delite_product"/>
</StackPanel>
<Button Name="PanelRequestBottom" Content="Заявки" Width="80" Margin="5" Click="Button_request"/>
</StackPanel>
<StackPanel>
<ListBox Name="BoxProduct" Width="1240" Height="730" MouseDoubleClick="BoxProduct_MouseDoubleClick_1"/>
<StackPanel Orientation="Horizontal" Margin="5" Name="PanelFind">
<TextBox Width="100" Name="BoxFind" TextChanged="BoxFind_TextChanged"/>
<TextBlock Text="Поиск" Margin=" 5 0 5 0"/>
<ComboBox Name="ComboBoxItem" SelectedIndex="0" Width="100" SelectionChanged="ComboSuppliers_SelectionChanged"/>
<RadioButton Content="по возрастанию" Margin="5 0 5 0"
Checked="RadioUpp_Checked"
IsChecked="True"/>
<RadioButton Content="по убыванию"
Checked="RadioDesc_Checked"/>
</StackPanel>
</StackPanel>
</DockPanel>
</Window>
Main.xaml.cs
using demo.Data;
using demo.Models;
using demo.UserControllers;
using demo.Windows.Products;
using demo.Windows.RequestWin;
using Microsoft.EntityFrameworkCore;
using System;
using System.IO;
using System.Reflection;
using System.Transactions;
using System.Windows;
using System.Windows.Controls;
namespace demo.Windows
{
public partial class Main : Window
{
private User user;
private DemoContext _db = new DemoContext();
private List<Product> _allProduct = new List<Product>();
private string _searchStr = string.Empty;
private int _filterId = 0;
private bool _desc = false;
public Main(User user = null)
{
InitializeComponent();
this.user = user;
LoadData(_desc, _searchStr, _filterId);
DrawSuppliers();
if (user == null)
{
RunUserName.Text = "Гость";
RunUserRole.Text = "гость";
PanelBottomButton.Visibility = Visibility.Collapsed;
PanelFind.Visibility = Visibility.Collapsed;
}
else
{
RunUserName.Text = user.FullName;
switch (user.RoleId)
{
case 1:
{
RunUserRole.Text = "Авторизированный пользователь";
return;
}
case 2:
{
RunUserRole.Text = "Администратор";
PanelFind.Visibility = Visibility.Visible;
PanelBottomAdmin.Visibility = Visibility.Visible;
PanelRequestBottom.Visibility = Visibility.Visible;
return;
}
case 3:
{
RunUserRole.Text = "Менеджер";
PanelFind.Visibility = Visibility.Visible;
PanelBottomAdmin.Visibility = Visibility.Collapsed;
PanelRequestBottom.Visibility = Visibility.Visible;
return;
}
}
}
}
public void DrawSuppliers()
{
var supplier = new List<Supplier>
{
new Supplier {Id = 0, Name = "все поставщики"}
};
supplier.AddRange(_db.Suppliers.ToList());
ComboBoxItem.SelectedIndex = 0;
ComboBoxItem.SelectedItem = "Id";
ComboBoxItem.ItemsSource = supplier;
ComboBoxItem.DisplayMemberPath = "Name";
}
private void LoadData(bool? desc = false, string? searchStr = null, int? filterId = null)
{
searchStr ??= "";
var query = _db.Products.AsQueryable();
if (!string.IsNullOrEmpty(searchStr))
{
query = query.Where(e => e.ProductName.Name.Contains(searchStr) || e.Category.Name.Contains(searchStr) || e.Description.Contains(searchStr) || e.Supplier.Name.Contains(searchStr) || e.Manufacturer.Name.Contains(searchStr));
}
if (filterId.HasValue && filterId.Value != 0)
{
query = query.Where(e => e.SupplierId == filterId.Value);
}
_allProduct = query.ToList();
if (desc == false)
{
_allProduct = _allProduct.OrderByDescending(e => e.Count).ToList();
}
else
{
_allProduct = _allProduct.OrderBy(e => e.Count).ToList();
}
BoxProduct.Items.Clear();
foreach (var product in _allProduct)
{
var productController = new ItemProduct(product);
BoxProduct.Items.Add(productController);
}
}
private void Button_exit_user(object sender, RoutedEventArgs e)
{
Authorization authorization = new Authorization();
authorization.Show();
this.Close();
}
private void Button_add_product(object sender, RoutedEventArgs e)
{
AddProduct add = new AddProduct();
if (add.ShowDialog() == true)
{
LoadData(_desc, _searchStr, _filterId);
}
}
private void Button_request(object sender, RoutedEventArgs e)
{
RequestWindows request = new RequestWindows(user);
if (request.ShowDialog() == true)
{
}
}
//Поиск
private void BoxFind_TextChanged(object sender, TextChangedEventArgs e)
{
_searchStr = BoxFind.Text;
LoadData(_desc, _searchStr, _filterId);
}
//Сортировка
private void RadioUpp_Checked(object sender, RoutedEventArgs e)
{
_desc = true;
LoadData(_desc, _searchStr, _filterId);
}
//Фильтрация
private void ComboSuppliers_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var selectedSupplier = ComboBoxItem.SelectedItem as Supplier;
_filterId = selectedSupplier?.Id ?? 0;
LoadData(_desc, _searchStr, _filterId);
}
private void Buutton_delite_product(object sender, RoutedEventArgs e)
{
if (BoxProduct.SelectedItem is ItemProduct controller)
{
var product = controller.Product;
try
{
using (var db = new DemoContext())
{
bool IsUsedInOrder = _db.OrderArticles.Any(e => e.ProductId == product.Id);
if (IsUsedInOrder)
{
MessageBox.Show("Вы не можете удалить товар, он находится в заказе");
return;
}
var productDeleted = _db.Products.FirstOrDefault(e => e.Id == product.Id);
if (productDeleted != null)
{
_db.Products.Remove(productDeleted);
_db.SaveChanges();
MessageBox.Show("Товар успешно удален");
LoadData(_desc, _searchStr, _filterId);
}
}
}
catch (Exception ex)
{
MessageBox.Show($"Произошла ошибка при удалении{ex.Message}", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
else
{
MessageBox.Show("Выберите товар для удаления");
}
}
private void BoxProduct_MouseDoubleClick_1(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
ListBox list = sender as ListBox;
ItemProduct controller = list.SelectedItem as ItemProduct;
Product product = controller.DataContext as Product;
EditProduct edit = new EditProduct(product);
if (edit.ShowDialog() == true)
{
//добавилииииии
_db.ChangeTracker.Clear();
LoadData(_desc, _searchStr, _filterId);
}
}
private void RadioDesc_Checked(object sender, RoutedEventArgs e)
{
_desc = false;
LoadData(_desc, _searchStr, _filterId);
}
}
}
App.xaml
<Application x:Class="demo.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:demo"
StartupUri="Windows/Authorization.xaml">
<Application.Resources>
</Application.Resources>
</Application>
There are no supported framework assets in this package.
Learn more about Target Frameworks and .NET Standard.
This package has no dependencies.
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 1.0.11 | 213 | 6/11/2026 |