EntityFrameworkGlobus 4.0.0
dotnet add package EntityFrameworkGlobus --version 4.0.0
NuGet\Install-Package EntityFrameworkGlobus -Version 4.0.0
<PackageReference Include="EntityFrameworkGlobus" Version="4.0.0" />
<PackageVersion Include="EntityFrameworkGlobus" Version="4.0.0" />
<PackageReference Include="EntityFrameworkGlobus" />
paket add EntityFrameworkGlobus --version 4.0.0
#r "nuget: EntityFrameworkGlobus, 4.0.0"
#:package EntityFrameworkGlobus@4.0.0
#addin nuget:?package=EntityFrameworkGlobus&version=4.0.0
#tool nuget:?package=EntityFrameworkGlobus&version=4.0.0
Scaffold: Scaffold-DbContext "Server=ServerName;Database=DatabaseName;Trusted_Connection=True; TrustServerCertificate=True" -Provider Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Context AppDatabase -Force
===========================================================================================================================================================
ProductController.xaml:
<UserControl x:Class="try2.Controlls.ProductController" 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:try2.Controlls" mc:Ignorable="d" d:DesignHeight="200" d:DesignWidth="1150"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="200"/> <ColumnDefinition Width="*"/> <ColumnDefinition Width="200"/> </Grid.ColumnDefinitions>
<Border Margin="5" BorderBrush="Black" BorderThickness="2" Grid.Column="0">
<Image x:Name="ImageBox"/>
</Border>
<Border Margin="5" BorderBrush="Black" BorderThickness="2" Grid.Column="1">
<StackPanel Width="780">
<TextBlock FontSize="20">
<Run Text="{Binding Category.Name}"/>
<Run Text="|"/>
<Run Text="{Binding Name}"/>
</TextBlock>
<TextBlock TextWrapping="Wrap" FontSize="20">
<Run Text="Описание:"/>
<Run Text="{Binding Description}"/>
</TextBlock>
<TextBlock FontSize="20">
<Run Text="Производиетль:"/>
<Run Text="{Binding Manufacturer.Name}"/>
</TextBlock>
<TextBlock FontSize="20">
<Run Text="Поставщик:"/>
<Run Text="{Binding Supplier.Name}"/>
</TextBlock>
<TextBlock FontSize="20">
<Run Text="Цена:"/>
<Run Name="PriceBox" Text="{Binding Price}"/>
<Run Name="NewPriceBox"/>
</TextBlock>
<TextBlock FontSize="20">
<Run Text="Единица измерения:"/>
<Run Text="{Binding Unit.Name}"/>
</TextBlock>
<TextBlock x:Name="CountBox" FontSize="20">
<Run Text="Количество на складе:"/>
<Run Text="{Binding Count}"/>
</TextBlock>
</StackPanel>
</Border>
<Border x:Name="DiscountBox" Margin="5" BorderBrush="Black" BorderThickness="2" Grid.Column="2">
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="30">
<Run Text="{Binding Discount}"/>
<Run Text="%"/>
</TextBlock>
</Border>
</Grid>
</UserControl>
=========================================================================================================================================================
ProductController.xaml.cs:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.IO; using try2.Models; using System.Reflection; using Microsoft.IdentityModel.Tokens;
namespace try2.Controlls {
public partial class ProductController : UserControl
{
private string projectPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
private string imagepath = string.Empty;
public ProductController(Product product)
{
InitializeComponent();
DataContext = product;
if(string.IsNullOrEmpty(product.ImagePath))
{
imagepath = Path.Combine(projectPath, "Images", "picture.png");
}
else
{
imagepath = Path.Combine(projectPath, "Images", product.ImagePath);
}
Uri uri = new Uri(imagepath);
ImageBox.Source = new BitmapImage(uri);
if (product.Discount > 0)
{
PriceBox.Foreground = new SolidColorBrush(Colors.Red);
PriceBox.TextDecorations = TextDecorations.Strikethrough;
NewPriceBox.Text = (product.Price - (product.Price * product.Discount/100)).ToString();
}
if(product.Discount > 15)
{
Color color = (Color)ColorConverter.ConvertFromString("#2E8B57");
DiscountBox.Background = new SolidColorBrush(color);
}
if (product.Count < 1)
{
CountBox.Foreground = new SolidColorBrush(Colors.Cyan);
}
}
}
}
===========================================================================================================================================================
AuthorizationWindow.xaml:
<Window x:Class="try2.Views.AuthorizationWindow" 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:try2.Views" mc:Ignorable="d" Title="AuthorizationWindow" Height="500" Width="800"> <StackPanel> <Label Margin="0,0,0,50" Content="Авторизация" FontSize="20" FontWeight="Bold" HorizontalAlignment="Center"/>
<Label Margin="10" Content="Логин:" FontSize="20"/>
<TextBox Margin="10,0,10,0" x:Name="LoginBox" FontSize="20" Width="300" HorizontalAlignment="Left"/>
<Label Margin="10" Content="Пароль:" FontSize="20"/>
<TextBox Margin="10,0,10,0" x:Name="PasswordBox" FontSize="20" Width="300" HorizontalAlignment="Left"/>
<Button Margin="50" Content="Войти" x:Name="EnterButton" FontSize="20" Width="300" HorizontalAlignment="Center" Click="EnterButton_Click"/>
<Button Content="Войти как гость" x:Name="GuestButton" FontSize="20" Width="300" HorizontalAlignment="Center" Click="GuestButton_Click" />
</StackPanel>
</Window>
==============================================================================================================================================================
AuthorizationWindow.xaml.cs:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using try2.Models;
namespace try2.Views { /// <summary> /// Логика взаимодействия для AuthorizationWindow.xaml /// </summary> public partial class AuthorizationWindow : Window { private AppDbContext db = new AppDbContext(); private string login = string.Empty; private string password = string.Empty; public AuthorizationWindow() { InitializeComponent(); }
private void EnterButton_Click(object sender, RoutedEventArgs e)
{
login = LoginBox.Text;
password = PasswordBox.Text;
if(string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password))
{
MessageBox.Show("Введите данные");
return;
}
User user = db.Users.Where(u => u.Login == login && u.Password == password).FirstOrDefault();
if(user == null)
{
MessageBox.Show("пользователь не найден");
return;
}
else
{
MainWindow mainWindow = new MainWindow(user);
mainWindow.Show();
this.Close();
}
}
private void GuestButton_Click(object sender, RoutedEventArgs e)
{
User user = new User
{
FullName = "Гостевой профиль",
RoleId = 3,
Login = login,
Password = password
};
MainWindow mainWindow = new MainWindow(user);
mainWindow.Show();
this.Close();
}
}
}
===============================================================================================================================================================
MainWindow.xaml:
<Window x:Class="try2.Views.MainWindow" 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:try2.Views" mc:Ignorable="d" WindowState="Maximized" WindowStyle="None" Title="MainWindow" Height="900" Width="1450"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> <ColumnDefinition Width="300"/> </Grid.ColumnDefinitions>
<Border BorderBrush="Black" BorderThickness="1" Grid.Column="0">
<ListBox x:Name="ProductList" MouseDoubleClick="ProductList_MouseDoubleClick"/>
</Border>
<StackPanel Margin="15" Grid.Column="1">
<TextBlock TextWrapping="Wrap" FontWeight="Bold" FontSize="20">
<Run Text="Пользователь:"/>
<Run Name="UserBox"/>
</TextBlock>
<Label Name="SearchTitle" Margin="0,90,0,0" Content="Поиск:" FontSize="20"/>
<TextBox x:Name="SearchBox" Width="270" FontSize="20" TextChanged="SearchBox_TextChanged"/>
<ComboBox Margin="0,45,0,65" Name="SupplierBox" FontSize="20" Width="270" SelectionChanged="SupplierBox_SelectionChanged"/>
<RadioButton x:Name="RiseButt" FontSize="20" Checked="RiseButt_Checked">
По возрастанию
</RadioButton>
<RadioButton Margin="0,22,0,85" x:Name="DownButt" FontSize="20" Checked="DownButt_Checked">
По убыванию
</RadioButton>
<Button Margin="0,20,0,20" FontSize="20" x:Name="AddButton" Content="Добавить" Click="AddButton_Click"/>
<Button Margin="0,20,0,20" FontSize="20" x:Name="DeleteButton" Content="Удалить" Click="DeleteButton_Click"/>
<Button Margin="0,20,0,20" FontSize="20" x:Name="BackButton" Content="Назад" Click="BackButton_Click" />
</StackPanel>
</Grid>
</Window>
=============================================================================================================================================================
MainWindow.xaml.cs:
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using try2.Controlls; using try2.Models;
namespace try2.Views {
public partial class MainWindow : Window
{
private AppDbContext db = new AppDbContext();
private List<Product> products = new List<Product>();
bool isRise = true;
bool isDown = false;
bool canRedact = true;
public MainWindow(User CurrentUser)
{
InitializeComponent();
UserBox.Text = CurrentUser.FullName;
if(CurrentUser.RoleId == 3)
{
canRedact = false;
AddButton.Visibility = Visibility.Collapsed;
DeleteButton.Visibility = Visibility.Collapsed;
SearchBox.Visibility = Visibility.Collapsed;
SearchTitle.Visibility = Visibility.Collapsed;
SupplierBox.Visibility = Visibility.Collapsed;
RiseButt.Visibility = Visibility.Collapsed;
DownButt.Visibility = Visibility.Collapsed;
}
if (CurrentUser.RoleId == 2)
{
canRedact = false;
AddButton.Visibility = Visibility.Collapsed;
DeleteButton.Visibility = Visibility.Collapsed;
}
RiseButt.IsChecked = true;
SupplierBox.Items.Add("Все поставщики");
foreach (Supplier supplier in db.Suppliers)
{
SupplierBox.Items.Add(supplier.Name);
}
SupplierBox.SelectedIndex = 0;
LoadInfo();
}
private void LoadInfo()
{
ProductList.Items.Clear();
products.Clear();
string searched = SearchBox.Text;
products = db.Products
.Include(p => p.Category)
.Include(p => p.Manufacturer)
.Include(p => p.Supplier)
.Include(p => p.Unit).ToList();
if(!string.IsNullOrEmpty(searched))
{
products = products.Where(p => p.Description.ToLower().Contains(searched.ToLower())
|| p.Name.ToLower().Contains(searched.ToLower())).ToList();
}
if(isRise)
{
products = products.OrderBy(p => p.Count).ToList();
}
if(isDown)
{
products = products.OrderByDescending(p => p.Count).ToList();
}
if(SupplierBox.SelectedIndex != 0)
{
products = products.Where(p => p.SupplierId == SupplierBox.SelectedIndex).ToList();
}
foreach(Product p in products)
{
ProductController productController = new ProductController(p);
ProductList.Items.Add(productController);
}
}
private void BackButton_Click(object sender, RoutedEventArgs e)
{
AuthorizationWindow authorizationWindow = new AuthorizationWindow();
authorizationWindow.Show();
this.Close();
}
private void SearchBox_TextChanged(object sender, TextChangedEventArgs e)
{
LoadInfo();
}
private void RiseButt_Checked(object sender, RoutedEventArgs e)
{
isRise = true;
isDown = false;
LoadInfo();
}
private void DownButt_Checked(object sender, RoutedEventArgs e)
{
isRise = false;
isDown = true;
LoadInfo();
}
private void SupplierBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
LoadInfo();
}
private void AddButton_Click(object sender, RoutedEventArgs e)
{
AddEditWindow addEditWindow = new AddEditWindow(null);
addEditWindow.ShowDialog();
if (addEditWindow.DialogResult == true)
{
Product product = addEditWindow.Tag as Product;
db.Add(product);
db.SaveChanges();
LoadInfo();
}
}
private void DeleteButton_Click(object sender, RoutedEventArgs e)
{
if (ProductList.SelectedItem == null)
{
MessageBox.Show("Выберите элемент");
return;
}
else
{
ProductController controller = ProductList.SelectedItem as ProductController;
Product product = controller.DataContext as Product;
db.Remove(product);
db.SaveChanges();
LoadInfo();
}
}
private void ProductList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
if(canRedact)
{
ProductController controller = ProductList.SelectedItem as ProductController;
Product product = controller.DataContext as Product;
AddEditWindow addEditWindow = new AddEditWindow(product);
addEditWindow.ShowDialog();
if(addEditWindow.DialogResult == true)
{
product = addEditWindow.Tag as Product;
db.Update(product);
db.SaveChanges();
LoadInfo();
}
}
}
}
}
==========================================================================================================================================================='
AddEditWindow.xaml:
<Window x:Class="try2.Views.AddEditWindow" 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:try2.Views" mc:Ignorable="d" WindowState="Maximized" WindowStyle="None" Title="AddEditWindow" Height="900" Width="1200"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="800"/> <ColumnDefinition Width="400"/> </Grid.ColumnDefinitions>
<StackPanel Grid.Column="0">
<TextBlock Margin="10" FontSize="20">
<Run Text="Введите артикул:"/>
<TextBox x:Name="ArticleBox" Width="300"/>
</TextBlock>
<TextBlock Margin="10" FontSize="20">
<Run Text="Введите название:"/>
<TextBox x:Name="NameBox" Width="300"/>
</TextBlock>
<TextBlock Margin="10" FontSize="20">
<Run Text="Выберите единицу измерения:"/>
<ComboBox DisplayMemberPath="Name" x:Name="UnitBox" Width="300"/>
</TextBlock>
<TextBlock Margin="10" FontSize="20">
<Run Text="Введите цену:"/>
<TextBox x:Name="PriceBox" Width="300"/>
</TextBlock>
<TextBlock Margin="10" FontSize="20">
<Run Text="Выберите поставщика:"/>
<ComboBox DisplayMemberPath="Name" x:Name="SupplierBox" Width="300"/>
</TextBlock>
<TextBlock Margin="10" FontSize="20">
<Run Text="Выберите производителя:"/>
<ComboBox DisplayMemberPath="Name" x:Name="ManufacturerBox" Width="300"/>
</TextBlock>
<TextBlock Margin="10" FontSize="20">
<Run Text="Выберите категорию:"/>
<ComboBox DisplayMemberPath="Name" x:Name="CategoryBox" Width="300"/>
</TextBlock>
<TextBlock Margin="10" FontSize="20">
<Run Text="Введите скидку:"/>
<TextBox x:Name="DiscountBox" Width="300"/>
</TextBlock>
<TextBlock Margin="10" FontSize="20">
<Run Text="Введите количество:"/>
<TextBox x:Name="CountBox" Width="300"/>
</TextBlock>
<TextBlock Margin="10" FontSize="20">
<Run Text="Введите описание:"/>
<TextBox x:Name="DescriptionBox" Width="300"/>
</TextBlock>
<Button Margin="30" Name="ImageButton" Width="300" FontSize="20" Content="Выберите фото" Click="ImageButton_Click"/>
<Button Margin="10" Name="SaveButton" Width="300" FontSize="20" Content="Сохранить" Click="SaveButton_Click"/>
<Button Margin="30" Name="CancelButton" Width="300" FontSize="20" Content="Отмена" Click="CancelButton_Click"/>
</StackPanel>
<StackPanel Grid.Column="1">
<Image x:Name="ImagePlace" Width="300" Height="300"/>
<TextBlock Margin="10" FontSize="30" HorizontalAlignment="Center">
<TextBox IsReadOnly="True" x:Name="ImageBox" Width="300"/>
</TextBlock>
</StackPanel>
</Grid>
</Window>
=============================================================================================================================================================
AddEditWindow.xaml.cs:
using Microsoft.Win32; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.IO; using try2.Models;
namespace try2.Views { /// <summary> /// Логика взаимодействия для AddEditWindow.xaml /// </summary> public partial class AddEditWindow : Window { private AppDbContext db = new AppDbContext(); private Product CurrentProduct = new Product(); private string projPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); public AddEditWindow(Product product) { InitializeComponent(); LoadData(); CurrentProduct = product; if (product != null) { ArticleBox.Text = product.Article; NameBox.Text = product.Name; UnitBox.SelectedIndex = product.Unit.Id - 1; PriceBox.Text = product.Price.ToString(); SupplierBox.SelectedIndex = product.Supplier.Id - 1; ManufacturerBox.SelectedIndex = product.Manufacturer.Id - 1; CategoryBox.SelectedIndex = product.Category.Id - 1; DiscountBox.Text = product.Discount.ToString(); CountBox.Text = product.Count.ToString(); DescriptionBox.Text = product.Description;
string imagePath = string.Empty;
if (string.IsNullOrEmpty(product.ImagePath))
{
imagePath = "picture.png";
}
else
{
imagePath = product.ImagePath;
}
ImageBox.Text = imagePath;
//со скрипом вывожу текущую картинку в окне изменения
string currentImage = Path.Combine(projPath, "Images", imagePath);
Uri uri = new Uri(currentImage);
ImagePlace.Source = new BitmapImage(uri);
}
}
private void LoadData()
{
List<Unit> units = db.Units.ToList();
List<Supplier> suppliers = db.Suppliers.ToList();
List<Manufacturer> manufacturers = db.Manufacturers.ToList();
List<Category> categories = db.Categories.ToList();
UnitBox.ItemsSource = units;
SupplierBox.ItemsSource = suppliers;
ManufacturerBox.ItemsSource = manufacturers;
CategoryBox.ItemsSource = categories;
}
private bool Validation()
{
if (string.IsNullOrEmpty(ArticleBox.Text))
{
MessageBox.Show("Введите артикул");
return false;
}
if (string.IsNullOrEmpty(NameBox.Text))
{
MessageBox.Show("Введите название");
return false;
}
if(UnitBox.SelectedIndex == -1)
{
MessageBox.Show("Выберите единицы измерения");
return false;
}
if (string.IsNullOrEmpty(PriceBox.Text))
{
MessageBox.Show("Введите цену");
return false;
}
else
{
try
{
float price = Convert.ToSingle(PriceBox.Text);
if (price < 1)
{
MessageBox.Show("Цена должна быть > 0");
return false;
}
}
catch
{
MessageBox.Show("Введите корректные данные");
return false;
}
}
if (SupplierBox.SelectedIndex == -1)
{
MessageBox.Show("Выберите поставщика");
return false;
}
if (ManufacturerBox.SelectedIndex == -1)
{
MessageBox.Show("Выберите производителя");
return false;
}
if (CategoryBox.SelectedIndex == -1)
{
MessageBox.Show("Выберите категорию");
return false;
}
if (string.IsNullOrEmpty(DiscountBox.Text))
{
MessageBox.Show("Введите скидку");
return false;
}
else
{
try
{
int discount = Convert.ToInt32(DiscountBox.Text);
if (discount < 1 || discount > 99)
{
MessageBox.Show("Скидка должна быть > 0 и < 100");
return false;
}
}
catch
{
MessageBox.Show("Введите корректные данные");
return false;
}
}
if (string.IsNullOrEmpty(CountBox.Text))
{
MessageBox.Show("Введите количество");
return false;
}
else
{
try
{
int count = Convert.ToInt32(CountBox.Text);
if (count < 0)
{
MessageBox.Show("Количчество должно быть не < 0");
return false;
}
}
catch
{
MessageBox.Show("Введите корректные данные");
return false;
}
}
if(string.IsNullOrEmpty(DescriptionBox.Text))
{
MessageBox.Show("Введите описание");
return false;
}
return true;
}
private void CancelButton_Click(object sender, RoutedEventArgs e)
{
this.DialogResult = false;
}
private void SaveButton_Click(object sender, RoutedEventArgs e)
{
if (Validation() == true)
{
string article = ArticleBox.Text;
string name = NameBox.Text;
string description = DescriptionBox.Text;
Unit unit = UnitBox.SelectedItem as Unit;
float price = Convert.ToSingle(PriceBox.Text);
Supplier supplier = SupplierBox.SelectedItem as Supplier;
Manufacturer manufacturer = ManufacturerBox.SelectedItem as Manufacturer;
Category category = CategoryBox.SelectedItem as Category;
int discount = Convert.ToInt32(DiscountBox.Text);
int count = Convert.ToInt32(CountBox.Text);
string imagepath = ImageBox.Text;
if(CurrentProduct == null)
{
Product product = new Product
{
Article = article,
Name = name,
UnitId = unit.Id,
Price = price,
SupplierId = supplier.Id,
ManufacturerId = manufacturer.Id,
CategoryId = category.Id,
Discount = discount,
Count = count,
Description = description,
ImagePath = imagepath
};
this.Tag = product;
this.DialogResult = true;
}
else
{
CurrentProduct.Article = article;
CurrentProduct.Name = name;
CurrentProduct.UnitId = unit.Id;
CurrentProduct.Price = price;
CurrentProduct.SupplierId = supplier.Id;
CurrentProduct.ManufacturerId = manufacturer.Id;
CurrentProduct.CategoryId = category.Id;
CurrentProduct.Discount = discount;
CurrentProduct.Count = count;
CurrentProduct.Description = description;
CurrentProduct.ImagePath = imagepath;
this.Tag = CurrentProduct;
this.DialogResult = true;
}
}
}
private void ImageButton_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Multiselect = false;
openFileDialog.Filter = "Изображения(*.png; *.jpg)| *.png; *.jpg";
if (openFileDialog.ShowDialog() == true)
{
//первые два стринга нужны для сохранения картинки впринципе, а тертий для копии несуществующей еще картинки
string mainPath = openFileDialog.FileName;
string name = Path.GetFileName(mainPath);
string targetPath = Path.Combine(projPath, "Images", Path.GetFileName(mainPath));
if (!File.Exists(targetPath))
{
File.Copy(mainPath, targetPath);
}
Uri uri = new Uri(mainPath);
ImagePlace.Source = new BitmapImage(uri);
ImageBox.Text = name;
}
}
}
}
=============================================================================================================================================================
ФормаСменыПароля:
&НаСервере Функция ИзменитьПарольНаСервере() Если ТекущийПароль = Параметры.ПараметрПользователь.Пароль и НовыйПароль = ПодтверждениеПароля Тогда ПользовательОбъект = Параметры.ПараметрПользователь.ПолучитьОбъект(); ПользовательОбъект.Пароль = НовыйПароль; ПользовательОбъект.ДатаВхода = ТекущаяДата(); ПользовательОбъект.Записать(); Возврат Истина; Иначе Сообщить("Пароли не совпадают"); Возврат Ложь; КонецЕсли; КонецФункции
&НаКлиенте Процедура ИзменитьПароль(Команда) Если ИзменитьПарольНаСервере()= Истина ТОгда Если Роль = ПредопределенноеЗначение("Перечисление.Роли.Пользователь") Тогда Открытьформу("ОбщаяФорма.ФормаПользователя"); Сообщить("Вы успешно авторизировались и сменили пароль"); Этаформа.Закрыть(); КонецЕсли;
Если Роль = ПредопределенноеЗначение("Перечисление.Роли.Админ") Тогда
Открытьформу("Справочник.Пользователи.ФормаСписка");
Сообщить("Вы успешно авторизировались и сменили пароль");
Этаформа.Закрыть();
КонецЕсли;
КонецЕсли;
КонецПроцедуры
&НаСервере Процедура ПриОткрытииНаСервере() Роль = Параметры.ПараметрПользователь.Роль; КонецПроцедуры
&НаКлиенте Процедура ПриОткрытии(Отказ) ПриОткрытииНаСервере(); КонецПроцедуры
============================================================================================================================================================
ФормаАвторизациии:
&НаСервере Функция ВойтиНаСервере() ПользовательНайден = Справочники.Пользователи.ПустаяСсылка(); Если НЕ Справочники.Пользователи.НайтиПоНаименованию(Логин,Истина).Пустая() Тогда ПользовательНайден = Справочники.Пользователи.НайтиПоНаименованию(Логин,Истина).Ссылка; Если ПользовательНайден.Пароль = Пароль Тогда Если НЕ ПользовательНайден.ДатаВхода = Дата("01.01.0001 0:00:00") Тогда Если ТекущаяДата() > ДобавитьМесяц(НачалоМесяца(ПользовательНайден.ДатаВхода),1) Тогда ИзменитьНаСервере(ПользовательНайден,"Активность",Ложь); Сообщить("Вы заблокированны!"); КонецЕсли; КонецЕсли; Возврат ПользовательНайден.Роль; Иначе ЗадатьПопытки(ПользовательНайден); Сообщить("Неверный пароль"); Возврат Неопределено; КонецЕсли;
Иначе
Сообщить("Вы ввели неверный логин");
Возврат Неопределено;
КонецЕсли;
КонецФункции
&НаКлиенте
Процедура Войти(Команда)
Роль = ВойтиНаСервере();
Если ЗначениеЗаполнено(Роль) Тогда
Если АктивностьПользователя(ПользовательНайден)= Истина Тогда
ИзменитьНаСервере(ПользовательНайден,"КоличествоПопыток",0);
Если ВходПользователя(ПользовательНайден) = Дата("01.01.0001 0:00:00") Тогда
ОткрытьФорму("ОбщаяФорма.ФормаСменыПароля",Новый Структура("ПараметрПользователь",ПользовательНайден));
Сообщить("Необходимо сменить пароль при первом входе");
Иначе
ИзменитьНаСервере(ПользовательНайден,"ДатаВхода",ТекущаяДата());
Если Роль = ПредопределенноеЗначение("Перечисление.Роли.Админ") Тогда
ОТкрытьформу("Справочник.Пользователи.ФормаСписка");
Сообщить("Успешная авторизация");
КонецЕсли;
Если Роль = ПредопределенноеЗначение("Перечисление.Роли.Пользователь") Тогда
ОТкрытьформу("ОбщаяФорма.ФормаПользователя");
Сообщить("Успешная авторизация");
КонецЕсли;
КонецЕсли;
Иначе
ИзменитьНаСервере(ПользовательНайден,"Активность",Ложь);
Сообщить("Вы заблокированы");
КонецЕсли;
Иначе
Если(ПопыткиПользователя(ПользовательНайден)>3) Тогда
ИзменитьНаСервере(ПользовательНайден,"Активность",Ложь);
Сообщить("Вы заблокированы");
Иначе
Сообщить("Неверные данные");
КонецЕсли;
КонецЕсли;
КонецПроцедуры
&НаСервере Функция АктивностьПользователя(ПользовательНайден) Возврат ПользовательНайден.Активность; КонецФункции
&НаСервере Функция ВходПользователя(ПользовательНайден) Возврат ПользовательНайден.ДатаВхода; КонецФункции
&НаСервере Функция ПопыткиПользователя(ПользовательНайден) Возврат ПользовательНайден.КоличествоПопыток; КонецФункции
&НаСервере Процедура ЗадатьПопытки(Пользователь) Объект = Пользователь.ПолучитьОбъект(); Объект.КоличествоПопыток = Объект.КоличествоПопыток + 1; Объект.Записать(); КонецПроцедуры
&НаСервере Процедура ИзменитьНаСервере(Пользователь, Реквизит, Значение) Объект = Пользователь.ПолучитьОбъект(); Объект[Реквизит] = Значение; Объект.Записать(); КонецПроцедуры
=============================================================================================================================================================
Проверка на существующий логин:
Процедура ПередЗаписью(Отказ) ТекущийЛогин = ЭтотОбъект.Наименование; ТекущаяСсылка = ЭтотОбъект.Ссылка;
Запрос = Новый Запрос;
Запрос.Текст = "Выбрать Ссылка ИЗ Справочник.Пользователи ГДЕ Наименование = &Логин И Ссылка <> &ТекущаяСсылка";
Запрос.УстановитьПараметр("Логин",ТекущийЛогин);
Запрос.УстановитьПараметр("ТекущаяСсылка", ТекущаяСсылка);
Выборка = Запрос.Выполнить().Выбрать();
Если Выборка.Количество()>0 ТОгда
Отказ = Истина;
Сообщить("Такой логин занят");
КонецЕсли;
КонецПроцедуры
=====================================================================================================================================================================
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net8.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 |
|---|---|---|
| 4.0.0 | 126 | 4/20/2026 |