Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public async Task EditTable(string TableName)
- {
- var db = new SqlConnection(connectionString);
- await db.OpenAsync();
- await db.QueryAsync($"DROP TABLE IF EXISTS [{TableName}_COPY]");
- await db.QueryAsync($"DROP TABLE IF EXISTS [USUMODEl{TableName}_COPY]");
- await db.QueryAsync($"Drop TABLE IF EXISTS [SPS_COPY]");
- await db.QueryAsync($"SELECT * INTO [{TableName + "_COPY"}] FROM [{TableName}];");
- await db.QueryAsync($"SELECT * INTO [{"USUMODEL" + TableName + "_COPY"}] FROM [{"USUMODEL" + TableName}];");
- await db.QueryAsync($"SELECT * INTO [SPS_COPY] FROM [SPS];");
- transitioner = new Transitioner { AutoApplyTransitionOrigins = true, SelectedIndex = 0, Height = 400, Width = 700, FocusVisualStyle = null };
- TransitionerSlide SlideMain = new TransitionerSlide { ForwardWipe = new SlideOutWipe(), FocusVisualStyle = null };
- transitioner.Items.Add(SlideMain);
- TransitionerSlide SlideConfig = new TransitionerSlide { BackwardWipe = new CircleWipe(), FocusVisualStyle = null };
- transitioner.Items.Add(SlideConfig);
- #region Childrens
- Grid DialogGrid = new Grid { VerticalAlignment = VerticalAlignment.Stretch, HorizontalAlignment = HorizontalAlignment.Stretch, Focusable = false, Background = (Brush)FindResource("MaterialDesignTextFieldBoxBackground") };
- ScrollViewer scrollViewer = new ScrollViewer { Margin = new Thickness(0, 45, 0, 75), VerticalAlignment = VerticalAlignment.Stretch, HorizontalAlignment = HorizontalAlignment.Stretch, Focusable = false };
- DialogGrid.Children.Add(scrollViewer);
- Card border = new Card { Background = Brushes.White, UniformCornerRadius = 20, Height = 80, HorizontalAlignment = HorizontalAlignment.Stretch, VerticalAlignment = VerticalAlignment.Bottom, Margin = new Thickness(0, 0, 0, -20) };
- DialogGrid.Children.Add(border);
- Button AddColumn = new Button
- {
- HorizontalAlignment = HorizontalAlignment.Center,
- VerticalAlignment = VerticalAlignment.Bottom,
- Margin = new Thickness(0, 0, 0, 30),
- FocusVisualStyle = null,
- Content = new PackIcon { Kind = PackIconKind.Add, Foreground = Brushes.Black, Height = 25, Width = 25 },
- Style = (Style)FindResource("MaterialDesignFloatingActionButton")
- };
- DialogGrid.Children.Add(AddColumn);
- Button OK = new Button
- {
- Content = "OK",
- VerticalAlignment = VerticalAlignment.Bottom,
- HorizontalAlignment = HorizontalAlignment.Right,
- Margin = new Thickness(0, 0, 100, 10),
- FocusVisualStyle = null,
- Height = 40,
- Style = (Style)FindResource("MaterialDesignFlatButton"),
- Command = DialogHost.CloseDialogCommand
- };
- DialogGrid.Children.Add(OK);
- Button Cancel = new Button
- {
- Content = "Отмена",
- VerticalAlignment = VerticalAlignment.Bottom,
- HorizontalAlignment = HorizontalAlignment.Right,
- Margin = new Thickness(0, 0, 15, 10),
- Focusable = false,
- Height = 40,
- Style = (Style)FindResource("MaterialDesignFlatButton"),
- Command = DialogHost.CloseDialogCommand
- };
- DialogGrid.Children.Add(Cancel);
- #endregion
- {
- DialogGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
- DialogGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(200, GridUnitType.Pixel) });
- DialogGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(120, GridUnitType.Pixel) });
- }
- #region Заголовок
- {
- TextBlock Column = new TextBlock { VerticalAlignment = VerticalAlignment.Top, HorizontalAlignment = HorizontalAlignment.Center, Margin = new Thickness(0, 10, 0, 0), Text = "Имя столбца" };
- Column.SetValue(Grid.ColumnProperty, 0);
- Column.SetResourceReference(TextBlock.StyleProperty, "MaterialDesignHeadline5TextBlock");
- DialogGrid.Children.Add(Column);
- }
- {
- TextBlock Column = new TextBlock { VerticalAlignment = VerticalAlignment.Top, HorizontalAlignment = HorizontalAlignment.Center, Margin = new Thickness(0, 10, 0, 0), Text = "Тип данных" };
- Column.SetValue(Grid.ColumnProperty, 1);
- Column.SetResourceReference(TextBlock.StyleProperty, "MaterialDesignHeadline5TextBlock");
- DialogGrid.Children.Add(Column);
- }
- #endregion
- #region Scroll
- scrollViewer.SetValue(Grid.ColumnSpanProperty, 3);
- StackPanel scrollStack = new StackPanel { VerticalAlignment = VerticalAlignment.Stretch, HorizontalAlignment = HorizontalAlignment.Stretch, Focusable = false, Orientation = Orientation.Vertical, Margin = new Thickness(0, 10, 0, 0) };
- scrollViewer.Content = scrollStack;
- foreach (var el in (await db.QueryAsync($"SELECT * FROM [USUMODEL{TableName}] ORDER BY [Порядковый номер] ASC ")).Select(b => (IDictionary<string, object>)b).ToList())
- {
- scrollStack.Children.Add(await AddColumnInColumns(el["Имя столбца"].ToString()));
- }
- #endregion
- #region NavBar
- border.SetValue(Grid.ColumnSpanProperty, 3);
- Panel.SetZIndex(border, 1001);
- #endregion
- #region Add
- AddColumn.SetValue(Grid.ColumnSpanProperty, 3);
- Panel.SetZIndex(AddColumn, 1002);
- AddColumn.Click += async (sender, e) =>
- {
- await db.OpenAsync();
- try
- {
- db.Query($"ALTER TABLE [{TableName + "_COPY"}] ADD [ ] NVARCHAR(MAX) NULL;");
- int max;
- if (db.Query<string>($"SELECT MAX([Порядковый номер]) FROM [{"USUMODEL" + TableName + "_COPY"}]").First() != null)
- {
- max = db.Query<int>($"SELECT MAX([Порядковый номер]) FROM [{"USUMODEL" + TableName + "_COPY"}]").First() + 1;
- }
- else
- {
- max = 0;
- }
- db.Query($"INSERT [USUMODEL{TableName}_COPY] ([Порядковый номер],[Имя столбца],[Тип данных],[Конфигурация],[IsType],[IsDelete]) VALUES ({max},N' ',N'Строка',N'',1,1);");
- scrollStack.Children.Add(await AddColumnInColumns(" "));
- OK.IsEnabled = false;
- }
- catch { }
- db.Close();
- };
- #endregion
- #region OK
- OK.SetValue(ButtonAssist.CornerRadiusProperty, new CornerRadius(20));
- OK.SetValue(Grid.ColumnSpanProperty, 3);
- Panel.SetZIndex(OK, 1002);
- OK.Click += (object sender, RoutedEventArgs e) =>
- {
- db.Open();
- int j = 1;
- foreach (Grid el in scrollStack.Children)
- {
- db.Query($"UPDATE [USUMODEL{TableName}_COPY] SET [Порядковый номер] = {j} WHERE [Имя столбца] = N'{((TextBox)el.Children[1]).Text}'");
- j++;
- el.Height += 1;
- }
- db.Query($"Drop TABLE[{TableName}]");
- db.Query($"EXEC sp_rename N'{TableName}_COPY', N'{TableName}'");
- db.Query($"Drop TABLE[USUMODEL{TableName}]");
- db.Query($"EXEC sp_rename N'USUMODEL{TableName}_COPY', N'USUMODEL{TableName}'");
- db.Query($"Drop TABLE[SPS]");
- db.Query($"EXEC sp_rename 'SPS_COPY', 'SPS'");
- db.Close();
- MenuOfTable.Visibility = Visibility.Hidden;
- dataGrid.Visibility = Visibility.Hidden;
- if ((TreeViewItem)TreeView.SelectedItem != null)
- {
- ((TreeViewItem)TreeView.SelectedItem).IsSelected = false;
- }
- };
- #endregion
- #region Cancel
- Cancel.SetValue(ButtonAssist.CornerRadiusProperty, new CornerRadius(20));
- Cancel.SetValue(Grid.ColumnSpanProperty, 3);
- Panel.SetZIndex(Cancel, 1002);
- Cancel.Click += (object sender, RoutedEventArgs e) =>
- {
- db.Open();
- db.Query($"Drop TABLE[{TableName + "_COPY"}]");
- db.Query($"Drop TABLE[{"USUMODEL" + TableName + "_COPY"}]");
- db.Query($"Drop TABLE IF EXISTS [SPS_COPY]");
- db.Close();
- };
- #endregion
- SlideMain.Content = DialogGrid;
- await DialogHost.ShowDialog(transitioner);
- async Task<Grid> AddColumnInColumns(string ColumnName)
- {
- db = new SqlConnection(connectionString);
- await db.OpenAsync();
- string Name = ColumnName;
- Grid Column = new Grid { Height = 45, Margin = new Thickness(0, -15, 0, 15), VerticalAlignment = VerticalAlignment.Top, HorizontalAlignment = HorizontalAlignment.Stretch };
- Column.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(30, GridUnitType.Pixel) });
- Column.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
- Column.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(150, GridUnitType.Pixel) });
- Column.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(45, GridUnitType.Pixel) });
- Column.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(45, GridUnitType.Pixel) });
- int counter = 0;
- #region Drag and Drop
- double y = 0;
- Button DragDrop = new Button
- {
- Height = 25,
- FocusVisualStyle = null,
- BorderBrush = Brushes.Transparent,
- Background = Brushes.Transparent,
- Content = new PackIcon { Kind = PackIconKind.DragHorizontal, Foreground = Brushes.Black, Width = 25, Height = 25 },
- HorizontalAlignment = HorizontalAlignment.Center,
- VerticalAlignment = VerticalAlignment.Bottom,
- Margin = new Thickness(5, 0, 0, 0),
- Style = (Style)FindResource("MaterialDesignFloatingActionMiniButton")
- };
- DragDrop.SetValue(Grid.ColumnProperty, counter);
- #region drag
- DragDrop.PreviewMouseLeftButtonDown += (object sender, MouseButtonEventArgs e) =>
- {
- y = e.GetPosition(null).Y;
- DragDrop.PreviewMouseMove += DragDrop_MouseMove;
- };
- DragDrop.PreviewMouseLeftButtonUp += (object sender, MouseButtonEventArgs e) =>
- {
- DragDrop.PreviewMouseMove -= DragDrop_MouseMove;
- };
- void DragDrop_MouseMove(object sender1, System.Windows.Input.MouseEventArgs e1)
- {
- double mousey = e1.GetPosition(null).Y;
- int pos = scrollStack.Children.IndexOf(Column);
- if (mousey < y - 45)
- {
- if (pos - 1 >= 0)
- {
- scrollStack.Children.Remove(Column);
- scrollStack.Children.Insert(pos - 1, Column);
- y = e1.GetPosition(null).Y;
- }
- }
- else if (mousey > y + 45)
- {
- if (scrollStack.Children.Count > pos + 1)
- {
- scrollStack.Children.Remove(Column);
- scrollStack.Children.Insert(pos + 1, Column);
- y = e1.GetPosition(null).Y;
- }
- }
- if (pos != scrollStack.Children.IndexOf(Column))
- {
- using (IDbConnection Db = new SqlConnection(connectionString))
- {
- string id1 = Db.Query<string>($"SELECT [Id] FROM [SPS_COPY] WHERE [KEY] LIKE N'{TableName}%' AND [VALUE] LIKE N'{pos + 1}'").FirstOrDefault();
- string id2 = Db.Query<string>($"SELECT [Id] FROM [SPS_COPY] WHERE [KEY] LIKE N'{TableName}%' AND [VALUE] LIKE N'{scrollStack.Children.IndexOf(Column) + 1}'").FirstOrDefault();
- Db.Query($"UPDATE [SPS_COPY] SET [VALUE] = N'{scrollStack.Children.IndexOf(Column) + 1}' WHERE [Id] = N'{id1}'");
- Db.Query($"UPDATE [SPS_COPY] SET [VALUE] = N'{pos + 1}' WHERE [Id] = N'{id2}'");
- }
- }
- }
- #endregion
- Column.Children.Add(DragDrop);
- counter++;
- #endregion
- #region Имя Столбца
- TextBox NameColumn = new TextBox
- {
- Height = 45,
- HorizontalAlignment = HorizontalAlignment.Stretch,
- VerticalContentAlignment = VerticalAlignment.Bottom,
- Margin = new Thickness(5, 0, 5, 0),
- Style = (Style)FindResource("MaterialDesignFloatingHintTextBox"),
- Text = " "
- };
- NameColumn.SetValue(Grid.ColumnProperty, counter);
- #region changed
- NameColumn.TextChanged += (sender, e) =>
- {
- db.Close();
- db.Open();
- if (NameColumn.Text.Trim() != string.Empty)
- {
- try
- {
- db.Query($"EXEC sp_rename N'{TableName + "_COPY"}.[{ColumnName}]', N'{NameColumn.Text}', 'COLUMN';");
- db.Query($"UPDATE [{"USUMODEL" + TableName + "_COPY"}] SET [Имя столбца] = N'{NameColumn.Text}' WHERE [Имя столбца] = N'{ColumnName}'");
- ColumnName = NameColumn.Text;
- NameColumn.SetValue(HintAssist.HelperTextProperty, "");
- }
- catch
- {
- NameColumn.SetValue(HintAssist.HelperTextProperty, "Столбец с таким названием уже есть");
- }
- }
- else
- {
- NameColumn.SetValue(HintAssist.HelperTextProperty, "Введите название столбца");
- }
- OK.IsEnabled = true;
- foreach (TextBox text in scrollStack.Children.Cast<Grid>().Select(b => b.Children[1]))
- {
- if (!(text.GetValue(HintAssist.HelperTextProperty) == "" || text.GetValue(HintAssist.HelperTextProperty) == null))
- {
- OK.IsEnabled = false;
- break;
- }
- }
- db.Close();
- };
- NameColumn.Text = ColumnName.Trim();
- NameColumn.LostFocus += (object sender, RoutedEventArgs e) =>
- {
- if (NameColumn.GetValue(HintAssist.HelperTextProperty) == "Столбец с таким названием уже есть" && NameColumn.IsFocused == false)
- {
- Dispatcher.BeginInvoke((ThreadStart)delegate
- {
- NameColumn.Focus();
- });
- }
- };
- #endregion
- Column.Children.Add(NameColumn);
- counter++;
- #endregion
- #region Тип данных
- ComboBox TypeColumn = new ComboBox
- {
- VerticalAlignment = VerticalAlignment.Bottom,
- HorizontalAlignment = HorizontalAlignment.Stretch,
- ItemsSource = TypeToTypeDb.Keys.ToList(),
- Margin = new Thickness(5, 0, 5, 0),
- IsEnabled = db.Query<bool>($"SELECT [IsType] FROM [USUMODEL{TableName}_COPY] WHERE [Имя столбца] = N'{ColumnName}'").First()
- };
- TypeColumn.SetValue(Grid.ColumnProperty, counter);
- try { TypeColumn.SelectedValue = db.QueryAsync<string>($"SELECT [Тип данных] FROM [USUMODEL{TableName}_COPY] WHERE [Имя столбца] = N'{ColumnName}'").Result.First(); }
- catch { TypeColumn.SelectedValue = TypeToTypeDb.Keys.ToList()[0]; }
- TypeColumn.SelectionChanged += (object sender, SelectionChangedEventArgs e1) =>
- {
- Grid MessageGrid = new Grid { Height = 180, Width = 470 };
- {
- TextBlock Header = new TextBlock
- {
- VerticalAlignment = VerticalAlignment.Top,
- Margin = new Thickness(15, 10, 15, 0),
- Text = "Измениние типа данных"
- };
- Header.SetResourceReference(StyleProperty, "MaterialDesignHeadline5TextBlock");
- MessageGrid.Children.Add(Header);
- }//Header
- {
- StackPanel stackPanel = new StackPanel
- {
- Orientation = Orientation.Horizontal,
- Margin = new Thickness(10, 7, 01, 7),
- Background = Brushes.Transparent
- };
- PackIcon icon = new PackIcon
- {
- Kind = PackIconKind.Alert,
- Foreground = Brushes.Red,
- Width = 22,
- Height = 22,
- Margin = new Thickness(5, 0, 5, 0),
- VerticalAlignment = VerticalAlignment.Center
- };
- stackPanel.Children.Add(icon);
- TextBlock text = new TextBlock
- {
- Foreground = Brushes.Red,
- VerticalAlignment = VerticalAlignment.Center,
- Text = "Измениние типа данных приводит к очищению всего столбца"
- };
- stackPanel.Children.Add(text);
- ColorZone colorZone = new ColorZone
- {
- Margin = new Thickness(15, 50, 15, 0),
- VerticalAlignment = VerticalAlignment.Top,
- Content = stackPanel,
- Background = new SolidColorBrush(Color.FromArgb(100, 250, 231, 231))
- };
- MessageGrid.Children.Add(colorZone);
- }//Warning
- {
- TextBlock textBlock = new TextBlock
- {
- VerticalAlignment = VerticalAlignment.Top,
- Margin = new Thickness(15, 100, 15, 0),
- Text = "Подвердить операцию?"
- };
- textBlock.SetResourceReference(StyleProperty, "MaterialDesignTextBlock");
- MessageGrid.Children.Add(textBlock);
- }//Question
- {
- Button ok = new Button
- {
- Content = "Да",
- VerticalAlignment = VerticalAlignment.Bottom,
- HorizontalAlignment = HorizontalAlignment.Right,
- Margin = new Thickness(0, 0, 75, 15),
- Focusable = false,
- Command = DialogHost.CloseDialogCommand,
- Style = (Style)FindResource("MaterialDesignFlatButton")
- };
- ok.SetValue(Grid.ColumnSpanProperty, 3);
- ok.Click += (object sender1, RoutedEventArgs e) =>
- {
- using (IDbConnection Db = new SqlConnection(connectionString))
- {
- Db.Query($"ALTER TABLE [{TableName + "_COPY"}] DROP COLUMN [{ColumnName}]");
- ComboBox comboBox = (ComboBox)sender;
- Button button = (Button)((Grid)comboBox.Parent).Children[3];
- switch (comboBox.SelectedItem)
- {
- case "Целое число":
- case "Дробное число":
- case "Строка":
- button.IsEnabled = true;
- break;
- case "Процент":
- case "Дата":
- case "Время":
- case "Фото":
- button.IsEnabled = false;
- break;
- }
- string str = $"ALTER TABLE [{TableName}_COPY] ADD [{ColumnName}] {TypeToTypeDb.Where(b => b.Key == comboBox.SelectedItem.ToString()).Select(b => b.Value).First()}";
- Db.Query(str);
- Db.Query($"UPDATE [USUMODEL{TableName}_COPY] SET [Тип данных] = N'{comboBox.SelectedItem}', [Конфигурация] = N'' WHERE [Имя столбца] = N'{ColumnName}'");
- }
- };
- MessageGrid.Children.Add(ok);
- }//OK
- {
- Button cancel = new Button
- {
- Content = "Нет",
- VerticalAlignment = VerticalAlignment.Bottom,
- HorizontalAlignment = HorizontalAlignment.Right,
- Margin = new Thickness(0, 0, 15, 15),
- Command = DialogHost.CloseDialogCommand,
- Focusable = false,
- Style = (Style)FindResource("MaterialDesignFlatButton")
- };
- cancel.SetValue(Grid.ColumnSpanProperty, 3);
- MessageGrid.Children.Add(cancel);
- }//CANCEL
- {
- DialogHost Host = new DialogHost { VerticalAlignment = VerticalAlignment.Stretch, IsManipulationEnabled = true };
- Host.SetResourceReference(StyleProperty, "MaterialDesignEmbeddedDialogHost");
- Host.SetValue(Grid.ColumnSpanProperty, 3);
- Host.SetValue(Grid.RowSpanProperty, 2);
- Host.SetValue(Panel.ZIndexProperty, 2000);
- grid.Children.Add(Host);
- Host.ShowDialog(MessageGrid);
- }//DialogHost
- };
- Column.Children.Add(TypeColumn);
- counter++;
- #endregion
- #region Конфигурация
- Button Configuration = new Button
- {
- VerticalAlignment = VerticalAlignment.Bottom,
- HorizontalAlignment = HorizontalAlignment.Center,
- Width = 40,
- Height = 40,
- Content = new PackIcon { Kind = PackIconKind.Tune, Foreground = Brushes.Black },
- Command = Transitioner.MoveNextCommand,
- FocusVisualStyle = null,
- Style = (Style)FindResource("MaterialDesignIconForegroundButton"),
- };
- Configuration.SetValue(Grid.ColumnProperty, counter);
- Configuration.Click += (object sender, RoutedEventArgs e) =>
- {
- SlideConfig.Content = EditConfigOfColumn(TableName, ColumnName);
- };
- Column.Children.Add(Configuration);
- counter++;
- #endregion
- #region Удаление
- Button Delete = new Button
- {
- VerticalAlignment = VerticalAlignment.Bottom,
- HorizontalAlignment = HorizontalAlignment.Center,
- Width = 40,
- Height = 40,
- Focusable = false,
- Content = new PackIcon { Kind = PackIconKind.Delete, Foreground = Brushes.Black },
- IsEnabled = db.Query<bool>($"SELECT [IsDelete] FROM [USUMODEL{TableName}_COPY] WHERE [Имя столбца] = N'{ColumnName}'").First(),
- Style = (Style)FindResource("MaterialDesignIconForegroundButton")
- };
- Delete.SetValue(Grid.ColumnProperty, counter);
- Delete.Click += (object sender, RoutedEventArgs e) =>
- {
- db.Open();
- db.Query($"ALTER TABLE [{TableName + "_COPY"}] DROP COLUMN [{ColumnName}]");
- db.Query($"DELETE FROM [{"USUMODEL" + TableName + "_COPY"}] WHERE [Имя столбца] = N'{ColumnName}'; ");
- scrollStack.Children.Remove(Column);
- OK.IsEnabled = true;
- foreach (Grid el in scrollStack.Children)
- {
- TextBox text = (TextBox)el.Children[1];
- if (!(text.GetValue(HintAssist.HelperTextProperty) == "" || text.GetValue(HintAssist.HelperTextProperty) == null))
- {
- OK.IsEnabled = false;
- break;
- }
- }
- db.Close();
- };
- Column.Children.Add(Delete);
- counter++;
- #endregion
- db.Close();
- Column.SizeChanged += (object sender, SizeChangedEventArgs e) =>
- {
- foreach (string USUMODELTABLE in db.Query<string>("SELECT [TABLE_NAME] FROM INFORMATION_SCHEMA.TABLES WHERE [TABLE_NAME] LIKE N'USUMODEL%'").ToList())
- {
- foreach (IDictionary<string, object> Configurat in db.Query($"SELECT * FROM [{USUMODELTABLE}] WHERE [Конфигурация] LIKE N'%Таблица:{TableName};%Столбец:{Name};%'").ToList().Select(b => (IDictionary<string, object>)b))
- {
- db.Query($"UPDATE [{USUMODELTABLE}] SET [Конфигурация] = N'{Configurat["Конфигурация"].ToString().Replace($"Столбец:{Name};", $"Столбец:{NameColumn.Text};")}' WHERE [Id] = N'{Configurat["Id"]}'");
- }
- }
- };
- return Column;
- }
- db.Close();
- }
Advertisement
Add Comment
Please, Sign In to add comment