Free cookie consent management tool by TermsFeed Policy Generator

source: branches/OKB/HeuristicLab.OKB.Cockpit.Admin/TableView.xaml.cs @ 4311

Last change on this file since 4311 was 4311, checked in by swagner, 14 years ago

Integrated OKB clients for HL 3.3 (#1166)

File size: 7.0 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using System.Windows.Controls;
6using HeuristicLab.BackgroundProcessing;
7using System.Windows;
8using System.IO.Compression;
9using System.IO;
10using HeuristicLab.MainForm.WPF;
11using HeuristicLab.MainForm;
12using System.ComponentModel;
13using System.Data;
14using System.Windows.Data;
15using Microsoft.Windows.Controls;
16using HeuristicLab.OKB.Client;
17using HeuristicLab.OKB.Cockpit.Admin.OKBTables;
18
19namespace HeuristicLab.OKB.Cockpit.Admin {
20
21  public partial class TableView : UserControl, IView, IOKBCockpitItem {
22
23    static DependencyProperty TableNameProperty =
24      DependencyProperty.Register("TableName", typeof(string), typeof(TableView),
25      new PropertyMetadata("<no table>"));
26
27    private DataTable table;
28    private Dictionary<string, DataTable> foreignKeys;
29
30    public TableView() {
31      InitializeComponent();
32      Data.Items.Clear();
33      Data.Columns.Clear();
34    }
35
36    public string TableName {
37      get {
38        return (string)GetValue(TableNameProperty);
39      }
40      set {
41        SetValue(TableNameProperty, value);
42      }
43    }
44
45    protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e) {
46      base.OnPropertyChanged(e);
47      if (e.Property == TableNameProperty) {
48        if (CaptionChanged != null)
49          CaptionChanged(this, new EventArgs());
50        OnLoad(this, new EventArgs());
51      }
52    }
53
54    #region IView Members
55
56    public string Caption {
57      get { return "Table View: " + TableName; }
58      set { throw new NotSupportedException(); }
59    }
60    public event EventHandler CaptionChanged;
61    public event EventHandler Changed;
62    public virtual void Close() {
63      MainFormManager.GetMainForm<WPFMainFormBase>().CloseView(this);
64      IsShown = false;
65    }
66
67    public void Hide() {
68      MainFormManager.GetMainForm<WPFMainFormBase>().HideView(this);
69      IsShown = false;
70    }
71
72    public bool IsShown { get; protected set; }
73
74    private bool readOnly = false;
75    public bool ReadOnly {
76      get {
77        return readOnly;
78      }
79      set {
80        if (value == readOnly) return;
81        readOnly = value;
82        OnReadOnlyChanged();
83      }
84    }
85    public event EventHandler ReadOnlyChanged;
86    protected void OnReadOnlyChanged() {
87      EventHandler handler = ReadOnlyChanged;
88      if (handler != null)
89        handler(this, EventArgs.Empty);
90    }
91
92    public void Show() {
93      MainFormManager.GetMainForm<WPFMainFormBase>().ShowView(this);
94      IsShown = true;
95    }
96
97
98    #endregion
99
100    protected void OnLoad(object sender, EventArgs args) {
101      if (TableName == null) {
102        MessageBox.Show("No table name given", Caption);
103        return;
104      }
105      var loader = new TableLoadWorker(TableName, true);
106      loader.RunWorkerCompleted += (s, a) => {
107        if (loader.Table == null) {
108          MessageBox.Show("Table loading failed", Caption);
109          return;
110        }
111        foreignKeys = loader.ForeignKeys;
112        table = loader.Table;
113        table.AcceptChanges();
114        Data.ItemsSource = null;
115        Data.Items.Clear();
116        Data.Columns.Clear();
117        Data.DataContext = table;
118        Data.SetBinding(DataGrid.ItemsSourceProperty, new Binding());
119        Data.ContextMenu = null;
120        if (table.TableName == "Algorithm" || table.TableName == "Problem") {
121          MenuItem edit = new MenuItem() { Header = "Edit Operator Graph" };
122          edit.Click += OnEditOperatorGraphClicked;
123          Data.ContextMenu = new ContextMenu();
124          Data.ContextMenu.Items.Add(edit);
125        }
126      };
127      loader.RunWorkerAsync(TableName);
128    }
129
130    private string DataRowValueToString(object o) {
131      if (o == DBNull.Value)
132        return null;
133      return o as string;
134    }
135
136    protected void OnEditOperatorGraphClicked(object sender, RoutedEventArgs args) {
137      if (Data.SelectedCells.Count == 0)
138        return;
139      DataRowView view = Data.SelectedCells.First().Item as DataRowView;
140      if (view == null)
141        return;
142      DataRow row = view.Row;
143      if (row["Id"] == DBNull.Value) {
144        MessageBox.Show(string.Format("Cannot edit newly created {0} as it has no id yet."
145          + Environment.NewLine +
146          "upload your changes to the database first", table.TableName), Caption, MessageBoxButton.OK, MessageBoxImage.Error);
147        return;
148      }
149      if (table.TableName == "Problem")
150        MainFormManager.GetMainForm<CockpitMainWindow>().ShowView(new ProblemEditor() {
151          Problem = new OKBAdmin.Problem() {
152            Id = (int)row["Id"],
153            Name = (string)row["Name"],
154            Description = DataRowValueToString(row["Description"]),
155          }
156        });
157      else if (table.TableName == "Algorithm")
158        MainFormManager.GetMainForm<CockpitMainWindow>().ShowView(new AlgorithmEditor() {
159          Algorithm = new OKBAdmin.Algorithm() {
160            Id = (int)row["Id"],
161            Name = (string)row["Name"],
162            Description = DataRowValueToString(row["Description"]),
163          }
164        });
165    }
166
167    protected void OnSave(object sender, EventArgs args) {
168      var saver = new ObservableBackgroundWorker("uploading changes");
169      DataTable updatedRows = table.GetChanges(DataRowState.Added | DataRowState.Modified);
170      DataTable deletedRows = table.GetChanges(DataRowState.Deleted);
171      bool success = false;
172      saver.DoWork += (s, a) => {
173        TableServiceClient client = ClientFactory.Create<TableServiceClient, ITableService>();
174        if (updatedRows != null)
175          client.UpdateDataTable(updatedRows, (string)a.Argument);
176        if (deletedRows != null)
177          client.DeleteTableRows(
178            deletedRows.Rows.Cast<DataRow>()
179              .Select(r => (int)r["Id", DataRowVersion.Original]).ToList(),
180            (string)a.Argument);
181        success = true;
182      };
183      saver.RunWorkerCompleted += (s, a) => {
184        if (success) {
185          table.AcceptChanges();
186        }
187        OnLoad(sender, args);
188      };
189      saver.RunWorkerAsync(TableName);
190    }
191
192    protected void OnAutoGeneratingColumn(object source, DataGridAutoGeneratingColumnEventArgs args) {
193      if (args.Column.Header as string == "Id") {
194        args.Cancel = true;
195        return;
196      }
197      if (foreignKeys.ContainsKey(args.PropertyName)) {
198        DataTable referencedTable = foreignKeys[args.PropertyName];
199        args.Column = new DataGridComboBoxColumn() {
200          Header = referencedTable.TableName,
201          ItemsSource = referencedTable.DefaultView,
202          SelectedValuePath = "Id",
203          DisplayMemberPath = referencedTable.Columns.Contains("Name") ? "Name" : "ClrName",
204          SelectedValueBinding = new Binding(args.PropertyName),
205        };
206      }
207    }
208
209    private void CommandBinding_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e) {
210      OnSave(sender, e);
211    }
212  }
213}
Note: See TracBrowser for help on using the repository browser.