123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801 |
- ///////////////////////////////////////////////////////////////////////////////////////// MainWindows интерфейс
- <Grid>
- <Grid.RowDefinitions>
- <RowDefinition Height="100"/>
- <RowDefinition/>
- </Grid.RowDefinitions>
- <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
- <Image Source="\resources\logo.png" Height="80"/>
- <TextBlock Text="ООО «Рыбалка»" FontSize="36" HorizontalAlignment="Center" VerticalAlignment="Center"/>
- </StackPanel>
- <Frame Grid.Row="1" NavigationUIVisibility="Hidden" Name="MainFrame">
-
- </Frame>
- </Grid>
- ///////////////////////////////////////////////////////////////////////////////////////// Стили
- <Style x:Key="PageStyle" TargetType="Page">
- <Setter Property="Background" Value="White"/>
- <Setter Property="FontSize" Value="24"/>
- <Setter Property="FontFamily" Value="Comic Sans MS"/>
- </Style>
- <Style x:Key="WindowsStyle" TargetType="Window">
- <Setter Property="Background" Value="White"/>
- <Setter Property="FontSize" Value="24"/>
- <Setter Property="FontFamily" Value="Comic Sans MS"/>
- </Style>
- <Style x:Key="ButtonStyle" TargetType="Button">
- <Setter Property="Background" Value="#FF76E383"/>
- <Setter Property="Margin" Value="10"/>
- <Setter Property="Padding" Value="5"/>
- </Style>
- ///////////////////////////////////////////////////////////////////////////////////////// Код авторизации
- /////////////////////////////////////////////////////////////////////////////////////////XAML
- <Grid>
- <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
- <TextBlock Text="Авторизация" FontSize="32" HorizontalAlignment="Center"/>
- <TextBlock Text="Логин:"/>
- <TextBox Name="TBLogin"/>
- <TextBlock Text="Пароль:"/>
- <TextBox Name="TBPassword"/>
- <Button Name="BtnLogin" Style="{StaticResource ButtonStyle}" Click="BtnLogin_Click" Content="Авторизоваться"/>
- <Button Name="BtnGuest" Style="{StaticResource ButtonStyle}" Click="BtnGuest_Click" Content="Войти как гость"/>
- <Button Name="BtnRegistration" Style="{StaticResource ButtonStyle}" Click="BtnRegistration_Click" Content="Зарегистрироваться"/>
- <TextBlock x:Name="tbNewCode" FontSize="18" TextWrapping="Wrap" Visibility="Collapsed"/>
- </StackPanel>
- </Grid>
- /////////////////////////////////////////////////////////////////////////////////////////C#
- public static User user;
- public static bool correctValue;
- int kolError;
- int countTime;
- DispatcherTimer disTimer = new DispatcherTimer();
- public Login()
- {
- InitializeComponent();
- user = null;
- kolError = 0; // кол-во неудачных входов
- correctValue = false; // корректность ввода капчи
- disTimer.Interval = new TimeSpan(0, 0, 1); // интервал времени для таймера
- disTimer.Tick += new EventHandler(DisTimer_Tick);
- }
- private void BtnLogin_Click(object sender, RoutedEventArgs e)
- {
- User user1 = Base.date.User.FirstOrDefault(x => x.UserLogin == TBLogin.Text && x.UserPassword == TBPassword.Text);
- if (user1 != null)
- {
- if (kolError == 0)
- {
- FrameClass.frame.Navigate(new ListProducts());
- }
- else
- {
- correctValue = false;
- CAPCHA captcha = new CAPCHA();
- captcha.ShowDialog();
- if (correctValue) // Если капча пройдена
- {
- user = user1;
- FrameClass.frame.Navigate(new ListProducts());
- }
- }
- }
- else
- {
- MessageBox.Show("Пользователь с таким логиным и паролем не найден!");
- correctValue = false;
- CAPCHA captcha = new CAPCHA();
- captcha.ShowDialog();
- kolError++;
- if (!correctValue) // Если капча не пройдена
- {
- BtnLogin.IsEnabled = false;
- countTime = 10;
- tbNewCode.Text = "Повторно авторизоваться можно через " + countTime + " секунд";
- tbNewCode.Visibility = Visibility.Visible;
- disTimer.Start();
- }
- }
- }
- private void BtnGuest_Click(object sender, RoutedEventArgs e)
- {
- FrameClass.frame.Navigate(new ListProducts());
- }
- private void BtnRegistration_Click(object sender, RoutedEventArgs e)
- {
- FrameClass.frame.Navigate(new Registration());
- }
- private void DisTimer_Tick(object sender, EventArgs e)
- {
- if (countTime == 0) // Если 10 секунд закончились
- {
- BtnLogin.IsEnabled = true;
- disTimer.Stop();
- tbNewCode.Visibility = Visibility.Collapsed;
- }
- else
- {
- tbNewCode.Text = "Повторно авторизоваться можно через " + countTime + " секунд";
- }
- countTime--;
- }
- }
- ///////////////////////////////////////////////////////////////////////////////////////// Каптча
- ///////////////////////////////////////////////////////////////////////////////////////// XAML
- <Grid>
- <Grid.RowDefinitions>
- <RowDefinition Height="1*"/>
- <RowDefinition Height="3*"/>
- <RowDefinition Height="2*"/>
- </Grid.RowDefinitions>
- <StackPanel Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Center">
- <TextBlock Text="Подтвердите, что вы не робот введя текст с картинки в последовательности слева на право" FontSize="24" TextWrapping="Wrap" TextAlignment="Center"/>
- </StackPanel>
- <Canvas x:Name="CvField" Width="600" Height="200" Grid.Row="1">
- </Canvas>
- <StackPanel Grid.Row="2" Orientation="Vertical">
- <TextBox x:Name="tbInputField" FontSize="24" Margin="200, 10, 200, 10" MaxLength="50"/>
- <Button x:Name="BtnGo" Content="Отправить" Style="{StaticResource ButtonStyle}" Click="BtnGo_Click" HorizontalAlignment="Center" VerticalAlignment="Center"/>
- </StackPanel>
- </Grid>
- /////////////////////////////////////////////////////////////////////////////////////////C#
- public string text;
- public CAPCHA()
- {
- InitializeComponent();
- Random rand = new Random();
- int kolText = 4; // Количество символов в строке
- text = "";
- for (int i = 0; i < kolText; i++)
- {
- int j = rand.Next(2); // Выбор 0 - число; 1 - буква
- if (j == 0)
- {
- text = text + rand.Next(9).ToString();
- }
- else
- {
- text = text + (char)rand.Next('a', 'z' + 1);
- }
- }
- // Переменные для того, чтобы символы шли по порядку
- int widthBegin = 0; // Начало отрезка
- int widthEnd = 0; // Конец отрезка
- int h = (int)CvField.Width / text.Length; // Шаг разбиения
- for (int i = 0; i < text.Length; i++) // Заполнение текста
- {
- if (i == 0) // Если первое разбиение
- {
- widthEnd += h;
- }
- else
- {
- widthBegin = widthEnd;
- widthEnd += h;
- }
- int height = rand.Next((int)CvField.Height);
- int width = rand.Next(widthBegin, widthEnd);
- if (height > 170) // Чтобы не выходило за пределы поля (30 - это самое большая высота символа)
- {
- height -= 30;
- }
- if (width > 590) // Чтобы не выходило за пределы поля (10 - это самое большая длина символа)
- {
- widthEnd -= 10;
- }
- int fontSize = rand.Next(16, 33);
- TextBlock txt = new TextBlock()
- {
- Text = text[i].ToString(),
- TextDecorations = TextDecorations.Strikethrough,
- Padding = new Thickness(width, height, 0, 0),
- FontSize = fontSize,
- };
- CvField.Children.Add(txt);
- }
- int kolLine = rand.Next(5, 16); // Рандомное количество линий
- for (int i = 0; i < kolLine; i++)
- {
- SolidColorBrush brush = new SolidColorBrush(Color.FromRgb((byte)rand.Next(256), (byte)rand.Next(256), (byte)rand.Next(256))); // Рандомный RGB цвет
- Line l = new Line()
- {
- X1 = rand.Next((int)CvField.Width),
- Y1 = rand.Next((int)CvField.Height),
- X2 = rand.Next((int)CvField.Width),
- Y2 = rand.Next((int)CvField.Height),
- Stroke = brush,
- };
- CvField.Children.Add(l);
- }
- }
- private void BtnGo_Click(object sender, RoutedEventArgs e)
- {
- if (tbInputField.Text == text)
- {
- Login.correctValue = true;
- this.Close();
- }
- else
- {
- this.Close();
- }
- }
- }
- ///////////////////////////////////////////////////////////////////////////////////////// Регистрация
- public partial class Registration : Page
- {
- public Registration()
- {
- InitializeComponent();
- }
- private void BtnLogin_Click(object sender, RoutedEventArgs e)
- {
- FrameClass.frame.Navigate(new Login());
- }
- private void BtnRegistration_Click(object sender, RoutedEventArgs e)
- {
- try
- {
- if(TBSurname.Text.Replace(" ", "").Length == 0)
- {
- MessageBox.Show("Фамилия не указана");
- return;
- }
- if (TBName.Text.Replace(" ", "").Length == 0)
- {
- MessageBox.Show("Имя не указано");
- return;
- }
- if (TBPatronomic.Text.Replace(" ", "").Length == 0)
- {
- MessageBox.Show("Отчество не указано");
- return;
- }
- //Regex regex = new Regex("((?= ^[8])(.{ 11}$))| (?= ^\\+? (7))(.{ 12})$"); // Регулярное выражение для телефона
- //DateTime dateTime = new DateTime();
- //Console.WriteLine(dateTime); // 01.01.0001 0:00:00
- //Console.WriteLine(DateTime.Now); // Текущая дата и время
- //Console.WriteLine(DateTime.Today);
- //DateTime date1 = new DateTime(2015, 7, 20, 18, 30, 25); // 20.07.2015 18:30:25
- //Console.WriteLine(date1.AddHours(-3)); // 20.07.2015 15:30:25
- //public TimeSpan (int hours, int minutes, int seconds);
- //TimeSpan.FromDays(10) - TimeSpan.FromSeconds(1); // 9.23:59:59
- Regex regex = new Regex("(?=.*[0-9].*[0-9])(?=.*[a-zA-Z])(?=.*[!@#$&*])^(.{4,6})$"); // Регулярное выражение для проверки пароля (минимум 2 цифры, 1 латинская буква и один спец символ (символов от 4 до 6))
- if (regex.IsMatch(TBPassword.Text) == false)
- {
- MessageBox.Show("Пароль не соответствует требованиям");
- return;
- }
- if (Base.date.User.Where(x => x.UserLogin == TBLogin.Text).ToList().Count > 0)
- {
- MessageBox.Show("Пользователь с таким логиным уже есть");
- return;
- }
- User user = new User();
- user.UserSurname = TBSurname.Text;
- user.UserName = TBName.Text;
- user.UserPatronymic = TBPatronomic.Text;
- user.UserLogin = TBLogin.Text;
- user.UserPassword = TBPassword.Text;
- user.UserRole = 3;
- Base.date.User.Add(user);
- Base.date.SaveChanges();
- MessageBox.Show("Пользователь зарегистрирован");
- FrameClass.frame.Navigate(new Login());
- }
- catch
- {
- MessageBox.Show("При регистрации пользоватедля возникла ошибка!");
- }
- }
- }
- ///////////////////////////////////////////////////////////////////////////////////////// Список товаров
- /////////////////////////////////////////////////////////////////////////////////////////xaml
- <Page.Resources>
- <BitmapImage x:Key="DefaultImage" UriSource="../resources/picture.png"/>
- </Page.Resources>
- <Grid>
- <Grid.RowDefinitions>
- <RowDefinition Height="50"/>
- <RowDefinition Height="100"/>
- <RowDefinition/>
- <RowDefinition Height="100"/>
- </Grid.RowDefinitions>
- <Grid Grid.Row="0">
- <TextBlock x:Name="TBCountField" HorizontalAlignment="Left"/>
- <TextBlock x:Name="TBUser" HorizontalAlignment="Right"/>
- </Grid>
- <Grid Grid.Row="1">
- <Grid.ColumnDefinitions>
- <ColumnDefinition Width="2*"/>
- <ColumnDefinition Width="1*"/>
- <ColumnDefinition Width="1*"/>
- </Grid.ColumnDefinitions>
- <StackPanel Orientation="Vertical" Grid.Column="0" VerticalAlignment="Center">
- <TextBlock Text="Поиск: " HorizontalAlignment="Center"/>
- <TextBox Name="TBSearch" Margin="5" TextChanged="TBSearch_TextChanged"/>
- </StackPanel>
- <StackPanel Orientation="Vertical" Grid.Column="1" VerticalAlignment="Center">
- <TextBlock Text="Сортировка: " HorizontalAlignment="Center"/>
- <ComboBox Name="CBSort" Margin="5" SelectionChanged="CBSort_SelectionChanged">
- <ComboBoxItem Content="Без сортировки"/>
- <ComboBoxItem Content="По возрастанию стоимости"/>
- <ComboBoxItem Content="По убыванию стоимости"/>
- </ComboBox>
- </StackPanel>
- <StackPanel Orientation="Vertical" Grid.Column="2" VerticalAlignment="Center">
- <TextBlock Text="Фильтрация: " HorizontalAlignment="Center"/>
- <ComboBox Name="CBFilt" Margin="5" SelectionChanged="CBSort_SelectionChanged"/>
- </StackPanel>
- </Grid>
- <ListView Name="LVProducts" Grid.Row="2" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
- <ListView.ItemContainerStyle>
- <Style TargetType="ListViewItem">
- <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
- </Style>
- </ListView.ItemContainerStyle>
- <ListView.ItemTemplate>
- <DataTemplate>
- <Border BorderBrush="#FF76E383" BorderThickness="4" CornerRadius="10" Background="{Binding BackgroundColor}">
- <Grid>
- <Grid.ColumnDefinitions>
- <ColumnDefinition Width="200"/>
- <ColumnDefinition/>
- <ColumnDefinition Width="200"/>
- </Grid.ColumnDefinitions>
- <Image Source="{Binding ImageAbsolute, TargetNullValue={StaticResource DefaultImage}}" Width="180" HorizontalAlignment="Center"/>
- <StackPanel Grid.Column="1">
- <TextBlock Text="{Binding ProductName}" TextWrapping="Wrap" FontWeight="Bold"/>
- <TextBlock Text="{Binding ProductName}" TextWrapping="Wrap"/>
- <TextBlock Text="{Binding Manufacturers.ProductManufacturer, StringFormat={}Производитель: {0}}"/>
- <TextBlock Text="{Binding ProductCost, StringFormat={}Цена: {0}}"/>
- <StackPanel Orientation="Horizontal">
- <Button Name="BtnDelete" Uid="{Binding ProductID}" Style="{StaticResource ButtonStyle}" Content="Удалить" Click="BtnDelete_Click" Loaded="BtnDelete_Loaded"/>
- <Button Name="BtnUpdate" Uid="{Binding ProductID}" Style="{StaticResource ButtonStyle}" Content="Изменить" Click="BtnUpdate_Click" Loaded="BtnUpdate_Loaded"/>
- </StackPanel>
- </StackPanel>
- <TextBlock Text="{Binding HaveInSclad}" Grid.Column="2" TextWrapping="Wrap"/>
- </Grid>
- </Border>
- </DataTemplate>
- </ListView.ItemTemplate>
- </ListView>
- <Grid Grid.Row="3">
- <Button Name="BtnBack" Style="{StaticResource ButtonStyle}" HorizontalAlignment="Left" Content="Назад" VerticalAlignment="Center" Click="BtnBack_Click"/>
- <Button Name="BtnAdd" Style="{StaticResource ButtonStyle}" HorizontalAlignment="Center" Content="Добавить" VerticalAlignment="Center" Click="BtnAdd_Click"/>
- </Grid>
- </Grid>
- /////////////////////////////////////////////////////////////////////////////////////////c#
- public partial class ListProducts : Page
- {
- public ListProducts()
- {
- InitializeComponent();
- BtnAdd.Visibility = Visibility.Collapsed;
- if (Login.user != null)
- {
- TBUser.Text = Login.user.UserSurname + " " + Login.user.UserName + " " + Login.user.UserPatronymic;
- if (Login.user.Role.RoleName == "Администратор")
- {
- BtnAdd.Visibility = Visibility.Visible;
- }
- }
- LVProducts.ItemsSource = Base.date.Product.ToList();
- TBCountField.Text = Base.date.Product.ToList().Count + " из " + Base.date.Product.ToList().Count;
- CBSort.SelectedIndex = 0;
- List<Manufacturers> manufacturers = Base.date.Manufacturers.ToList();
- CBFilt.Items.Add("Все производители");
- foreach(Manufacturers m in manufacturers)
- {
- CBFilt.Items.Add(m.ProductManufacturer);
- }
- CBFilt.SelectedIndex = 0;
- }
- private void BtnBack_Click(object sender, RoutedEventArgs e)
- {
- FrameClass.frame.Navigate(new Login());
- }
- private void TBSearch_TextChanged(object sender, TextChangedEventArgs e)
- {
- Search();
- }
- private void CBSort_SelectionChanged(object sender, SelectionChangedEventArgs e)
- {
- Search();
- }
- private void Search()
- {
- List<Product> products = Base.date.Product.ToList();
- if(TBSearch.Text.Length > 0)
- {
- products = products.Where(x => x.ProductName.ToLower().Contains(TBSearch.Text.ToLower()) || x.ProductDescription.ToLower().Contains(TBSearch.Text.ToLower()) || x.Manufacturers.ProductManufacturer.ToLower().Contains(TBSearch.Text.ToLower())).ToList();
- }
- switch(CBSort.SelectedIndex)
- {
- case 1:
- products = products.OrderBy(x => x.ProductCost).ToList();
- break;
- case 2:
- products = products.OrderByDescending(x => x.ProductCost).ToList();
- break;
- }
- if(CBFilt.SelectedIndex > 0)
- {
- products = products.Where(x => x.Manufacturers.ProductManufacturer == CBFilt.SelectedValue).ToList();
- }
- LVProducts.ItemsSource = products;
- TBCountField.Text = products.Count + " из " + Base.date.Product.ToList().Count;
- if(products.Count == 0)
- {
- MessageBox.Show("Данные не найдены");
- }
- }
- private void BtnDelete_Click(object sender, RoutedEventArgs e)
- {
- Button button = sender as Button;
- int index = Convert.ToInt32(button.Uid);
- if(Base.date.OrderProduct.Where(x => x.ProductID == index).ToList().Count == 0)
- {
- if(MessageBox.Show("Вы точно хотите удалить товар?", "Системное сообщение", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes)
- {
- try
- {
- Product product = Base.date.Product.FirstOrDefault(x => x.ProductID == index);
- Base.date.Product.Remove(product);
- Base.date.SaveChanges();
- LVProducts.ItemsSource = Base.date.Product.ToList();
- TBCountField.Text = Base.date.Product.ToList().Count + " из " + Base.date.Product.ToList().Count;
- MessageBox.Show("Товар успешно удален");
- }
- catch
- {
- MessageBox.Show("При удаление товара возникла ошибка!");
- }
- }
- }
- else
- {
- MessageBox.Show("Товар нельзя удалить так как с ним есть заказ");
- }
- }
- private void BtnUpdate_Click(object sender, RoutedEventArgs e)
- {
- Button button = sender as Button;
- int index = Convert.ToInt32(button.Uid);
- Product product = Base.date.Product.FirstOrDefault( x => x.ProductID == index);
- FrameClass.frame.Navigate(new AddAndUpdate(product));
- }
- private void BtnAdd_Click(object sender, RoutedEventArgs e)
- {
- FrameClass.frame.Navigate(new AddAndUpdate());
- }
- private void BtnDelete_Loaded(object sender, RoutedEventArgs e)
- {
- Button button = sender as Button;
- button.Visibility = Visibility.Collapsed;
- if(Login.user != null)
- {
- if(Login.user.Role.RoleName == "Администратор")
- {
- button.Visibility = Visibility.Visible;
- }
- }
- }
- private void BtnUpdate_Loaded(object sender, RoutedEventArgs e)
- {
- Button button = sender as Button;
- button.Visibility = Visibility.Collapsed;
- if (Login.user != null)
- {
- if (Login.user.Role.RoleName == "Администратор")
- {
- button.Visibility = Visibility.Visible;
- }
- }
- }
- }
- ///////////////////////////////////////////////////////////////////////////////////////// Редактирование
- ///////////////////////////////////////////////////////////////////////////////////////// xaml
- <Grid>
- <Grid.RowDefinitions>
- <RowDefinition Height="50"/>
- <RowDefinition Height="50"/>
- <RowDefinition/>
- <RowDefinition Height="100"/>
- </Grid.RowDefinitions>
- <TextBlock x:Name="TBUser" Grid.Row="0" HorizontalAlignment="Right"/>
- <TextBlock x:Name="TBHeader" HorizontalAlignment="Center" FontSize="32" Grid.Row="1"/>
- <Grid Grid.Row="2">
- <ScrollViewer VerticalScrollBarVisibility="Auto">
- <StackPanel>
- <StackPanel Orientation="Horizontal" Margin="5">
- <StackPanel Orientation="Horizontal">
- <TextBlock Text="Наименование: "/>
- <TextBox Name="TBName" Width="300"/>
- </StackPanel>
- <StackPanel Orientation="Horizontal" Name="SPID" Visibility="Collapsed" Margin="10, 0, 0, 0">
- <TextBlock Text="ID товара: "/>
- <TextBlock Name="TBID"/>
- </StackPanel>
- </StackPanel>
- <StackPanel Orientation="Horizontal" Margin="5">
- <TextBlock Text="Категория: "/>
- <ComboBox Name="CBCategoria" Width="300"/>
- </StackPanel>
- <StackPanel Orientation="Horizontal" Margin="5">
- <TextBlock Text="Кол-во на складе: "/>
- <TextBox Name="TBCountInSclad" Width="300" PreviewTextInput="TBCountInSclad_PreviewTextInput"/>
- </StackPanel>
- <StackPanel Orientation="Horizontal" Margin="5">
- <TextBlock Text="Ед. измерения: "/>
- <ComboBox Name="CBUnit" Width="300"/>
- </StackPanel>
- <StackPanel Orientation="Horizontal" Margin="5">
- <TextBlock Text="Поставщик: "/>
- <ComboBox Name="CBSuplier" Width="300"/>
- </StackPanel>
- <StackPanel Orientation="Horizontal" Margin="5">
- <TextBlock Text="Стоимость: "/>
- <TextBox Name="TBCost" Width="300" PreviewTextInput="TBCost_PreviewTextInput"/>
- </StackPanel>
- <StackPanel Orientation="Horizontal" Margin="5">
- <TextBlock Text="Описание: "/>
- <TextBox Name="TBDescription" Width="500" Height="100" TextWrapping="Wrap" AcceptsReturn="True"/>
- </StackPanel>
- <StackPanel Orientation="Horizontal" Margin="5">
- <Image Name="IMPhoto" Height="150"/>
- <Button Name="BtnDeletePhoto" Style="{StaticResource ButtonStyle}" Content="Удалить" VerticalAlignment="Center" Click="BtnDeletePhoto_Click"/>
- <Button Name="BtnUpdPhoto" Style="{StaticResource ButtonStyle}" Content="Добавить" VerticalAlignment="Center" Click="BtnUpdPhoto_Click"/>
- </StackPanel>
- </StackPanel>
- </ScrollViewer>
- </Grid>
- <Grid Grid.Row="3">
- <Button Name="BtnBack" Style="{StaticResource ButtonStyle}" HorizontalAlignment="Left" Content="Назад" VerticalAlignment="Center" Click="BtnBack_Click"/>
- <Button Name="BtnAddAndUpdate" Style="{StaticResource ButtonStyle}" HorizontalAlignment="Center" VerticalAlignment="Center" Click="BtnAddAndUpdate_Click"/>
- </Grid>
- </Grid>
- ///////////////////////////////////////////////////////////////////////////////////////// C#
- public partial class AddAndUpdate : Page
- {
- Product product;
- bool newProduct;
- string image;
- public AddAndUpdate()
- {
- InitializeComponent();
- newProduct = true;
- BtnAddAndUpdate.Content = "Добавть";
- TBHeader.Text = "Добавление продукта";
- image = "\\resources\\picture.png";
- IMPhoto.Source = new BitmapImage(new Uri(image, UriKind.Relative));
- BtnUpdPhoto.Content = "Добавить";
- CreateField();
- }
- public AddAndUpdate(Product product)
- {
- InitializeComponent();
- newProduct = false;
- this.product = product;
- BtnAddAndUpdate.Content = "Изменить";
- TBHeader.Text = "Изменение продукта";
- SPID.Visibility = Visibility.Visible;
- TBID.Text = product.ProductID.ToString();
- CreateField();
- if(product.ProductPhoto != null)
- {
- image = product.ProductPhoto;
- IMPhoto.Source = new BitmapImage(new Uri(Directory.GetParent(Environment.CurrentDirectory).Parent.FullName + image));
- BtnUpdPhoto.Content = "Изменить";
- }
- else
- {
- image = "\\resources\\picture.png";
- IMPhoto.Source = new BitmapImage(new Uri(image, UriKind.Relative));
- BtnUpdPhoto.Content = "Добавить";
- }
- TBName.Text = product.ProductName;
- TBDescription.Text = product.ProductDescription;
- CBCategoria.SelectedIndex = product.Categorys.ProductCategoryID - 1;
- CBUnit.SelectedIndex = product.Units.ProductUnitID - 1;
- CBSuplier.SelectedIndex = product.Supliers.ProductSuplierID - 1;
- TBCountInSclad.Text = product.ProductQuantityInStock.ToString();
- TBCost.Text = product.ProductCost.ToString();
- }
- private void CreateField()
- {
- CBCategoria.ItemsSource = Base.date.Categorys.ToList();
- CBCategoria.SelectedValuePath = "ProductCategoryID";
- CBCategoria.DisplayMemberPath = "ProductCategory";
- CBUnit.ItemsSource = Base.date.Units.ToList();
- CBUnit.SelectedValuePath = "ProductUnitID";
- CBUnit.DisplayMemberPath = "ProductUnit";
- CBSuplier.ItemsSource = Base.date.Supliers.ToList();
- CBSuplier.SelectedValuePath = "ProductSuplierID";
- CBSuplier.DisplayMemberPath = "ProductSuplier";
- }
- private void BtnBack_Click(object sender, RoutedEventArgs e)
- {
- FrameClass.frame.Navigate(new ListProducts());
- }
- private void BtnAddAndUpdate_Click(object sender, RoutedEventArgs e)
- {
- try
- {
- if (newProduct)
- {
- product = new Product();
- product.ProductID = Base.date.Product.Max(x => x.ProductID) + 1;
- }
- product.ProductName = TBName.Text;
- product.ProductCategoryID = CBCategoria.SelectedIndex + 1;
- product.ProductUnitID = CBUnit.SelectedIndex + 1;
- product.ProductSuplierID = CBSuplier.SelectedIndex + 1;
- product.ProductQuantityInStock = Convert.ToInt32(TBCountInSclad.Text);
- product.ProductCost = Convert.ToDouble(TBCost.Text);
- product.ProductDescription = TBDescription.Text;
- if (image == "\\resources\\picture.png")
- {
- product.ProductPhoto = null;
- }
- else
- {
- product.ProductPhoto = image;
- }
- if(newProduct)
- {
- Base.date.Product.Add(product);
- }
- Base.date.SaveChanges();
- if (newProduct)
- {
- MessageBox.Show("Товар успешно добавлен");
- }
- else
- {
- MessageBox.Show("Товар успешно изменен");
- }
- FrameClass.frame.Navigate(new ListProducts());
- }
- catch
- {
- if(newProduct)
- {
- MessageBox.Show("При добавление товара возникла ошибка");
- }
- else
- {
- MessageBox.Show("При изменение товара возникла ошибка");
- }
- }
- }
- private void TBCountInSclad_PreviewTextInput(object sender, TextCompositionEventArgs e)
- {
- if(!(Char.IsDigit(e.Text, 0)))
- {
- e.Handled = true;
- }
- }
- private void TBCost_PreviewTextInput(object sender, TextCompositionEventArgs e)
- {
- if (!(Char.IsDigit(e.Text, 0)) && (e.Text != ","))
- {
- e.Handled = true;
- }
- }
- private void BtnDeletePhoto_Click(object sender, RoutedEventArgs e)
- {
- image = "\\resources\\picture.png";
- IMPhoto.Source = new BitmapImage(new Uri(image, UriKind.Relative));
- BtnUpdPhoto.Content = "Добавить";
- }
- private void BtnUpdPhoto_Click(object sender, RoutedEventArgs e)
- {
- try
- {
- string path;
- OpenFileDialog openFileDialog = new OpenFileDialog();
- openFileDialog.ShowDialog();
- path = openFileDialog.FileName;
- if(path != null)
- {
- string newFilePath = Directory.GetParent(Environment.CurrentDirectory).Parent.FullName + "\\image\\" + System.IO.Path.GetFileName(path); // Путь куда копировать файл
- if (!File.Exists(newFilePath)) // Проверка наличия картинки в папке
- {
- File.Copy(path, newFilePath);
- }
- image = "\\image\\" + System.IO.Path.GetFileName(path);
- IMPhoto.Source = new BitmapImage(new Uri(Directory.GetParent(Environment.CurrentDirectory).Parent.FullName + image));
- BtnUpdPhoto.Content = "Изменить";
- }
- }
- catch
- {
- MessageBox.Show("При добавлении нового фото возникла ошибка!");
- }
- }
- }
- ///////////////////////////////////////////////////////////////////////////////////////// Частичный класс
- public string HaveInSclad
- {
- get
- {
- if(ProductQuantityInStock > 0)
- {
- return "Товар есть на складе";
- }
- return "Товар отсутствует";
- }
- }
- public SolidColorBrush BackgroundColor
- {
- get
- {
- if (ProductQuantityInStock > 0)
- {
- return Brushes.White;
- }
- return Brushes.Gray;
- }
- }
- public string ImageAbsolute
- {
- get
- {
- if(ProductPhoto == null)
- {
- return null;
- }
- else
- {
- return Directory.GetParent(Environment.CurrentDirectory).Parent.FullName + ProductPhoto;
- }
- }
- }
- ///////////////////////////////////////////////////////////////////////////////////////// Прочее
- DateTime dateTime = new DateTime();
- Console.WriteLine(dateTime); // 01.01.0001 0:00:00
- Console.WriteLine(DateTime.Now); // Текущая дата и время
- Console.WriteLine(DateTime.Today);
- DateTime date1 = new DateTime(2015, 7, 20, 18, 30, 25); // 20.07.2015 18:30:25
- Console.WriteLine(date1.AddHours(-3)); // 20.07.2015 15:30:25
- public TimeSpan (int hours, int minutes, int seconds);
- TimeSpan.FromDays(10) - TimeSpan.FromSeconds(1); // 9.23:59:59
- Regex regex = new Regex("(?=.*[0-9].*[0-9])(?=.*[a-zA-Z])(?=.*[!@#$&*])^(.{4,6})$"); // Регулярное выражение для проверки пароля (минимум 2 цифры, 1 латинская буква и один спец символ (символов от 4 до 6))
- Regex regex = new Regex("((?= ^[8])(.{ 11}$))| (?= ^\\+? (7))(.{ 12})$"); // Регулярное выражение для телефона
|