DemoExam.Nuget3 1.0.0

dotnet add package DemoExam.Nuget3 --version 1.0.0
                    
NuGet\Install-Package DemoExam.Nuget3 -Version 1.0.0
                    
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="DemoExam.Nuget3" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="DemoExam.Nuget3" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="DemoExam.Nuget3" />
                    
Project file
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 DemoExam.Nuget3 --version 1.0.0
                    
#r "nuget: DemoExam.Nuget3, 1.0.0"
                    
#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 DemoExam.Nuget3@1.0.0
                    
#: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=DemoExam.Nuget3&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=DemoExam.Nuget3&version=1.0.0
                    
Install as a Cake Tool

AddProduct

<Window x:Class="DemoExamForNuGet.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:DemoExamForNuGet.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>

using DemoExamForNuGet.AppDbContext; using DemoExamForNuGet.Models; using Microsoft.Win32; using System.IO; using System.Reflection; using System.Windows; using System.Windows.Media.Imaging;

namespace DemoExamForNuGet.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
        {
            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);
            }
            //тут идёт присвоение id как как в таблице я забыл установить автоикремент для поля ID,
            //поэтому я делаю это руками (так делать не надо)
            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 = int.Parse(BoxPrice.Text),
                Unit = BoxUnit.Text,
                Count = int.Parse(BoxCount.Text),
                Discount = int.Parse(BoxDiscount.Text),
                ImagePath = imageName,
            };
            context.Products.Add(newProduct);
            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;
            //}
            selectImage = select;
            imageName = openFile.SafeFileName;
            BoxImage.Source = selectImage;
        }
    }
}

}

EditProduct

<Window x:Class="DemoExamForNuGet.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:DemoExamForNuGet.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>

using DemoExamForNuGet.AppDbContext; using DemoExamForNuGet.Models; using Microsoft.EntityFrameworkCore; using Microsoft.Win32; using System.IO; using System.Reflection; using System.Windows; using System.Windows.Media.Imaging;

namespace DemoExamForNuGet.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;
        }
    }
}

}

AddRequest

<Window x:Class="DemoExamForNuGet.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:DemoExamForNuGet.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"> <TextBox Name="BoxDelivary" Width="120"/> <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>

using DemoExamForNuGet.AppDbContext; using DemoExamForNuGet.Models; using System.Windows;

namespace DemoExamForNuGet.Windows.RequestWin { public partial class AddRequest : Window { private DemoContext context; public AddRequest() { InitializeComponent(); context = new DemoContext(); BoxStatus.ItemsSource = context.Statuses.ToList(); }

    private void Button_add(object sender, RoutedEventArgs e)
    {
        if(!string.IsNullOrWhiteSpace(BoxDateDelivery.Text) && 
            !string.IsNullOrWhiteSpace(BoxDateOrder.Text) && 
            !string.IsNullOrWhiteSpace(BoxArc.Text) &&
            !string.IsNullOrWhiteSpace(BoxDelivary.Text))
        {
            try
            {
                //тут идёт присвоение id как как в таблице я забыл установить автоикремент для поля ID,
                //поэтому я делаю это руками (так делать не надо)
                Order order = new Order()
                {
                    
                    OrderDate = DateTime.Parse(BoxDateOrder.Text),
                    DeliveryDate = DateTime.Parse(BoxDateDelivery.Text),
                    Code = double.Parse(BoxArc.Text),
                    PickupPoint = context.PickupPoints.FirstOrDefault(q => q.Adress == BoxDelivary.Text),
                    Status = BoxStatus.SelectedItem as Status
                };
                context.Orders.Add(order);
                context.SaveChanges();
                DialogResult = true;
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }

    private void Button_exit(object sender, RoutedEventArgs e)
    {
        DialogResult = false;
    }
}

}

EditRequest

<Window x:Class="DemoExamForNuGet.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:DemoExamForNuGet.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" DisplayMemberPath="Name"/> <TextBlock Text="Статус заказа" Margin="5 0 0 0"/> </StackPanel> <StackPanel Orientation="Horizontal" Margin="4"> <TextBox Name="BoxDelivary" Width="120" Text="{Binding PickupPoint.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>

using DemoExamForNuGet.AppDbContext; using DemoExamForNuGet.Models; using Microsoft.EntityFrameworkCore; using System.Windows;

namespace DemoExamForNuGet.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;

    }

    private void Button_save(object sender, RoutedEventArgs e)
    {
        if (!string.IsNullOrWhiteSpace(BoxDateDelivery.Text) &&
            !string.IsNullOrWhiteSpace(BoxDateOrder.Text) &&
            !string.IsNullOrWhiteSpace(BoxArc.Text) &&
            !string.IsNullOrWhiteSpace(BoxDelivary.Text))
        {
            try
            {

                order.OrderDate = DateTime.Parse(BoxDateOrder.Text);
                order.DeliveryDate = DateTime.Parse(BoxDateDelivery.Text);
                order.Code = double.Parse(BoxArc.Text);
                order.PickupPoint = context.PickupPoints.FirstOrDefault(q => q.Adress == BoxDelivary.Text);
                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

<Window x:Class="DemoExamForNuGet.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:DemoExamForNuGet.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"
                 MouseDoubleClick="BoxProduct_MouseDoubleClick">
            <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>

using DemoExamForNuGet.AppDbContext; using DemoExamForNuGet.Models; using DemoExamForNuGet.UserControllers; using Microsoft.EntityFrameworkCore; using System.Linq; using System.Windows; using System.Windows.Controls;

namespace DemoExamForNuGet.Windows.RequestWin { public partial class RequestWindows : Window { private DemoContext Context; public RequestWindows() { InitializeComponent(); Context = new DemoContext();

        List<Order> orders = Context.Orders
            .Include(q => q.PickupPoint)
            .Include(q => q.Status)
            .ToList();
        BoxOrder.ItemsSource = Context.Orders.ToList();

        //if (user.RoleNavigation.Role1 == "Администратор")
        //{
        //    BoxOrder.MouseDoubleClick += BoxProduct_MouseDoubleClick; ;
        //    PanelBottomButton.Visibility = Visibility.Visible;
        //}
        //else
        //{
        //    PanelBottomButton.Visibility = Visibility.Collapsed;
        //}
    }

    private void BoxProduct_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        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.ToList();
        }
    }

    private void Buutton_delite_reques(object sender, RoutedEventArgs e)
    {
        Order prod = BoxOrder.SelectedItem as Order;
        if (prod != null)
        {
            try
            {
                // Получаем связанные записи OrderArticles
                var ordersArticles = Context.OrderArticles.Where(q => q.Order == prod).ToList();

                if (ordersArticles.Any())
                {
                    Context.OrderArticles.RemoveRange(ordersArticles);
                }

                // Удаляем сам заказ
                Context.Orders.Remove(prod);

                // Один раз сохраняем изменения
                Context.SaveChanges();

                // Обновляем источник данных
                BoxOrder.ItemsSource = Context.Orders.ToList();

                MessageBox.Show("Заказ успешно удален");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ошибка при удалении: {ex.Message}");
            }
        }
        else
        {
            MessageBox.Show("Выберите заказ для удаления");
        }
    }

    private void Button_exit(object sender, RoutedEventArgs e)
    {
        DialogResult = false;
    }
}

}

Authorization

<Window x:Class="DemoExamForNuGet.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:DemoExamForNuGet.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>

using DemoExamForNuGet.AppDbContext; using DemoExamForNuGet.Models; using Microsoft.EntityFrameworkCore; using System.Windows;

namespace DemoExamForNuGet.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

<Window x:Class="DemoExamForNuGet.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:DemoExamForNuGet.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>

using DemoExamForNuGet.AppDbContext; using DemoExamForNuGet.Models; using DemoExamForNuGet.UserControllers; using DemoExamForNuGet.Windows.Products; using DemoExamForNuGet.Windows.RequestWin; using System.Windows; using System.Windows.Controls;

namespace DemoExamForNuGet.Windows { public partial class Main : Window { 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();
        LoadData(_desc, _searchStr, _filterId);
        DrawSuppliers();
        if (user == null)
        {
            RunUserName.Text = "Гость";
            RunUserRole.Text = "гость";
        }
        else
        {
            RunUserName.Text = user.FullName;
            switch (user.RoleId)
            {
                case 1:
                    {
                        RunUserRole.Text = "Авторизированный пользователь";
                        return;
                    }
                    case 2:
                    {
                        RunUserRole.Text = "Администратор";
                        PanelFind.Visibility = Visibility.Collapsed;
                        PanelBottomAdmin.Visibility = Visibility.Collapsed;
                        return;
                    }
                    case 3:
                    {
                        RunUserRole.Text = "Менеджер";
                        PanelFind.Visibility = Visibility.Collapsed;
                        PanelBottomButton.Visibility = Visibility.Collapsed;
                        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 BoxProduct_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        
    }

    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();
        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);
    }
}

}

ItemProduct

<UserControl x:Class="DemoExamForNuGet.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:DemoExamForNuGet.UserControllers" mc:Ignorable="d" d:DesignHeight="200" d:DesignWidth="1200" Background="White"> <DockPanel Width="1200"> <Border DockPanel.Dock="Left" BorderBrush="Black" BorderThickness="1" Margin="5"> <Image Height="200" Width="300" Name="BoxImage"/> </Border>

    <Border DockPanel.Dock="Right"
            BorderBrush="Black"
            BorderThickness="1"
            Margin="5"
            MinWidth="250"
            Name="BoxDiscount">
        <TextBlock FontSize="40" 
                   HorizontalAlignment="Center" 
                   VerticalAlignment="Center">
            <Run Text="{Binding Discount}"/>
            <Run Text="%"/>
        </TextBlock>
    </Border>
    
    <Border BorderBrush="Black"
            BorderThickness="1"
            Margin="5">
        <StackPanel Margin="5 0 0 0">
            <TextBlock FontSize="25" FontWeight="Bold">
                <Run Text="{Binding ProductName.Name}"/>
                <Run Text=" | "/>
                <Run Text="{Binding Category.Name}"/>
            </TextBlock>
            <TextBlock FontSize="18" TextWrapping="Wrap">
                <Run Text="Описание товара: "/>
                <Run Text="{Binding Description}"/>
            </TextBlock>
            <TextBlock FontSize="18">
                <Run Text="Производитель: "/>
                <Run Text="{Binding Manufacturer.Name}"/>
            </TextBlock>
            <TextBlock FontSize="18">
                <Run Text="Поставщик: "/>
                <Run Text="{Binding Supplier.Name}"/>
            </TextBlock>
            <TextBlock FontSize="18">
                <Run Text="Цена: "/>
                <Run Text="{Binding Price}" Name="BoxPrice"/>
                <Run Name="BoxNewPrice"/>
            </TextBlock>
            <TextBlock FontSize="18">
                <Run Text="Единица измерения: "/>
                <Run Text="{Binding Unit}"/>
            </TextBlock>
            <TextBlock FontSize="18" Name="BoxCount">
                <Run Text="Количество на складе: "/>
                <Run Text="{Binding Count}"/>
            </TextBlock>
        </StackPanel>
    </Border>
</DockPanel>

</UserControl>

using DemoExamForNuGet.AppDbContext; using DemoExamForNuGet.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 DemoExamForNuGet.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);

            BoxNewPrice.Text = (product.Price * (1 - product.Discount / 100.0)).ToString();
        }

        if (product.Count == 0)
        {
            BoxCount.Foreground = Brushes.Blue;
        }
    }
}

}

Models

Category.cs

public class Category { [Key] public int Id { get; set; }

public string? Name { get; set; }

public ICollection<Product> Products { get; set; }

}

Manufacter.cs

public class Manufacturer { [Key] public int Id { get; set; }

public string? Name { get; set; }

public ICollection<Product> Products { get; set; }

}

Order.cs

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; }

}

OrderArcicle.cs

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

public class PickupPoint { [Key] public int Id { get; set; }

public string? Adress { get; set; }

public ICollection<Order> Orders { get; set; }

}

Product.cs

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

public class ProductName { [Key] public int Id { get; set; }

public string? Name { get; set; }

public ICollection<Product> Products { get; set; }

}

Role.cs

public class Role { [Key] public int Id { get; set; }

public string? Name { get; set; }

public ICollection<User> Users { get; set; }

}

Status.cs

public partial class Status { [Key] public int Id { get; set; }

public string? Name { get; set; }

public ICollection<Order> Orders { get; set; }

}

Supplier.cs

public class Supplier { [Key] public int Id { get; set; }

public string? Name { get; set; }

public ICollection<Product> Products { get; set; }

}

User.cs

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; }

}

AppDbContext

using Microsoft.EntityFrameworkCore; using DemoExamForNuGet.Models; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Controls;

namespace DemoExamForNuGet.AppDbContext { 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");
}

}

Product Compatible and additional computed target framework versions.
.NET net8.0-windows7.0 is compatible.  net9.0-windows was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • net8.0-windows7.0

    • 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.0 116 4/19/2026