HamBook – Blame information for rev 17

Subversion Repositories:
Rev:
Rev Author Line No. Line
15 office 1 using Configuration;
2 using HamBook.Properties;
3 using HamBook.Radios;
4 using HamBook.Radios.Generic;
16 office 5 using HamBook.Utilities.Serialization;
15 office 6 using Serilog;
7 using System;
8 using System.Collections;
9 using System.Collections.Concurrent;
10 using System.Collections.Generic;
11 using System.ComponentModel;
12 using System.Data;
13 using System.Diagnostics;
14 using System.Drawing;
15 using System.IO;
16 using System.Linq;
17 using System.Reflection;
18 using System.Text;
19 using System.Text.RegularExpressions;
20 using System.Threading;
21 using System.Threading.Tasks;
22 using System.Windows.Forms;
23  
24 namespace HamBook
25 {
26 public partial class MemoryOrganizerForm : Form
27 {
28 private Configuration.Configuration Configuration { get; set; }
29  
30 private CatAssemblies _catAssemblies;
31 private CancellationToken _cancellationToken;
32  
33 public MemoryOrganizerForm()
34 {
35 InitializeComponent();
36 }
37  
38 public MemoryOrganizerForm(Configuration.Configuration configuration, CatAssemblies catAssemblies, CancellationToken cancellationToken) : this()
39 {
40 Configuration = configuration;
41 _catAssemblies = catAssemblies;
42 _cancellationToken = cancellationToken;
43 }
44  
45 /// <summary>
46 /// Clean up any resources being used.
47 /// </summary>
48 /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
49 protected override void Dispose(bool disposing)
50 {
51 if (disposing && (components != null))
52 {
53 components.Dispose();
54 }
55 base.Dispose(disposing);
56 }
57  
58 private async void button1_Click(object sender, EventArgs e)
59 {
60 var rows = GetSelectedDataGridViewRows(dataGridView1);
61 await ReadMemoryBanks(rows);
62 }
63  
64 private async void button2_Click(object sender, EventArgs e)
65 {
66 var rows = GetSelectedDataGridViewRows(dataGridView1);
67 await WriteMemoryBanks(rows);
68 }
69  
70 private void MemoryOrganizerForm_Load(object sender, EventArgs e)
71 {
72 toolStripProgressBar1.Minimum = 0;
73 toolStripProgressBar1.Maximum = 98;
74  
75 var memoryBankQueue = new ConcurrentQueue<int>();
76 var snapshotsQueuedTaskCompletionSource = new TaskCompletionSource<object>();
77  
78 async void IdleHandler(object idleHandlerSender, EventArgs idleHandlerArgs)
79 {
80 await snapshotsQueuedTaskCompletionSource.Task;
81  
82 try
83 {
84 if (!memoryBankQueue.TryDequeue(out var memoryBank))
85 {
86 Application.Idle -= IdleHandler;
87  
88 dataGridView1.Sort(dataGridView1.Columns["LocationColumn"], ListSortDirection.Ascending);
89 toolStripStatusLabel1.Text = "Done.";
90  
91 return;
92 }
93  
94 var index = dataGridView1.Rows.Add();
95  
96 dataGridView1.Rows[index].Cells["LocationColumn"].Value = $"{memoryBank:000}";
97 dataGridView1.Rows[index].Cells["FrequencyColumn"].Value = default;
98 dataGridView1.Rows[index].Cells["ClarifierDirectionColumn"].Value = default;
99 dataGridView1.Rows[index].Cells["ClarifierOffsetColumn"].Value = default;
100 dataGridView1.Rows[index].Cells["ClarColumn"].Value = default;
101 dataGridView1.Rows[index].Cells["ModeColumn"].Value = default;
102 dataGridView1.Rows[index].Cells["CtcssColumn"].Value = default;
103 dataGridView1.Rows[index].Cells["PhaseColumn"].Value = default;
104 dataGridView1.Rows[index].Cells["TagColumn"].Value = default;
105 dataGridView1.Rows[index].Cells["TextColumn"].Value = default;
106  
107 toolStripStatusLabel1.Text = $"{Resources.Read_memory_bank} {memoryBank}";
108  
109 toolStripProgressBar1.Increment(1);
110  
111 statusStrip1.Update();
112 }
113 catch (Exception exception)
114 {
115 Log.Error(exception, Resources.Could_not_update_data_grid_view);
116 }
117 }
118  
119 Application.Idle += IdleHandler;
120 try
121 {
122 foreach (var memoryBank in Enumerable.Range(1, 99))
123 {
124 memoryBankQueue.Enqueue(memoryBank);
125 }
126  
127 snapshotsQueuedTaskCompletionSource.TrySetResult(new { });
128 }
129 catch (Exception exception)
130 {
131 Application.Idle -= IdleHandler;
132  
133 Log.Error(exception, Resources.Unable_to_create_memory_banks);
134 }
135 }
136  
137 private void DataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
138 {
139 var dataGridView = (DataGridView)sender;
140  
141 if (dataGridView.CurrentCell is DataGridViewCheckBoxCell)
142 {
143 dataGridView.CommitEdit(DataGridViewDataErrorContexts.Commit);
144 }
145 }
146  
147 private void DataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
148 {
149 var dataGridView = (DataGridView)sender;
150  
151 dataGridView.CommitEdit(DataGridViewDataErrorContexts.Commit);
152 }
153  
154 private void DataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
155 {
156 var dataGridView = (DataGridView)sender;
157  
158 if (dataGridView.CurrentCell is DataGridViewCheckBoxCell)
159 {
160 if (dataGridView.CurrentCell.IsInEditMode)
161 {
162 if (dataGridView.IsCurrentCellDirty)
163 {
164 dataGridView.EndEdit();
165 }
166 }
167 }
168 }
169  
170 private void DataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
171 {
172 var dataGridView = (DataGridView)sender;
173  
174 if (e.RowIndex == -1 || e.ColumnIndex == -1)
175 {
176 return;
177 }
178  
179 switch (dataGridView.Columns[e.ColumnIndex].Name)
180 {
181 case "EnableColumn":
182 //ProcessEnable(dataGridView.Rows[e.RowIndex]);
183 break;
184 }
185 }
186  
187 private void DataGridView1_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
188 {
189 var dataGridView = (DataGridView)sender;
190  
191 if (e.RowIndex == -1 || e.ColumnIndex == -1 ||
192 !(dataGridView.Columns[e.ColumnIndex] is DataGridViewCheckBoxColumn))
193 {
194 return;
195 }
196  
197 dataGridView.EndEdit();
198 }
199  
200 private void DataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
201 {
202 var dataGridView = (DataGridView)sender;
203  
204 if (e.RowIndex == -1 || e.ColumnIndex == -1 ||
205 !(dataGridView.Columns[e.ColumnIndex] is DataGridViewCheckBoxColumn))
206 {
207 return;
208 }
209  
210 dataGridView.EndEdit();
211 }
212  
213 private void DataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
214 {
215 // @(-.-)@ -(o.o)- @(o_o)@
216 }
217  
218 private static List<DataGridViewRow> GetSelectedDataGridViewRows(DataGridView dataGridView)
219 {
220 return dataGridView.SelectedRows.OfType<DataGridViewRow>().OrderBy(row => row.Index).ToList();
221 }
222  
223 private async Task WriteMemoryBanks(List<DataGridViewRow> rows)
224 {
225 var count = rows.Count;
226  
227 toolStripProgressBar1.Minimum = 0;
228 toolStripProgressBar1.Maximum = count;
229  
230 var progress = new Progress<DataGridViewRowProgress>(rowProgress =>
231 {
232 switch (rowProgress)
233 {
234 case DataGridViewRowProgressSuccess<bool> rowProgressSuccess:
235 var success = rowProgressSuccess.Data;
236  
237 if (!success)
238 {
239 Log.Error($"{Resources.Could_not_write_memory_bank}");
240  
241 toolStripStatusLabel1.Text =
242 $"{Resources.Could_not_write_memory_bank} {rowProgress.Index + 1}";
17 office 243 toolStripProgressBar1.Increment(1);
15 office 244 statusStrip1.Update();
245  
246 return;
247 }
248  
249 toolStripStatusLabel1.Text =
250 $"{Resources.Wrote_memory_bank} {rowProgress.Index + 1}";
17 office 251 toolStripProgressBar1.Increment(1);
15 office 252 statusStrip1.Update();
253 break;
254 case DataGridViewRowProgressFailure rowProgressFailure:
255 Log.Error(rowProgressFailure.Exception, $"{Resources.Could_not_write_memory_bank}");
256  
257 toolStripStatusLabel1.Text =
258 $"{Resources.Could_not_write_memory_bank} {rowProgress.Index + 1}";
17 office 259 toolStripProgressBar1.Increment(1);
15 office 260 statusStrip1.Update();
261 break;
262 }
263 });
264  
265 await Task.Run(() => WriteMemoryBanks(rows, progress, _cancellationToken), _cancellationToken);
266  
267 if (!_cancellationToken.IsCancellationRequested)
268 {
269 toolStripProgressBar1.Value = toolStripProgressBar1.Maximum;
270 toolStripStatusLabel1.Text = "Done.";
271 }
272 }
273  
274 private async Task ReadMemoryBanks(IReadOnlyList<DataGridViewRow> rows)
275 {
276 var count = rows.Count;
277  
278 toolStripProgressBar1.Minimum = 0;
279 toolStripProgressBar1.Maximum = count;
280  
281 var progress = new Progress<DataGridViewRowProgress>(rowProgress =>
282 {
283 switch(rowProgress)
284 {
285 case DataGridViewRowProgressSuccess<MemoryChannel> rowProgressSuccess:
286 var result = rowProgressSuccess.Data;
287  
288 rowProgress.Row.Cells["FrequencyColumn"].Value = result.Frequency;
289 rowProgress.Row.Cells["ClarifierDirectionColumn"].Value = (char)result.ClarifierDirection;
290 rowProgress.Row.Cells["ClarifierOffsetColumn"].Value = result.ClarifierOffset;
291 rowProgress.Row.Cells["ClarColumn"].Value = result.Clar;
292 rowProgress.Row.Cells["ModeColumn"].Value = (string)result.MemoryRadioMode;
293 rowProgress.Row.Cells["CtcssColumn"].Value = (string)result.CtcssMode;
294 rowProgress.Row.Cells["PhaseColumn"].Value = (string)result.Phase;
295 rowProgress.Row.Cells["TagColumn"].Value = result.Tag;
296 rowProgress.Row.Cells["TextColumn"].Value = result.Text.Trim();
16 office 297 rowProgress.Row.Tag = rowProgressSuccess.Data;
15 office 298  
299 break;
300 case DataGridViewRowProgressFailure rowProgressFailure:
301 Log.Error(rowProgressFailure.Exception, $"{Resources.Could_not_read_memory_bank}");
302  
303 break;
304 }
305  
306 toolStripStatusLabel1.Text =
307 $"{Resources.Read_memory_bank} {rowProgress.Index + 1}";
17 office 308 toolStripProgressBar1.Increment(1);
15 office 309  
310 statusStrip1.Update();
311 });
312  
313 await Task.Run(() => ReadMemoryBanks(rows, progress, _cancellationToken), _cancellationToken);
314  
315 if (!_cancellationToken.IsCancellationRequested)
316 {
317 toolStripProgressBar1.Value = toolStripProgressBar1.Maximum;
318 toolStripStatusLabel1.Text = "Done.";
319 }
320 }
321  
322 private async Task ReadMemoryBanks(IReadOnlyList<DataGridViewRow> rows, IProgress<DataGridViewRowProgress> progress,
323 CancellationToken cancellationToken)
324 {
325 var count = rows.Count;
326  
327 for (var i = 0; i < count && !cancellationToken.IsCancellationRequested; ++i)
328 {
329 try
330 {
331 var location = int.Parse($"{rows[i].Cells["LocationColumn"].Value}");
332  
333 var memoryBank = $"{location:000}";
334  
335 var result = await _catAssemblies.CatReadAsync<MemoryChannel>("MT", new object[] { memoryBank }, _cancellationToken);
336  
337 progress.Report(new DataGridViewRowProgressSuccess<MemoryChannel>(rows[i], i, result));
338 }
339 catch (UnexpectedRadioResponseException exception)
340 {
341 progress.Report(new DataGridViewRowProgressFailure(rows[i], i, exception));
342 }
343 catch (Exception exception)
344 {
345 progress.Report(new DataGridViewRowProgressFailure(rows[i], i, exception));
346 }
347 }
348 }
349  
350 private async Task WriteMemoryBanks(IReadOnlyList<DataGridViewRow> rows, IProgress<DataGridViewRowProgress> progress,
351 CancellationToken cancellationToken)
352 {
353 var count = rows.Count;
354  
355 for (var i = 0; i < count && !cancellationToken.IsCancellationRequested; ++i)
356 {
357 try
358 {
359 var location = int.Parse($"{rows[i].Cells["LocationColumn"].Value}");
360  
361 var currentLocation = $"{location:000}";
362 var frequency = int.Parse($"{rows[i].Cells["FrequencyColumn"].Value}");
363 var clarifierDirection = char.Parse($"{rows[i].Cells["ClarifierDirectionColumn"].Value}");
364 var clarifierOffset = int.Parse($"{rows[i].Cells["ClarifierOffsetColumn"].Value}");
365 var clar = bool.Parse($"{rows[i].Cells["ClarColumn"].Value}");
366 var radioMode = new MemoryRadioMode($"{rows[i].Cells["ModeColumn"].Value}");
367 var ctcssMode = new CtcssMode($"{rows[i].Cells["CtcssColumn"].Value}");
368 var phase = new RadioPhase($"{rows[i].Cells["PhaseColumn"].Value}");
369 var tag = bool.Parse($"{rows[i].Cells["TagColumn"].Value}");
17 office 370 var text = $"{rows[i].Cells["TextColumn"].Value, -12}";
15 office 371  
372 var memoryChannel = new MemoryChannel
373 {
374 CurrentLocation = currentLocation,
375 Frequency = frequency,
376 ClarifierDirection = clarifierDirection,
377 ClarifierOffset = clarifierOffset,
378 Clar = clar,
379 MemoryRadioMode = radioMode,
380 CtcssMode = ctcssMode,
381 Phase = phase,
382 Tag = tag,
383 Text = text
384 };
385  
386 var result = await _catAssemblies.CatSetAsync<MemoryChannel, bool>("MT", new object[] { memoryChannel }, _cancellationToken);
387  
388 progress.Report(new DataGridViewRowProgressSuccess<bool>(rows[i], i, result));
389 }
390 catch (UnexpectedRadioResponseException exception)
391 {
392 progress.Report(new DataGridViewRowProgressFailure(rows[i], i, exception));
393 }
394 catch (Exception exception)
395 {
396 progress.Report(new DataGridViewRowProgressFailure(rows[i], i, exception));
397 }
398 }
399 }
16 office 400  
401 private void importToolStripMenuItem_Click(object sender, EventArgs e)
402 {
403 openFileDialog1.ShowDialog();
404 }
405  
406 private void exportToolStripMenuItem_Click(object sender, EventArgs e)
407 {
408 saveFileDialog1.ShowDialog();
409 }
410  
411 private async void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
412 {
413 if (e.Cancel)
414 {
415 return;
416 }
417  
418 var fileName = saveFileDialog1.FileName;
419 var list = new List<MemoryChannelOrganizerBank>();
420 foreach(var row in dataGridView1.Rows.OfType<DataGridViewRow>().OrderBy(row => row.Index))
421 {
422 if (row.Tag is MemoryChannel memoryChannel)
423 {
424 var memoryChannelOrganizerBanks = new MemoryChannelOrganizerBank(row.Index, memoryChannel);
425 list.Add(memoryChannelOrganizerBanks);
426 }
427 }
428  
429 var memoryBanks = list.ToArray();
430  
431 switch (await Serialization.Serialize(memoryBanks, fileName, "MemoryChannelOrganizerBank",
432 "<!ATTLIST MemoryChannelOrganizerBank xmlns:xsi CDATA #IMPLIED xsi:noNamespaceSchemaLocation CDATA #IMPLIED>",
433 CancellationToken.None))
434 {
435 case SerializationSuccess<MemoryChannelOrganizerBank[]> configuration:
436 Log.Information(Resources.Serialized_memory_banks);
437 break;
438 case SerializationFailure serializationFailure:
439 Log.Warning(serializationFailure.Exception.Message, Resources.Failed_to_serialize_memory_banks);
440 break;
441 }
442 }
443  
444 private async void openFileDialog1_FileOk(object sender, CancelEventArgs e)
445 {
446 if(e.Cancel)
447 {
448 return;
449 }
450  
451 var fileName = openFileDialog1.FileName;
452 MemoryChannelOrganizerBank[] memoryBanks = null;
453  
454 var deserializationResult =
455 await Serialization.Deserialize<MemoryChannelOrganizerBank[]>(fileName,
456 "urn:hambook-memorychannelorganizerbank-schema", "MemoryChannelOrganizerBanks.xsd", CancellationToken.None);
457  
458 switch (deserializationResult)
459 {
460 case SerializationSuccess<MemoryChannelOrganizerBank[]> serializationSuccess:
461 Log.Information(Resources.Deserialized_memory_banks);
462 memoryBanks = serializationSuccess.Result;
463 break;
464 case SerializationFailure serializationFailure:
465 Log.Warning(serializationFailure.Exception, Resources.Failed_to_deserialize_memory_banks);
466 return;
467 }
468  
469 toolStripProgressBar1.Minimum = 0;
470 toolStripProgressBar1.Maximum = 98;
471  
472 var memoryBankQueue = new ConcurrentQueue<MemoryChannelOrganizerBank>();
473 var snapshotsQueuedTaskCompletionSource = new TaskCompletionSource<object>();
474  
475 async void IdleHandler(object idleHandlerSender, EventArgs idleHandlerArgs)
476 {
477 await snapshotsQueuedTaskCompletionSource.Task;
478  
479 try
480 {
481 if (!memoryBankQueue.TryDequeue(out var memoryBank))
482 {
483 Application.Idle -= IdleHandler;
484  
485 dataGridView1.Sort(dataGridView1.Columns["LocationColumn"], ListSortDirection.Ascending);
486 toolStripStatusLabel1.Text = "Done.";
487  
488 return;
489 }
490  
491 dataGridView1.Rows[memoryBank.Index].Cells["FrequencyColumn"].Value = memoryBank.MemoryChannel.Frequency;
492 dataGridView1.Rows[memoryBank.Index].Cells["ClarifierDirectionColumn"].Value = (char)memoryBank.MemoryChannel.ClarifierDirection;
493 dataGridView1.Rows[memoryBank.Index].Cells["ClarifierOffsetColumn"].Value = memoryBank.MemoryChannel.ClarifierOffset;
494 dataGridView1.Rows[memoryBank.Index].Cells["ClarColumn"].Value = memoryBank.MemoryChannel.Clar;
495 dataGridView1.Rows[memoryBank.Index].Cells["ModeColumn"].Value = (string)memoryBank.MemoryChannel.MemoryRadioMode;
496 dataGridView1.Rows[memoryBank.Index].Cells["CtcssColumn"].Value = (string)memoryBank.MemoryChannel.CtcssMode;
497 dataGridView1.Rows[memoryBank.Index].Cells["PhaseColumn"].Value = (string)memoryBank.MemoryChannel.Phase;
498 dataGridView1.Rows[memoryBank.Index].Cells["TagColumn"].Value = memoryBank.MemoryChannel.Tag;
499 dataGridView1.Rows[memoryBank.Index].Cells["TextColumn"].Value = memoryBank.MemoryChannel.Text;
500  
501 toolStripProgressBar1.Increment(1);
502  
503 statusStrip1.Update();
504 }
505 catch (Exception exception)
506 {
507 Log.Error(exception, Resources.Could_not_update_data_grid_view);
508 }
509 }
510  
511 Application.Idle += IdleHandler;
512 try
513 {
514 foreach (var memoryChannel in memoryBanks)
515 {
516 memoryBankQueue.Enqueue(memoryChannel);
517 }
518  
519 snapshotsQueuedTaskCompletionSource.TrySetResult(new { });
520 }
521 catch (Exception exception)
522 {
523 Application.Idle -= IdleHandler;
524  
525 Log.Error(exception, Resources.Unable_to_create_memory_banks);
526 }
527 }
15 office 528 }
529 }