Compare commits

..

2 Commits

Author SHA1 Message Date
22ddf238ef added missing data 2025-05-26 09:01:59 +02:00
7bf2994cda Added basic LokiAppender for all log4net logging output 2025-05-23 16:34:03 +02:00
115 changed files with 3097 additions and 5030 deletions

View File

@ -11,8 +11,8 @@
<section name="ENI2.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8.1" />
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<applicationSettings>
<ENI2.Properties.Settings>
@ -85,7 +85,7 @@
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Extensions.Logging.Abstractions" publicKeyToken="adb9793829ddae60" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.0" />
<bindingRedirect oldVersion="0.0.0.0-9.0.0.4" newVersion="9.0.0.4" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Memory" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
@ -119,26 +119,6 @@
<assemblyIdentity name="Microsoft.Extensions.Primitives" publicKeyToken="adb9793829ddae60" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-9.0.0.3" newVersion="9.0.0.3" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Security.Cryptography.Pkcs" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Numerics.Vectors" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.1.6.0" newVersion="4.1.6.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="DocumentFormat.OpenXml.Framework" publicKeyToken="8fb06cb64d019a17" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.3.0.0" newVersion="3.3.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="DocumentFormat.OpenXml" publicKeyToken="8fb06cb64d019a17" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.3.0.0" newVersion="3.3.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Bcl.HashCode" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

View File

@ -11,10 +11,13 @@ using log4net;
using System.Windows.Controls;
using System.Windows.Input;
using System;
using System.Net;
using ENI2.LockingServiceReference;
using ENI2.Util;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Excel;
using System.Drawing.Drawing2D;
namespace ENI2
{

View File

@ -56,7 +56,7 @@
</Grid>
</ControlTemplate>
<!-- Validation Error Template for a DataGrid Row -->
@ -80,7 +80,7 @@
</Setter.Value>
</Setter>
</Style>
<Style TargetType="{x:Type ToolTip}" >

View File

@ -8,7 +8,6 @@ using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Threading;
namespace ENI2.Controls
{
@ -162,9 +161,8 @@ namespace ENI2.Controls
}
if (!abort)
{
var tabControl = Parent as TabControl;
tabControl.SelectedItem = null;
_ = Dispatcher.BeginInvoke(new Action(() => tabControl.Items.Remove(this)), DispatcherPriority.Background);
var tabControl = Parent as ItemsControl;
tabControl.Items.Remove(this);
}
};
dockPanel.Children.Add(closeButton);

View File

@ -1,113 +0,0 @@
<UserControl x:Class="ENI2.Controls.EasyPeasyControl"
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:ENI2.Controls"
mc:Ignorable="d"
d:DesignHeight="650" d:DesignWidth="1024" Loaded="UserControl_Loaded" Unloaded="UserControl_Unloaded">
<DockPanel>
<!-- Header with logo -->
<Border DockPanel.Dock="Top" Padding="10" Background="#FFFDF6">
<StackPanel Orientation="Horizontal" VerticalAlignment="Center" >
<!-- Embed SVG via Image (optional): place your SVG as a DrawingImage in resources, or replace with PNG -->
<TextBlock Text="🍋 easy-peasy" FontSize="20" FontWeight="Bold" Margin="0,0,16,0"/>
<TextBlock Text="Edit • Paste • Export XML" VerticalAlignment="Center"/>
</StackPanel>
</Border>
<ScrollViewer VerticalScrollBarVisibility="Auto">
<StackPanel Margin="12" Orientation="Vertical" >
<!-- Top-level fields -->
<UniformGrid Columns="4" Rows="3" Margin="0,0,0,12" Height="84">
<TextBlock Text="Art der Identification (Vertreter)" Margin="0,0,4,0" VerticalAlignment="Center" TextAlignment="Right"/>
<TextBox Text="{Binding DelegateIdentificationType, UpdateSourceTrigger=PropertyChanged}" Margin="2" VerticalContentAlignment="Center"/>
<TextBlock Text="Art der Identifikation (Kunde)" VerticalAlignment="Center" Margin="0,0,4,0" TextAlignment="Right" />
<TextBox Text="{Binding TraderIdentificationType, UpdateSourceTrigger=PropertyChanged}" Margin="2" VerticalContentAlignment="Center"/>
<TextBlock Text="LRN" TextAlignment="Right" Margin="0,0,4,0" VerticalAlignment="Center"/>
<TextBox Text="{Binding LRN, UpdateSourceTrigger=PropertyChanged}" Margin="2" VerticalContentAlignment="Center"/>
<TextBlock Text="Identifikationsnummer (Kunde)" Margin="0,0,4,0" VerticalAlignment="Center" TextAlignment="Right" />
<TextBox Text="{Binding TraderIdentificationNumber, UpdateSourceTrigger=PropertyChanged}" Margin="2" VerticalContentAlignment="Center"/>
<TextBlock Text="Land" TextAlignment="Right" Margin="0,0,4,0" VerticalAlignment="Center"/>
<TextBox Text="{Binding Country, UpdateSourceTrigger=PropertyChanged}" Margin="2" VerticalContentAlignment="Center"/>
<TextBlock Text="Identifikationsnummer (Vertreter)" Margin="0,0,4,0" VerticalAlignment="Center" TextAlignment="Right"/>
<TextBox Text="{Binding DelegateIdentificationNumber, UpdateSourceTrigger=PropertyChanged}" Margin="2" VerticalContentAlignment="Center"/>
</UniformGrid>
<!-- ProofInformation -->
<GroupBox Header="Kennung des Antrags auf Nachweis TZ2L(F)">
<StackPanel Margin="8">
<UniformGrid Columns="4" Rows="4" Margin="0,0,0,12" >
<TextBlock Text="Zuständige Zollstelle" TextAlignment="Right" VerticalAlignment="Center" Margin="0,0,4,0"/>
<TextBox Text="{Binding ProofInformationT2LT2LF.CompetentCustomsOffice, UpdateSourceTrigger=PropertyChanged}" Margin="2" VerticalContentAlignment="Center"/>
<TextBlock Text="Art der Anmeldung" TextAlignment="Right" VerticalAlignment="Center" Margin="0,0,4,0"/>
<TextBox Text="{Binding ProofInformationT2LT2LF.DeclarationType, UpdateSourceTrigger=PropertyChanged}" Margin="2" VerticalContentAlignment="Center"/>
<TextBlock TextWrapping="Wrap" Text="Datum Anmeldung
(yyyy-MM-ddTHH:mm:ss)" TextAlignment="Right" VerticalAlignment="Center" Margin="0,0,4,0"/>
<TextBox Text="{Binding ProofInformationT2LT2LF.DeclarationDate, StringFormat={}{0:yyyy-MM-ddTHH:mm:ss}, UpdateSourceTrigger=PropertyChanged}" Margin="2" VerticalContentAlignment="Center" />
<TextBlock Text="Gesamtrohmasse (kg)" TextAlignment="Right" VerticalAlignment="Center" Margin="0,0,4,0"/>
<TextBox x:Name="textBoxTotalGrossMass" Text="{Binding ProofInformationT2LT2LF.TotalGrossMassKg, UpdateSourceTrigger=PropertyChanged}" Margin="2" VerticalContentAlignment="Center"/>
<TextBlock TextWrapping="Wrap" Text="Antrag auf Gültigkeitsdauer des Nachweises (in Tagen)" TextAlignment="Right" VerticalAlignment="Center" Margin="0,0,4,0"/>
<TextBox Text="{Binding ProofInformationT2LT2LF.RequestedValidityOfTheProof.NumberOfDays, UpdateSourceTrigger=PropertyChanged}" Margin="2" VerticalContentAlignment="Center"/>
<TextBlock Text="Art des Antrags" TextAlignment="Right" VerticalAlignment="Center" Margin="0,0,4,0"/>
<TextBox Text="{Binding ProofInformationT2LT2LF.RequestType, UpdateSourceTrigger=PropertyChanged}" Margin="2" VerticalContentAlignment="Center"/>
</UniformGrid>
<GroupBox Header="Warenort">
<UniformGrid Columns="6" Margin="8" Height="28">
<TextBlock Text="Art des Ortes" TextAlignment="Right" VerticalAlignment="Center" Margin="0,0,4,0"/>
<TextBox Text="{Binding ProofInformationT2LT2LF.GoodsShipmentForT2LT2LF.LocationOfGoods.TypeOfLocation}" Margin="2" VerticalContentAlignment="Center"/>
<TextBlock Text="Art der Ortsbestimmung" TextAlignment="Right" VerticalAlignment="Center" Margin="0,0,4,0"/>
<TextBox Text="{Binding ProofInformationT2LT2LF.GoodsShipmentForT2LT2LF.LocationOfGoods.QualifierOfIdentification}" Margin="2" VerticalContentAlignment="Center"/>
<TextBlock Text="UNLocode" TextAlignment="Right" VerticalAlignment="Center" Margin="0,0,4,0"/>
<TextBox Text="{Binding ProofInformationT2LT2LF.GoodsShipmentForT2LT2LF.LocationOfGoods.UNLocode}" Margin="2" VerticalContentAlignment="Center"/>
</UniformGrid>
</GroupBox>
<CheckBox Content="In Containern beförderte Waren" Margin="8"
IsChecked="{Binding ProofInformationT2LT2LF.GoodsShipmentForT2LT2LF.ContainerIndication}"/>
<!-- Goods Items grid (paste target) -->
<TextBlock Text="Warenpositionen (Paste tab/CSV with columns: HS, Item#, Description, Gross, Net, Pkgs, Type, Marks)" Margin="4,12,0,4"/>
<DataGrid ItemsSource="{Binding ProofInformationT2LT2LF.GoodsShipmentForT2LT2LF.GoodsItemsForT2LT2LF}"
AutoGenerateColumns="False" SelectionMode="Extended" x:Name="dataGridGoodsItems" CanUserAddRows="False"
PreviewKeyDown="DataGrid_PreviewKeyDown" Focusable="True" MinHeight="80" IsTabStop="True" MaxHeight="320">
<DataGrid.Columns>
<DataGridTextColumn Header="HS Code" Binding="{Binding Commodity.HarmonizedSystemSubHeadingCode}"/>
<DataGridTextColumn Header="Item #" Binding="{Binding GoodsItemNumber}"/>
<DataGridTextColumn Header="Description" Binding="{Binding DescriptionOfGoods}" Width="2*"/>
<DataGridTextColumn Header="Gross" Binding="{Binding GoodsMeasure.GrossMass}"/>
<DataGridTextColumn Header="Net" Binding="{Binding GoodsMeasure.NetMass}"/>
<DataGridTextColumn Header="Pkgs" Binding="{Binding Packaging.NumberOfPackages}"/>
<DataGridTextColumn Header="Type" Binding="{Binding Packaging.TypeOfPackages}"/>
<DataGridTextColumn Header="Marks" Binding="{Binding Packaging.ShippingMarks}" Width="*"/>
</DataGrid.Columns>
</DataGrid>
<GroupBox Header="Dokumente" Margin="0,12,0,0">
<UniformGrid Columns="4" Margin="8" Height="28">
<TextBlock Text="Art des Dokuments" Margin="0,0,4,0" VerticalAlignment="Center" TextAlignment="Right"/>
<TextBox Text="{Binding ProofInformationT2LT2LF.GoodsShipmentForT2LT2LF.TransportDocuments.Type}" Margin="2" VerticalContentAlignment="Center"/>
<TextBlock Text="Referenznummer" Margin="0,0,4,0" VerticalAlignment="Center" TextAlignment="Right"/>
<TextBox Text="{Binding ProofInformationT2LT2LF.GoodsShipmentForT2LT2LF.TransportDocuments.ReferenceNumber}" Margin="2" VerticalContentAlignment="Center" />
</UniformGrid>
</GroupBox>
</StackPanel>
</GroupBox>
<!-- Actions -->
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Margin="0,16,0,0">
<Button x:Name="buttonImport" Content="Import" Width="100" Margin="0,0,8,0" Click="buttonImport_Click" />
<Button x:Name="buttonClear" Content="Clear" Width="100" Margin="0,0,8,0" Click="buttonClear_Click"/>
<Button x:Name="buttonExport" Content="Export" Width="120" Click="buttonExport_Click"/>
</StackPanel>
</StackPanel>
</ScrollViewer>
</DockPanel>
</UserControl>

View File

@ -1,506 +0,0 @@
// Copyright (c) 2017- schick Informatik
// Description: Display dialog for customs XML data upload app
//
using bsmd.database.EasyPeasy;
using ENI2.Util;
using Microsoft.Win32;
using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using System.Xml;
using System.Xml.Serialization;
namespace ENI2.Controls
{
/// <summary>
/// Interaction logic for EasyPeasyControl.xaml
/// </summary>
public partial class EasyPeasyControl : UserControl
{
private ProofRequest _vm;
#region Construction
public EasyPeasyControl()
{
InitializeComponent();
this.dataGridGoodsItems.ContextMenu = new ContextMenu();
MenuItem addItem = new MenuItem();
addItem.Header = Properties.Resources.textAdd;
addItem.Icon = new Image { Source = new BitmapImage(new Uri("pack://application:,,,/Resources/add.png")) };
addItem.Click += AddItem_Click;
this.dataGridGoodsItems.ContextMenu.Items.Add(addItem);
MenuItem deleteItem = new MenuItem();
deleteItem.Header = Properties.Resources.textDelete;
deleteItem.Icon = new Image { Source = new BitmapImage(new Uri("pack://application:,,,/Resources/delete.png")) };
deleteItem.Click += DeleteItem_Click;
this.dataGridGoodsItems.ContextMenu.Items.Add(deleteItem);
// Add separator and paste option
this.dataGridGoodsItems.ContextMenu.Items.Add(new Separator());
MenuItem pasteItem = new MenuItem();
pasteItem.Header = "Paste";
pasteItem.Click += (s, e) => HandlePasteOperation();
this.dataGridGoodsItems.ContextMenu.Items.Add(pasteItem);
// Add command bindings for proper keyboard handling
this.dataGridGoodsItems.CommandBindings.Add(new CommandBinding(
ApplicationCommands.Paste,
(s, e) => HandlePasteOperation(),
(s, e) => e.CanExecute = Clipboard.ContainsText()));
}
#endregion
public void SaveState()
{
try
{
EasyPeasyState.Save(_vm);
}
catch { }
}
#region context menu event handler
private void AddItem_Click(object sender, RoutedEventArgs e)
{
if (_vm?.ProofInformationT2LT2LF?.GoodsShipmentForT2LT2LF?.GoodsItemsForT2LT2LF == null) return;
var list = _vm.ProofInformationT2LT2LF.GoodsShipmentForT2LT2LF.GoodsItemsForT2LT2LF;
int nextItemNo = list.Any() ? list.Max(x => x.GoodsItemNumber) + 1 : 1;
var item = new GoodsItemForT2LT2LF
{
GoodsItemNumber = nextItemNo
};
list.Add(item);
}
private void DeleteItem_Click(object sender, RoutedEventArgs e)
{
foreach(GoodsItemForT2LT2LF item in this.dataGridGoodsItems.SelectedItems.Cast<GoodsItemForT2LT2LF>().ToArray())
{
if (_vm?.ProofInformationT2LT2LF?.GoodsShipmentForT2LT2LF?.GoodsItemsForT2LT2LF == null) return;
var list = _vm.ProofInformationT2LT2LF.GoodsShipmentForT2LT2LF.GoodsItemsForT2LT2LF;
list.Remove(item);
}
}
#endregion
#region button event handler
private void buttonClear_Click(object sender, RoutedEventArgs e)
{
CleanupAutoCalculation();
this._vm = EasyPeasyState.CreateDefault();
if (_vm.ProofInformationT2LT2LF?.GoodsShipmentForT2LT2LF?.GoodsItemsForT2LT2LF == null)
_vm.ProofInformationT2LT2LF.GoodsShipmentForT2LT2LF.GoodsItemsForT2LT2LF = new ObservableCollection<GoodsItemForT2LT2LF>();
_vm.ProofInformationT2LT2LF.DeclarationDate = DateTime.Now; // reset to today
_vm.ProofInformationT2LT2LF.RequestedValidityOfTheProof.NumberOfDays = 90; // default 90 days
this.DataContext = this._vm;
SetupAutoCalculation();
}
private void buttonExport_Click(object sender, RoutedEventArgs e)
{
var dlg = new SaveFileDialog
{
FileName = "proofRequest.xml",
Filter = "XML file|*.xml",
OverwritePrompt = true
};
if (dlg.ShowDialog() == true)
{
try
{
var ser = new XmlSerializer(typeof(ProofRequest));
// Namespaces (if needed)
// var ns = new XmlSerializerNamespaces();
// ns.Add("xsd", "http://www.w3.org/2001/XMLSchema");
// ns.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");
var settings = new XmlWriterSettings
{
Indent = true,
OmitXmlDeclaration = true
};
using (var fs = File.Create(dlg.FileName))
using (var xw = XmlWriter.Create(fs, settings))
{
ser.Serialize(xw, _vm); //, ns);
}
MessageBox.Show("Exported successfully.", "easy-peasy", MessageBoxButton.OK, MessageBoxImage.Information);
}
catch (Exception ex)
{
MessageBox.Show("Export failed:\n" + ex.Message, "easy-peasy", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
private void buttonImport_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "XML file|*.xml";
ofd.RestoreDirectory = true;
ofd.Multiselect = false;
if (ofd.ShowDialog() == true)
{
using (var fs = File.OpenRead(ofd.FileName))
{
CleanupAutoCalculation();
var ser = new XmlSerializer(typeof(ProofRequest));
_vm = (ProofRequest)ser.Deserialize(fs);
// after loading/creating _vm
if (_vm.ProofInformationT2LT2LF?.GoodsShipmentForT2LT2LF?.GoodsItemsForT2LT2LF == null)
_vm.ProofInformationT2LT2LF.GoodsShipmentForT2LT2LF.GoodsItemsForT2LT2LF = new ObservableCollection<GoodsItemForT2LT2LF>();
_vm.ProofInformationT2LT2LF.DeclarationDate = DateTime.Now; // reset to today
if(_vm.ProofInformationT2LT2LF.RequestedValidityOfTheProof.NumberOfDays == 9)
_vm.ProofInformationT2LT2LF.RequestedValidityOfTheProof.NumberOfDays = 90; // default 90 days
this.DataContext = _vm;
SetupAutoCalculation();
}
}
}
#endregion
#region loaded/unloaded event handler
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
_vm = EasyPeasyState.LoadOrCreate();
if (_vm.ProofInformationT2LT2LF == null)
_vm.ProofInformationT2LT2LF = new ProofInformationT2LT2LF();
if (_vm.ProofInformationT2LT2LF.GoodsShipmentForT2LT2LF == null)
_vm.ProofInformationT2LT2LF.GoodsShipmentForT2LT2LF = new GoodsShipmentForT2LT2LF
{
LocationOfGoods = new LocationOfGoods(),
TransportDocuments = new TransportDocuments()
};
_vm.ProofInformationT2LT2LF.DeclarationDate = DateTime.Now; // reset to today
this.DataContext = _vm;
SetupAutoCalculation();
}
private void UserControl_Unloaded(object sender, RoutedEventArgs e)
{
CleanupAutoCalculation();
try
{
EasyPeasyState.Save(_vm);
}
catch { }
}
#endregion
#region auto calculation total gross mass
private void SetupAutoCalculation()
{
if (_vm?.ProofInformationT2LT2LF?.GoodsShipmentForT2LT2LF?.GoodsItemsForT2LT2LF != null)
{
// Subscribe to collection changes (add/remove items)
_vm.ProofInformationT2LT2LF.GoodsShipmentForT2LT2LF.GoodsItemsForT2LT2LF.CollectionChanged += GoodsItems_CollectionChanged;
// Subscribe to DataGrid cell changes
dataGridGoodsItems.CellEditEnding += DataGridGoodsItems_CellEditEnding;
// Calculate initial total
CalculateTotalGrossMass();
}
}
private void CleanupAutoCalculation()
{
if (_vm?.ProofInformationT2LT2LF?.GoodsShipmentForT2LT2LF?.GoodsItemsForT2LT2LF != null)
{
// Unsubscribe from collection changes
_vm.ProofInformationT2LT2LF.GoodsShipmentForT2LT2LF.GoodsItemsForT2LT2LF.CollectionChanged -= GoodsItems_CollectionChanged;
dataGridGoodsItems.CellEditEnding -= DataGridGoodsItems_CellEditEnding;
}
}
private void DataGridGoodsItems_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
// Check if the edited column is GrossMass
if (e.Column.Header.ToString() == "Gross")
{
// Delay calculation to allow the binding to update
Dispatcher.BeginInvoke(new Action(() => {
CalculateTotalGrossMass();
}), System.Windows.Threading.DispatcherPriority.Background);
}
}
private void GoodsItems_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
// Recalculate total after any collection change
CalculateTotalGrossMass();
}
private void CalculateTotalGrossMass()
{
if (_vm?.ProofInformationT2LT2LF?.GoodsShipmentForT2LT2LF?.GoodsItemsForT2LT2LF != null)
{
var total = _vm.ProofInformationT2LT2LF.GoodsShipmentForT2LT2LF.GoodsItemsForT2LT2LF
.Sum(item => item.GoodsMeasure?.GrossMass ?? 0m);
_vm.ProofInformationT2LT2LF.TotalGrossMassKg = total;
// Force UI update by refreshing the binding
var binding = BindingOperations.GetBindingExpression(
FindTotalGrossMassTextBox(), TextBox.TextProperty);
binding?.UpdateTarget();
}
}
// Simple property changed notification helper
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private TextBox FindTotalGrossMassTextBox()
{
// Find the TextBox that displays TotalGrossMassKg
return this.FindName("textBoxTotalGrossMass") as TextBox ??
this.GetTemplateChild("textBoxTotalGrossMass") as TextBox;
}
#endregion
#region cut & paste logic
private void HandlePasteOperation()
{
if (Clipboard.ContainsText())
{
var text = Clipboard.GetText();
if (!TryPaste_EspHsPkgsGross(text))
PasteGoodsItems(text);
}
}
private void DataGrid_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.V && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
{
if (Clipboard.ContainsText())
{
var text = Clipboard.GetText();
if(!TryPaste_EspHsPkgsGross(text))
PasteGoodsItems(text);
e.Handled = true;
}
}
}
private void PasteGoodsItems(string text)
{
if (_vm?.ProofInformationT2LT2LF?.GoodsShipmentForT2LT2LF == null) return;
var lines = text.Replace("\r\n", "\n").Replace('\r', '\n')
.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var line in lines)
{
// Split by tab first; if only one column, try CSV
var cells = line.Split('\t');
if (cells.Length == 1) cells = SplitCsv(line);
// Expected order: HS, Item#, Description, Gross, Net, Pkgs, Type, Marks
var item = new GoodsItemForT2LT2LF();
if (cells.Length > 0) item.Commodity.HarmonizedSystemSubHeadingCode = cells[0].Trim();
if (cells.Length > 1 && int.TryParse(cells[1], out var n)) item.GoodsItemNumber = n;
if (cells.Length > 2) item.DescriptionOfGoods = cells[2].Trim();
if (cells.Length > 3 && decimal.TryParse(cells[3], out var gross)) item.GoodsMeasure.GrossMass = gross;
if (cells.Length > 4 && decimal.TryParse(cells[4], out var net)) item.GoodsMeasure.NetMass = net;
if (cells.Length > 5 && int.TryParse(cells[5], out var pkgs)) item.Packaging.NumberOfPackages = pkgs;
if (cells.Length > 6) item.Packaging.TypeOfPackages = cells[6].Trim();
if (cells.Length > 7) item.Packaging.ShippingMarks = cells[7].Trim();
_vm.ProofInformationT2LT2LF.GoodsShipmentForT2LT2LF.GoodsItemsForT2LT2LF.Add(item);
}
}
// Very small CSV splitter (handles quotes)
private static string[] SplitCsv(string line)
{
var res = new System.Collections.Generic.List<string>();
var sb = new StringBuilder();
bool inQuotes = false;
for (int i = 0; i < line.Length; i++)
{
char c = line[i];
if (c == '\"')
{
if (inQuotes && i + 1 < line.Length && line[i + 1] == '\"')
{ sb.Append('\"'); i++; }
else { inQuotes = !inQuotes; }
}
else if (c == ',' && !inQuotes)
{ res.Add(sb.ToString()); sb.Clear(); }
else { sb.Append(c); }
}
res.Add(sb.ToString());
return res.ToArray();
}
private bool TryPaste_EspHsPkgsGross(string text)
{
if (_vm?.ProofInformationT2LT2LF?.GoodsShipmentForT2LT2LF == null) return false;
// Normalize and split lines
var lines = text.Replace("\r\n", "\n").Replace('\r', '\n')
.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
if (lines.Length == 0) return false;
// Determine next item number
var list = _vm.ProofInformationT2LT2LF.GoodsShipmentForT2LT2LF.GoodsItemsForT2LT2LF;
int nextItemNo = list.Any() ? list.Max(x => x.GoodsItemNumber) + 1 : 1;
bool anyAdded = false;
bool countrySeen = false;
foreach (var raw in lines)
{
var line = raw; // do not Trim() entirely; keep leading tab as empty first cell
var cells = line.Split('\t'); // keeps empty entries
// Expected:
// - 4 cells: [ESP or ""], [HS], [Pkgs], [Gross]
// - 3 cells: [HS], [Pkgs], [Gross]
string hs = null, pkgs = null, gross = null;
if (cells.Length >= 4)
{
string c0 = cells[0]?.Trim();
// Optionally capture the first token like "ESP" (country tag),
// only once and only if alphabetic (won't throw if numeric)
if (!countrySeen && !string.IsNullOrWhiteSpace(c0) && c0.All(ch => char.IsLetter(ch)))
{
// If you decide later this should set a field, uncomment:
// if (string.IsNullOrWhiteSpace(_vm.Country)) _vm.Country = c0;
countrySeen = true;
}
hs = (cells.Length > 1 ? cells[1] : null);
pkgs = (cells.Length > 2 ? cells[2] : null);
gross = (cells.Length > 3 ? cells[3] : null);
}
else if (cells.Length == 3)
{
hs = cells[0];
pkgs = cells[1];
gross = cells[2];
}
else
{
// Not enough data for this format; skip the row
continue;
}
if (string.IsNullOrWhiteSpace(hs)) continue;
var item = new GoodsItemForT2LT2LF
{
GoodsItemNumber = nextItemNo++,
DescriptionOfGoods = "" // per spec
};
item.Commodity.HarmonizedSystemSubHeadingCode = hs.Trim();
if (TryParseIntFlexible(pkgs, out var pk))
item.Packaging.NumberOfPackages = pk;
if (TryParseDecimalFlexible(gross, out var g))
{
item.GoodsMeasure.GrossMass = g;
var net = g; // - 1m; // now net mass equals gross mass (no deduction)
if (net < 0m) net = 0m;
item.GoodsMeasure.NetMass = net;
}
item.DescriptionOfGoods = "Brand New Vehicles"; // per spec
item.Packaging.TypeOfPackages = "UN"; // per spec
item.Packaging.ShippingMarks = "-"; // per spec
list.Add(item);
anyAdded = true;
}
return anyAdded;
}
#endregion
#region static utils
// this will go somewhere else later
// Try parse decimal with current culture, invariant, and comma/dot flip
private static bool TryParseDecimalFlexible(string s, out decimal value)
{
s = (s ?? "").Trim();
// 1) current culture
if (decimal.TryParse(s, NumberStyles.Number, CultureInfo.CurrentCulture, out value)) return true;
// 2) invariant
if (decimal.TryParse(s, NumberStyles.Number, CultureInfo.InvariantCulture, out value)) return true;
// 3) flip comma/dot and retry (helps when clipboard mixes locales)
string flipped = s.Contains(",") ? s.Replace(",", ".") : s.Replace(".", ",");
if (decimal.TryParse(flipped, NumberStyles.Number, CultureInfo.CurrentCulture, out value)) return true;
if (decimal.TryParse(flipped, NumberStyles.Number, CultureInfo.InvariantCulture, out value)) return true;
value = 0m;
return false;
}
private static bool TryParseIntFlexible(string s, out int value)
{
s = (s ?? "").Trim();
// Extract leading integer if something like "12 pcs"
var digits = new string(s.TakeWhile(ch => char.IsDigit(ch) || ch == '-' || ch == '+').ToArray());
if (string.IsNullOrEmpty(digits)) digits = s;
return int.TryParse(digits, NumberStyles.Integer, CultureInfo.CurrentCulture, out value)
|| int.TryParse(digits, NumberStyles.Integer, CultureInfo.InvariantCulture, out value);
}
#endregion
}
}

View File

@ -2,23 +2,23 @@
// Description: Request dbh ids for Maersk data lists
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Win32;
using bsmd.database;
using ClosedXML.Excel;
using ExcelDataReader;
using System.Collections.ObjectModel;
using ENI2.Excel;
using ENI2.Locode;
using ENI2.Util;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
namespace ENI2.Controls
{
@ -336,73 +336,80 @@ namespace ENI2.Controls
};
if (ofd.ShowDialog() ?? false)
{
FileStream stream;
try
{
using (var stream = new FileStream(ofd.FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var workbook = new XLWorkbook(stream))
stream = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read, FileShare.Read);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
using (IExcelDataReader reader = ExcelReaderFactory.CreateReader(stream))
{
List<MaerskData> importData = new List<MaerskData>();
bool isFirstRow = true;
int currentRow = 0;
bool imosAreOkay = true;
try
{
var worksheet = workbook.Worksheet(1); // Get first worksheet
var rows = worksheet.RangeUsed().RowsUsed().Skip(1); // Skip header row
List<MaerskData> importData = new List<MaerskData>();
int currentRow = 1; // Start at 1 since we skip header
bool imosAreOkay = true;
foreach (var row in rows)
while (reader.Read())
{
currentRow++;
if (worksheet.RangeUsed().ColumnCount() < 13)
if (isFirstRow)
{
isFirstRow = false; // this must be a header row, skip
continue;
}
if (reader.FieldCount < 13)
{
throw new InvalidDataException("Sheet must have 13 columns of data");
}
MaerskData md = new MaerskData();
if (!row.Cell(1).IsEmpty())
if (!reader.IsDBNull(0))
{
var cellValue = row.Cell(1).Value;
if (cellValue.IsDateTime)
if (reader.GetFieldType(0) == typeof(DateTime))
{
var dateTime = cellValue.GetDateTime();
md.ETA = dateTime;
md.ETA = reader.GetDateTime(0);
md.ColA = md.ETA.ToString();
}
else
{
md.ColA = row.Cell(1).GetString();
md.ColA = reader.GetString(0);
if (DateTime.TryParse(md.ColA, out DateTime aDateTime))
md.ETA = aDateTime;
}
}
if (!row.Cell(2).IsEmpty()) md.ColB = row.Cell(2).GetString();
if (!row.Cell(3).IsEmpty()) md.ColC = row.Cell(3).GetString();
if (!row.Cell(4).IsEmpty()) md.ColD = row.Cell(4).GetString();
if (!row.Cell(5).IsEmpty()) md.ColE = row.Cell(5).GetString();
if (!row.Cell(6).IsEmpty()) md.ColF = row.Cell(6).GetString();
if (!row.Cell(7).IsEmpty()) md.ColG = row.Cell(7).GetString();
if (!row.Cell(8).IsEmpty()) md.ColH = row.Cell(8).GetString();
if (!row.Cell(9).IsEmpty()) md.ColI = row.Cell(9).GetString();
if (!reader.IsDBNull(1)) md.ColB = reader.ReadAsString(1);
if (!reader.IsDBNull(2)) md.ColC = reader.ReadAsString(2);
if (!reader.IsDBNull(3)) md.ColD = reader.ReadAsString(3);
if (!reader.IsDBNull(4)) md.ColE = reader.ReadAsString(4);
if (!reader.IsDBNull(5)) md.ColF = reader.ReadAsString(5);
if (!reader.IsDBNull(6)) md.ColG = reader.ReadAsString(6);
if (!reader.IsDBNull(7)) md.ColH = reader.ReadAsString(7);
if (!reader.IsDBNull(8)) md.ColI = reader.ReadAsString(8);
if (md.ColI != null)
{
if ((md.ColI.Contains("bremerhaven", StringComparison.OrdinalIgnoreCase) && this.PortLocode.Equals("DEWVN")) ||
(md.ColI.Contains("eurogate", StringComparison.OrdinalIgnoreCase) && this.PortLocode.Equals("DEBRV")))
throw new InvalidOperationException($"{md.ColI} found in import to {PortLocode}, this is probably an error. Aborting import");
}
if (!row.Cell(10).IsEmpty()) md.ColJ = row.Cell(10).GetString();
if (!reader.IsDBNull(9)) md.ColJ = reader.ReadAsString(9);
if (md.ColJ == null) continue;
if (!(md.ColJ.Equals("msk", StringComparison.OrdinalIgnoreCase) || md.ColJ.Equals("sgl", StringComparison.OrdinalIgnoreCase))) continue; // skip operator we are not interested in
if (!row.Cell(11).IsEmpty()) md.ColK = row.Cell(11).GetString();
if (!row.Cell(12).IsEmpty()) md.ColL = row.Cell(12).GetString();
if (!row.Cell(13).IsEmpty()) md.ColM = row.Cell(13).GetString();
if (!row.Cell(14).IsEmpty()) md.Remark = row.Cell(14).GetString();
if (!md.ColF.IsNullOrEmpty())
if (!reader.IsDBNull(10)) md.ColK = reader.ReadAsString(10);
if (!reader.IsDBNull(11)) md.ColL = reader.ReadAsString(11);
if (!reader.IsDBNull(12)) md.ColM = reader.ReadAsString(12);
if (!reader.IsDBNull(13)) md.Remark = reader.ReadAsString(13);
if(!md.ColF.IsNullOrEmpty())
{
if (Int32.TryParse(md.ColF, out int imo))
{
@ -410,7 +417,7 @@ namespace ENI2.Controls
{
imosAreOkay = false;
}
}
}
else
{
imosAreOkay = false;
@ -428,67 +435,71 @@ namespace ENI2.Controls
}
importData.Add(md);
}
if (imosAreOkay && importData.Count > 0)
{
busyControl.BusyState = Util.UIHelper.BusyStateEnum.BUSY;
foreach (MaerskData md in importData)
{
if (this.maerskDataList.Contains(md))
{
// update record with imported record
MaerskData foundData = this.maerskDataList.First((m) => (m.ColF != null) ? m.ColF.Equals(md.ColF) : (md.ColF == null) &&
(m.ColG != null) ? m.ColG.Equals(md.ColG) : (md.ColG == null) &&
(m.ColH != null) ? m.ColH.Equals(md.ColH) : (md.ColH == null));
if ((foundData.MessageCore == null) || !(foundData.MessageCore.Cancelled ?? false))
{
if (foundData.ETA.HasValue && ((foundData.ETA.Value - DateTime.Now).TotalSeconds > 0) && foundData.Update(md))
foundData.Status = MaerskData.MDStatus.UPDATED;
}
}
else
{
if (!md.ColM.IsNullOrEmpty())
{
md.MessageCore = await DBManagerAsync.LoadCoreByVisitIdAsync(md.ColM);
if (md.MessageCore != null)
{
MaerskData existingMD = await DBManagerAsync.LoadMaerskDataForCoreAsync(md.MessageCore.Id.Value);
if (existingMD == null)
{
// we have a core but no MarskData for this import -> save it
md.MessageCoreId = (Guid)md.MessageCore.Id;
_ = DBManagerAsync.SaveAsync(md);
}
else
{
existingMD.Update(md);
_ = DBManagerAsync.SaveAsync(existingMD);
this.UpdateStatus(existingMD);
maerskDataList.Add(existingMD);
continue; // add existing instead of new one
}
}
}
this.UpdateStatus(md);
maerskDataList.Add(md);
}
}
this.TimeFilterItemSource();
busyControl.BusyState = Util.UIHelper.BusyStateEnum.NEUTRAL;
this.dataGridPOCores.Items.Refresh();
if (isFirstRow) isFirstRow = false;
}
}
catch (Exception ex)
{
MessageBox.Show("Error reading Excel: " + ex.Message, Properties.Resources.textCaptionError, MessageBoxButton.OK, MessageBoxImage.Error);
}
if (imosAreOkay && importData.Count > 0)
{
busyControl.BusyState = Util.UIHelper.BusyStateEnum.BUSY;
foreach (MaerskData md in importData)
{
if (this.maerskDataList.Contains(md))
{
// update record with imported record
MaerskData foundData = this.maerskDataList.First((m) => (m.ColF != null) ? m.ColF.Equals(md.ColF) : (md.ColF == null) &&
(m.ColG != null) ? m.ColG.Equals(md.ColG) : (md.ColG == null) &&
(m.ColH != null) ? m.ColH.Equals(md.ColH) : (md.ColH == null));
if ((foundData.MessageCore == null) || !(foundData.MessageCore.Cancelled ?? false))
{
if (foundData.ETA.HasValue && ((foundData.ETA.Value - DateTime.Now).TotalSeconds > 0) && foundData.Update(md))
foundData.Status = MaerskData.MDStatus.UPDATED;
}
}
else
{
if (!md.ColM.IsNullOrEmpty())
{
md.MessageCore = await DBManagerAsync.LoadCoreByVisitIdAsync(md.ColM);
if (md.MessageCore != null)
{
MaerskData existingMD = await DBManagerAsync.LoadMaerskDataForCoreAsync(md.MessageCore.Id.Value);
if(existingMD == null)
{
// we have a core but no MarskData for this import -> save it
md.MessageCoreId = (Guid) md.MessageCore.Id;
_ = DBManagerAsync.SaveAsync(md);
}
else
{
existingMD.Update(md);
_ = DBManagerAsync.SaveAsync(existingMD);
this.UpdateStatus(existingMD);
maerskDataList.Add(existingMD);
continue; // add existing instead of new one
}
}
}
this.UpdateStatus(md);
maerskDataList.Add(md);
}
}
this.TimeFilterItemSource();
busyControl.BusyState = Util.UIHelper.BusyStateEnum.NEUTRAL;
this.dataGridPOCores.Items.Refresh();
}
}
catch (Exception ex)
{
MessageBox.Show("Error reading Excel: " + ex.Message, Properties.Resources.textCaptionError, MessageBoxButton.OK, MessageBoxImage.Error);
}
stream.Close();
}
}

View File

@ -70,7 +70,7 @@ namespace ENI2
/// <summary>
/// Damit kann ein Listenelement eine Validierung der gesamten Anmeldung auslösen (inkl. Highlighting) (auf Knopfdruck)
/// </summary>
public event Action<bool> RequestValidate;
public event Action RequestValidate;
/// <summary>
/// Alle Meldeklassen die auf "zu versenden" stehen werden validiert und falls die Validierung scheitert auf "SUSPEND" gestellt
@ -160,9 +160,9 @@ namespace ENI2
this.RequestReload?.Invoke(coreId);
}
protected virtual void OnRequestValidate(bool showDialog)
protected virtual void OnRequestValidate()
{
this.RequestValidate?.Invoke(showDialog);
this.RequestValidate?.Invoke();
}
protected virtual void OnRequestSendValidation()

View File

@ -15,7 +15,7 @@
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="220" x:Name="leftColumnDefinition"/>
<ColumnDefinition Width="220" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>

View File

@ -17,7 +17,6 @@ using ENI2.EditControls;
using System.Windows.Input;
using System.Linq;
using ENI2.SheetDisplayControls;
using System.Threading.Tasks;
namespace ENI2
{
@ -35,9 +34,6 @@ namespace ENI2
// private readonly Dictionary<Message.NotificationClass, string> messageClassControlDict = new Dictionary<Message.NotificationClass, string>();
private readonly object messageListLock = new object();
private readonly HighlightService highlightService = new HighlightService();
private readonly object validationLock = new object();
private Task<ValidationResult> activeValidationTask = null;
private bool pendingShowMessages = false;
// Referenzen für Fehler/Violation Dialoge (können, müssen aber nicht offen bleiben)
protected ErrorListDialog _errorListDialog = null;
@ -193,7 +189,6 @@ namespace ENI2
this._listBoxList.Add(new MessageGroup() { MessageGroupName = Properties.Resources.text11DangerousCargoDeparture, MessageGroupControlType = typeof(DangerousCargoControl), ImagePath = "Resources/sign_warning_radiation.png" });
this._listBoxList.Add(new MessageGroup() { MessageGroupName = Properties.Resources.text12ATAATD, MessageGroupControlType = typeof(ATAControl), ImagePath = "Resources/clock.png" });
this._listBoxList.Add(new MessageGroup() { MessageGroupName = Properties.Resources.text13WasteReceipts, MessageGroupControlType = typeof(WasteReceiptsControl), ImagePath = "Resources/garbage.png" });
this.leftColumnDefinition.Width = new GridLength(260);
}
this.listBoxMessages.ItemsSource = this._listBoxList;
@ -230,7 +225,6 @@ namespace ENI2
public void CoreChanged(MessageCore newCore)
{
this.Core = newCore;
this.ReloadCore();
System.Windows.Application.Current.Dispatcher.Invoke(delegate
{
if(controlCache.ContainsKey(Properties.Resources.textOverview))
@ -512,7 +506,7 @@ namespace ENI2
this.DetailControl_RequestReload(this.Core.Id.Value);
System.Action<int> SetTabAction = x =>
System.Action<int> SetTabAction = (int x) =>
{
// this hopefully happens *after* the view was completely reloaded
if (this.detailView.Children[0] is DetailBaseControl currentNewControl)
@ -532,14 +526,9 @@ namespace ENI2
{
if ((message.Status == Message.MessageStatus.ACCEPTED) &&
((message.InternalStatus == Message.BSMDStatus.CONFIRMED) || (message.InternalStatus == Message.BSMDStatus.VIOLATION)))
{
message.InternalStatus = Message.BSMDStatus.UPDATED;
message.Status = null; // reset send status
}
else
{
message.InternalStatus = Message.BSMDStatus.SAVED;
}
string userName = "?";
if(App.UserId.HasValue && DBManager.Instance.GetReportingPartyDict().ContainsKey(App.UserId.Value))
@ -601,7 +590,7 @@ namespace ENI2
this.DetailControl_RequestReload(this.Core.Id.Value);
Action<int> SetTabAction = x =>
System.Action<int> SetTabAction = (int x) =>
{
// this hopefully happens *after* the view was completely reloaded
if (this.detailView.Children[0] is DetailBaseControl currentNewControl)
@ -668,7 +657,7 @@ namespace ENI2
private void ShortCutValidate(object sender, ExecutedRoutedEventArgs e)
{
this.DetailControl_RequestValidate(true);
this.DetailControl_RequestValidate();
}
private void DetailControl_RequestReload(Guid id)
@ -707,13 +696,7 @@ namespace ENI2
private void DetailControl_RequestSendValidation()
{
DetailControl_RequestSendValidationAsync();
}
private async void DetailControl_RequestSendValidationAsync()
{
ValidationResult result = await ValidateAndApplyAsync(false);
List<MessageError> errorList = result.Errors;
this.Validate(false, out _, out List<MessageError> errorList);
foreach (Message aMessage in this._messages)
{
@ -787,66 +770,28 @@ namespace ENI2
}
}
private async void DetailControl_RequestValidate(bool showDialog)
private void DetailControl_RequestValidate()
{
await ValidateAndApplyAsync(showDialog);
this.Validate(true, out _, out _);
}
private async Task<ValidationResult> ValidateAndApplyAsync(bool showMessages)
private void Validate(bool showMessages, out List<MessageViolation> vViolations, out List<MessageError> vErrors)
{
Task<ValidationResult> validationTask = null;
lock (validationLock)
{
if (activeValidationTask != null && !activeValidationTask.IsCompleted)
{
if (showMessages)
pendingShowMessages = true;
validationTask = activeValidationTask;
}
else
{
pendingShowMessages = showMessages;
activeValidationTask = ValidateAndApplyCoreAsync();
validationTask = activeValidationTask;
}
}
vViolations = new List<MessageViolation>();
vErrors = new List<MessageError>();
return await validationTask;
}
// TODO: clear highlighting
private async Task<ValidationResult> ValidateAndApplyCoreAsync()
{
Util.UIHelper.SetBusyState();
ApplyCrewEffectsWarningSuppression();
List<Message> messagesSnapshot = _messages.ToList();
ValidationResult result = await Task.Run(() => ValidateCore(messagesSnapshot));
bool showMessages;
lock (validationLock)
{
showMessages = pendingShowMessages;
pendingShowMessages = false;
activeValidationTask = null;
}
ApplyValidationResult(result, showMessages);
return result;
}
private ValidationResult ValidateCore(List<Message> messagesSnapshot)
{
List<MessageViolation> vViolations = new List<MessageViolation>();
List<MessageError> vErrors = new List<MessageError>();
RuleEngine ruleEngine = new RuleEngine();
foreach (Message aMessage in messagesSnapshot)
foreach (Message aMessage in _messages)
{
if (!aMessage.EvaluateForValidation(this.Core.IsTransit)) continue;
List<MessageError> errors = new List<MessageError>();
List<MessageViolation> violations = new List<MessageViolation>();
ruleEngine.ValidateMessage(aMessage, out errors, out violations);
ruleEngine.ValidateMessage(aMessage, out errors, out violations);
string messageGroup = this.MessageGroupForMessage(aMessage);
@ -862,22 +807,22 @@ namespace ENI2
vViolations.AddRange(violations);
}
#region 12.11.18 / 6.3.21 / 23.5.22 / 26.10.24 / 27.1.26: globale Plausi-Prüfungen
#region 12.11.18 / 6.3.21 / 23.5.22 / 26.10.24: globale Plausi-Prüfungen
Message crewaMessage = messagesSnapshot.Find(message => message.MessageNotificationClass == Message.NotificationClass.CREWA);
Message crewdMessage = messagesSnapshot.Find(message => message.MessageNotificationClass == Message.NotificationClass.CREWD);
Message pasaMessage = messagesSnapshot.Find(message => message.MessageNotificationClass == Message.NotificationClass.PASA);
Message pasdMessage = messagesSnapshot.Find(message => message.MessageNotificationClass == Message.NotificationClass.PASD);
Message pobaMessage = messagesSnapshot.Find(message => message.MessageNotificationClass == Message.NotificationClass.POBA);
Message pobdMessage = messagesSnapshot.Find(message => message.MessageNotificationClass == Message.NotificationClass.POBD);
Message secMessage = messagesSnapshot.Find(message => message.MessageNotificationClass == Message.NotificationClass.SEC);
Message noanodMessage = messagesSnapshot.Find(message => message.MessageNotificationClass == Message.NotificationClass.NOA_NOD);
Message mdhMessage = messagesSnapshot.Find(message => message.MessageNotificationClass == Message.NotificationClass.MDH);
Message was_rcptMessage = messagesSnapshot.Find(message => message.MessageNotificationClass == Message.NotificationClass.WAS_RCPT);
Message wasMessage = messagesSnapshot.Find(message => message.MessageNotificationClass == Message.NotificationClass.WAS);
Message servMessage = messagesSnapshot.Find(message => message.MessageNotificationClass == Message.NotificationClass.SERV);
Message statMessage = messagesSnapshot.Find(message => message.MessageNotificationClass == Message.NotificationClass.STAT);
Message pre72hMessage = messagesSnapshot.Find(message => message.MessageNotificationClass == Message.NotificationClass.PRE72H);
Message crewaMessage = _messages.Find(message => message.MessageNotificationClass == Message.NotificationClass.CREWA);
Message crewdMessage = _messages.Find(message => message.MessageNotificationClass == Message.NotificationClass.CREWD);
Message pasaMessage = _messages.Find(message => message.MessageNotificationClass == Message.NotificationClass.PASA);
Message pasdMessage = _messages.Find(message => message.MessageNotificationClass == Message.NotificationClass.PASD);
Message pobaMessage = _messages.Find(message => message.MessageNotificationClass == Message.NotificationClass.POBA);
Message pobdMessage = _messages.Find(message => message.MessageNotificationClass == Message.NotificationClass.POBD);
Message secMessage = _messages.Find(message => message.MessageNotificationClass == Message.NotificationClass.SEC);
Message noanodMessage = _messages.Find(message => message.MessageNotificationClass == Message.NotificationClass.NOA_NOD);
Message mdhMessage = _messages.Find(message => message.MessageNotificationClass == Message.NotificationClass.MDH);
Message was_rcptMessage = _messages.Find(message => message.MessageNotificationClass == Message.NotificationClass.WAS_RCPT);
Message wasMessage = _messages.Find(message => message.MessageNotificationClass == Message.NotificationClass.WAS);
Message servMessage = _messages.Find(message => message.MessageNotificationClass == Message.NotificationClass.SERV);
Message statMessage = _messages.Find(message => message.MessageNotificationClass == Message.NotificationClass.STAT);
Message pre72hMessage = _messages.Find(message => message.MessageNotificationClass == Message.NotificationClass.PRE72H);
#region CREW / PAS Count Plausibility
@ -1017,6 +962,22 @@ namespace ENI2
#endregion
#region 4.1.23 no CREW effects warning for DE
if (crewaMessage != null)
{
MessageViolation mv = crewaMessage.ViolationList.Find((x) => x.PropertyName.Equals("Effects") && (x.ViolationCode == (int)ValidationCode.TRUNCATE));
if ((mv != null) && !Core.IsDK)
crewaMessage.ViolationList.Remove(mv);
}
if(crewdMessage != null)
{
MessageViolation mvd = crewdMessage.ViolationList.Find((x) => x.PropertyName.Equals("Effects") && (x.ViolationCode == (int)ValidationCode.TRUNCATE));
if ((mvd != null) && !Core.IsDK)
crewdMessage.ViolationList.Remove(mvd);
}
#endregion
#region WAS_RCPT double numbers
Dictionary<string, string> identDict = new Dictionary<string, string>();
@ -1044,37 +1005,35 @@ namespace ENI2
#region Kiel Canal Timing Plausibility
if (!this.Core.IsTransit && (secMessage?.Elements.Count > 0) && (noanodMessage?.Elements.Count > 0))
{
if (!this.Core.IsTransit && (secMessage?.Elements.Count > 0) && (noanodMessage?.Elements.Count > 0))
SEC sec = secMessage.Elements[0] as SEC;
NOA_NOD noa_nod = noanodMessage.Elements[0] as NOA_NOD;
if (sec.KielCanalPassagePlanned ?? false)
{
SEC sec = secMessage.Elements[0] as SEC;
NOA_NOD noa_nod = noanodMessage.Elements[0] as NOA_NOD;
// Überprüfung, ob die eingehende NOK-Durchfahrt auch wirklich innerhalb der eingehenden Reise liegt (bei VISIT)
bool isValidIncoming = (noa_nod.ETDFromLastPort < sec.KielCanalPassagePlannedIncomming) &&
(sec.KielCanalPassagePlannedIncomming < noa_nod.ETAToPortOfCall);
if (!sec.KielCanalPassagePlannedIncomming.HasValue) isValidIncoming = true;
if (sec.KielCanalPassagePlanned ?? false)
if(!isValidIncoming)
{
// Überprüfung, ob die eingehende NOK-Durchfahrt auch wirklich innerhalb der eingehenden Reise liegt (bei VISIT)
bool isValidIncoming = (noa_nod.ETDFromLastPort < sec.KielCanalPassagePlannedIncomming) &&
(sec.KielCanalPassagePlannedIncomming < noa_nod.ETAToPortOfCall);
if (!sec.KielCanalPassagePlannedIncomming.HasValue) isValidIncoming = true;
if (!isValidIncoming)
{
MessageViolation mv = RuleEngine.CreateViolation(ValidationCode.IMPLAUSIBLE, "Kiel Canal incoming implausible (ETD / ETA ports)!", null, "Kiel Canal timing", null, "SEC");
mv.MessageGroupName = Properties.Resources.textOverview;
vViolations.Add(mv);
}
MessageViolation mv = RuleEngine.CreateViolation(ValidationCode.IMPLAUSIBLE, "Kiel Canal incoming implausible (ETD / ETA ports)!", null, "Kiel Canal timing", null, "SEC");
mv.MessageGroupName = Properties.Resources.textOverview;
vViolations.Add(mv);
}
bool isValidOutgoing = (noa_nod.ETDFromPortOfCall < sec.KielCanalPassagePlannedOutgoing) &&
((noa_nod.NextPort == "ZZUKN") || (sec.KielCanalPassagePlannedOutgoing < noa_nod.ETAToNextPort));
if (!sec.KielCanalPassagePlannedOutgoing.HasValue) isValidOutgoing = true;
bool isValidOutgoing = (noa_nod.ETDFromPortOfCall < sec.KielCanalPassagePlannedOutgoing) &&
((noa_nod.NextPort == "ZZUKN") || (sec.KielCanalPassagePlannedOutgoing < noa_nod.ETAToNextPort));
if (!sec.KielCanalPassagePlannedOutgoing.HasValue) isValidOutgoing = true;
if (!isValidOutgoing)
{
MessageViolation mv = RuleEngine.CreateViolation(ValidationCode.IMPLAUSIBLE, "Kiel Canal outgoing implausible (ETD / ETA ports)!", null, "Kiel Canal timing", null, "SEC");
mv.MessageGroupName = Properties.Resources.textOverview;
vViolations.Add(mv);
}
if(!isValidOutgoing)
{
MessageViolation mv = RuleEngine.CreateViolation(ValidationCode.IMPLAUSIBLE, "Kiel Canal outgoing implausible (ETD / ETA ports)!", null, "Kiel Canal timing", null, "SEC");
mv.MessageGroupName = Properties.Resources.textOverview;
vViolations.Add(mv);
}
}
}
@ -1231,133 +1190,19 @@ namespace ENI2
#endregion
#region WAS special max capa rules regarding next port
#endregion
foreach (MessageError me in vErrors)
{
string wasMessageGroup = this.MessageGroupForMessage(wasMessage);
// see WAS-Regulation.docx in parent projects misc folder
if ((noanodMessage?.Elements.Count > 0) && wasMessage?.Elements.Count > 0)
{
NOA_NOD noa_nod = noanodMessage.Elements[0] as NOA_NOD;
WAS was = wasMessage.Elements[0] as WAS;
bool isSpecialNextPort = RuleEngine.IsSpecialNextPort(noa_nod.NextPort);
if (isSpecialNextPort)
{
foreach (Waste waste in was.Waste)
{
switch (waste.WasteType)
{
case 101:
case 102:
case 103:
case 104:
case 105:
case 401:
if (waste.WasteAmountRetained_MTQ > waste.WasteCapacity_MTQ * 0.5)
{
MessageViolation mv = RuleEngine.CreateViolation(ValidationCode.IMPLAUSIBLE, "Acc. to EU Regulation 2022/89 the amount retained on board is noticeably", null, "Waste", waste.Identifier, was.Tablename);
mv.MessageGroupName = wasMessageGroup;
vViolations.Add(mv);
}
break;
case 501:
case 502:
case 503:
case 504:
case 505:
case 506:
case 507:
case 508:
case 509:
case 510:
case 511:
if (waste.WasteAmountRetained_MTQ > waste.WasteCapacity_MTQ * 0.25)
{
MessageViolation mv = RuleEngine.CreateViolation(ValidationCode.IMPLAUSIBLE, "Acc. to EU Regulation 2022/89 the amount retained on board is noticeably", null, "Waste", waste.Identifier, was.Tablename);
mv.MessageGroupName = wasMessageGroup;
vViolations.Add(mv);
}
break;
case 601:
case 602:
if (waste.WasteAmountRetained_MTQ > waste.WasteCapacity_MTQ * 0.75)
{
MessageViolation mv = RuleEngine.CreateViolation(ValidationCode.IMPLAUSIBLE, "Acc. to EU Regulation 2022/89 the amount retained on board is noticeably", null, "Waste", waste.Identifier, was.Tablename);
mv.MessageGroupName = wasMessageGroup;
vViolations.Add(mv);
}
break;
}
}
}
else
{
foreach (Waste waste in was.Waste)
{
switch (waste.WasteType)
{
case 101:
case 102:
case 103:
case 104:
case 105:
if (waste.WasteAmountRetained_MTQ > waste.WasteCapacity_MTQ * 0.25)
{
MessageViolation mv = RuleEngine.CreateViolation(ValidationCode.IMPLAUSIBLE, "Acc. to EU Regulation 2022/89 the amount retained on board is noticeably", null, "Waste", waste.Identifier, was.Tablename);
mv.MessageGroupName = wasMessageGroup;
vViolations.Add(mv);
}
break;
case 401:
if (waste.WasteAmountRetained_MTQ > waste.WasteCapacity_MTQ * 0.5)
{
MessageViolation mv = RuleEngine.CreateViolation(ValidationCode.IMPLAUSIBLE, "Acc. to EU Regulation 2022/89 the amount retained on board is noticeably", null, "Waste", waste.Identifier, was.Tablename);
mv.MessageGroupName = wasMessageGroup;
vViolations.Add(mv);
}
break;
case 501:
case 502:
case 503:
case 504:
case 505:
case 506:
case 507:
case 508:
case 509:
case 510:
case 511:
if (waste.WasteAmountRetained_MTQ > waste.WasteCapacity_MTQ * 0.2)
{
MessageViolation mv = RuleEngine.CreateViolation(ValidationCode.IMPLAUSIBLE, "Acc. to EU Regulation 2022/89 the amount retained on board is noticeably", null, "Waste", waste.Identifier, was.Tablename);
mv.MessageGroupName = wasMessageGroup;
vViolations.Add(mv);
}
break;
case 601:
case 602:
if (waste.WasteAmountRetained_MTQ > waste.WasteCapacity_MTQ * 0.25)
{
MessageViolation mv = RuleEngine.CreateViolation(ValidationCode.IMPLAUSIBLE, "Acc. to EU Regulation 2022/89 the amount retained on board is noticeably", null, "Waste", waste.Identifier, was.Tablename);
mv.MessageGroupName = wasMessageGroup;
vViolations.Add(mv);
}
break;
}
}
}
}
this.highlightService.HighlightError(me, this.GetContainerForMessageGroupName(me.MessageGroupName));
}
foreach (MessageViolation mv in vViolations)
{
this.highlightService.HighlightViolation(mv, this.GetContainerForMessageGroupName(mv.MessageGroupName));
}
#endregion
#endregion
// "neue" regelbasierte Validierung: Hier werden die einzelnen Regeln geprüft.
bsmd.database.ValidationRule.PrepareNameLookupDict(this.Core, messagesSnapshot);
bsmd.database.ValidationRule.PrepareNameLookupDict(this.Core, this._messages);
List<bsmd.database.ValidationRule> validationRules = DBManager.Instance.GetValidationRules();
@ -1384,94 +1229,10 @@ namespace ENI2
}
}
// Recompute per-message counts after all global validations
Dictionary<Message, MessageValidationCounts> counts = new Dictionary<Message, MessageValidationCounts>();
int assignViolationCounter = 0;
int assignErrorCounter = 0;
List<MessageViolation> tmpVList = new List<MessageViolation>(vViolations);
List<MessageError> tmpEList = new List<MessageError>(vErrors);
foreach (Message aMessage in messagesSnapshot)
{
counts[aMessage] = new MessageValidationCounts();
counts[aMessage].ErrorCount = tmpEList.Count(me => me.NotificationClass == aMessage.MessageNotificationClassDisplay); // generic
// special cases
counts[aMessage].ErrorCount += tmpEList.Count(me => (aMessage.MessageNotificationClass == Message.NotificationClass.WAS_RCPT) && (me.NotificationClass == "WasteReceived"));
counts[aMessage].ErrorCount += tmpEList.Count(me => (aMessage.MessageNotificationClass == Message.NotificationClass.HAZA) && (me.NotificationClass == "IMDGPosition") && me.MessageGroupName.Contains("arrival", StringComparison.OrdinalIgnoreCase));
counts[aMessage].ErrorCount += tmpEList.Count(me => (aMessage.MessageNotificationClass == Message.NotificationClass.HAZA) && (me.NotificationClass == "IGCPosition") && me.MessageGroupName.Contains("arrival", StringComparison.OrdinalIgnoreCase));
counts[aMessage].ErrorCount += tmpEList.Count(me => (aMessage.MessageNotificationClass == Message.NotificationClass.HAZA) && (me.NotificationClass == "IBCPosition") && me.MessageGroupName.Contains("arrival", StringComparison.OrdinalIgnoreCase));
counts[aMessage].ErrorCount += tmpEList.Count(me => (aMessage.MessageNotificationClass == Message.NotificationClass.HAZA) && (me.NotificationClass == "IMSBCPosition") && me.MessageGroupName.Contains("arrival", StringComparison.OrdinalIgnoreCase));
counts[aMessage].ErrorCount += tmpEList.Count(me => (aMessage.MessageNotificationClass == Message.NotificationClass.HAZA) && (me.NotificationClass == "MARPOL_Annex_I_Position") && me.MessageGroupName.Contains("arrival", StringComparison.OrdinalIgnoreCase));
counts[aMessage].ErrorCount += tmpEList.Count(me => (aMessage.MessageNotificationClass == Message.NotificationClass.HAZD) && (me.NotificationClass == "IMDGPosition") && me.MessageGroupName.Contains("departure", StringComparison.OrdinalIgnoreCase));
counts[aMessage].ErrorCount += tmpEList.Count(me => (aMessage.MessageNotificationClass == Message.NotificationClass.HAZD) && (me.NotificationClass == "IGCPosition") && me.MessageGroupName.Contains("departure", StringComparison.OrdinalIgnoreCase));
counts[aMessage].ErrorCount += tmpEList.Count(me => (aMessage.MessageNotificationClass == Message.NotificationClass.HAZD) && (me.NotificationClass == "IBCPosition") && me.MessageGroupName.Contains("departure", StringComparison.OrdinalIgnoreCase));
counts[aMessage].ErrorCount += tmpEList.Count(me => (aMessage.MessageNotificationClass == Message.NotificationClass.HAZD) && (me.NotificationClass == "IMSBCPosition") && me.MessageGroupName.Contains("departure", StringComparison.OrdinalIgnoreCase));
counts[aMessage].ErrorCount += tmpEList.Count(me => (aMessage.MessageNotificationClass == Message.NotificationClass.HAZD) && (me.NotificationClass == "MARPOL_Annex_I_Position") && me.MessageGroupName.Contains("departure", StringComparison.OrdinalIgnoreCase));
counts[aMessage].ErrorCount += tmpEList.Count(me => (aMessage.MessageNotificationClass == Message.NotificationClass.WAS) && (me.NotificationClass == "Waste"));
counts[aMessage].ErrorCount += tmpEList.Count(me => (aMessage.MessageNotificationClass == Message.NotificationClass.SEC) && (me.NotificationClass == "LastTenPortFacilitiesCalled"));
counts[aMessage].ErrorCount += tmpEList.Count(me => (aMessage.MessageNotificationClass == Message.NotificationClass.SEC) && (me.NotificationClass == "ShipToShipActivitiesDuringLastTenPortFacilitiesCalled"));
if (counts[aMessage].ErrorCount == 0) counts[aMessage].ErrorCount = null; // set to empty if nothing counted
assignErrorCounter += counts[aMessage].ErrorCount ?? 0;
counts[aMessage].ViolationCount = vViolations.Count(mv => mv.NotificationClass == aMessage.MessageNotificationClassDisplay); // generic
// special cases
counts[aMessage].ViolationCount += tmpVList.Count(me => (aMessage.MessageNotificationClass == Message.NotificationClass.WAS_RCPT) && (me.NotificationClass == "WasteReceived"));
counts[aMessage].ViolationCount += tmpVList.Count(me => (aMessage.MessageNotificationClass == Message.NotificationClass.HAZA) && (me.NotificationClass == "IMDGPosition") && me.MessageGroupName.Contains("arrival", StringComparison.OrdinalIgnoreCase));
counts[aMessage].ViolationCount += tmpVList.Count(me => (aMessage.MessageNotificationClass == Message.NotificationClass.HAZA) && (me.NotificationClass == "IGCPosition") && me.MessageGroupName.Contains("arrival", StringComparison.OrdinalIgnoreCase));
counts[aMessage].ViolationCount += tmpVList.Count(me => (aMessage.MessageNotificationClass == Message.NotificationClass.HAZA) && (me.NotificationClass == "IBCPosition") && me.MessageGroupName.Contains("arrival", StringComparison.OrdinalIgnoreCase));
counts[aMessage].ViolationCount += tmpVList.Count(me => (aMessage.MessageNotificationClass == Message.NotificationClass.HAZA) && (me.NotificationClass == "IMSBCPosition") && me.MessageGroupName.Contains("arrival", StringComparison.OrdinalIgnoreCase));
counts[aMessage].ViolationCount += tmpVList.Count(me => (aMessage.MessageNotificationClass == Message.NotificationClass.HAZA) && (me.NotificationClass == "MARPOL_Annex_I_Position") && me.MessageGroupName.Contains("arrival", StringComparison.OrdinalIgnoreCase));
counts[aMessage].ViolationCount += tmpVList.Count(me => (aMessage.MessageNotificationClass == Message.NotificationClass.HAZD) && (me.NotificationClass == "IMDGPosition") && me.MessageGroupName.Contains("departure", StringComparison.OrdinalIgnoreCase));
counts[aMessage].ViolationCount += tmpVList.Count(me => (aMessage.MessageNotificationClass == Message.NotificationClass.HAZD) && (me.NotificationClass == "IGCPosition") && me.MessageGroupName.Contains("departure", StringComparison.OrdinalIgnoreCase));
counts[aMessage].ViolationCount += tmpVList.Count(me => (aMessage.MessageNotificationClass == Message.NotificationClass.HAZD) && (me.NotificationClass == "IBCPosition") && me.MessageGroupName.Contains("departure", StringComparison.OrdinalIgnoreCase));
counts[aMessage].ViolationCount += tmpVList.Count(me => (aMessage.MessageNotificationClass == Message.NotificationClass.HAZD) && (me.NotificationClass == "IMSBCPosition") && me.MessageGroupName.Contains("departure", StringComparison.OrdinalIgnoreCase));
counts[aMessage].ViolationCount += tmpVList.Count(me => (aMessage.MessageNotificationClass == Message.NotificationClass.HAZD) && (me.NotificationClass == "MARPOL_Annex_I_Position") && me.MessageGroupName.Contains("departure", StringComparison.OrdinalIgnoreCase));
counts[aMessage].ViolationCount += tmpVList.Count(me => (aMessage.MessageNotificationClass == Message.NotificationClass.WAS) && (me.NotificationClass == "Waste"));
counts[aMessage].ViolationCount += tmpVList.Count(me => (aMessage.MessageNotificationClass == Message.NotificationClass.SEC) && (me.NotificationClass == "LastTenPortFacilitiesCalled"));
counts[aMessage].ViolationCount += tmpVList.Count(me => (aMessage.MessageNotificationClass == Message.NotificationClass.SEC) && (me.NotificationClass == "ShipToShipActivitiesDuringLastTenPortFacilitiesCalled"));
if (counts[aMessage].ViolationCount == 0) counts[aMessage].ViolationCount = null;
assignViolationCounter += counts[aMessage].ViolationCount ?? 0;
}
Trace.WriteLine(string.Format("Unassigned errors: {0}, unassigned violations: {1}", vErrors.Count - assignErrorCounter, vViolations.Count - assignViolationCounter));
return new ValidationResult(vViolations, vErrors, counts);
}
private void ApplyValidationResult(ValidationResult result, bool showMessages)
{
// TODO: clear highlighting
foreach (KeyValuePair<Message, MessageValidationCounts> entry in result.Counts)
{
Message aMessage = entry.Key;
MessageValidationCounts messageCounts = entry.Value;
aMessage.ErrorCount = messageCounts.ErrorCount;
aMessage.ViolationCount = messageCounts.ViolationCount;
}
foreach (MessageError me in result.Errors)
{
this.highlightService.HighlightError(me, this.GetContainerForMessageGroupName(me.MessageGroupName));
}
foreach (MessageViolation mv in result.Violations)
{
this.highlightService.HighlightViolation(mv, this.GetContainerForMessageGroupName(mv.MessageGroupName));
}
if (showMessages)
{
// Show error and violation dialog
if (result.Errors.Count > 0)
if (vErrors.Count > 0)
{
if(this._errorListDialog == null)
{
@ -1486,10 +1247,10 @@ namespace ENI2
{
this._errorListDialog.BringUp();
}
this._errorListDialog.Errors = result.Errors;
this._errorListDialog.Errors = vErrors;
}
if (result.Violations.Count > 0)
if (vViolations.Count > 0)
{
if(this._violationListDialog == null)
{
@ -1504,67 +1265,20 @@ namespace ENI2
{
this._violationListDialog.BringUp();
}
_violationListDialog.Violations = result.Violations;
_violationListDialog.Violations = vViolations;
}
if((result.Errors.Count == 0) && (result.Violations.Count == 0))
if((vErrors.Count == 0) && (vViolations.Count == 0))
{
MessageBox.Show(Properties.Resources.textValidationOK, Properties.Resources.textValidation, MessageBoxButton.OK, MessageBoxImage.Information);
}
}
if (controlCache.TryGetValue(Properties.Resources.textOverview, out DetailBaseControl overviewControl) &&
overviewControl is OverViewDetailControl ovdc)
{
ovdc.RefreshMessageGrid();
}
}
private void ApplyCrewEffectsWarningSuppression()
{
// 4.1.23 no CREW effects warning for DE
Message crewaMessage = _messages.Find(message => message.MessageNotificationClass == Message.NotificationClass.CREWA);
Message crewdMessage = _messages.Find(message => message.MessageNotificationClass == Message.NotificationClass.CREWD);
if (crewaMessage != null)
{
MessageViolation mv = crewaMessage.ViolationList.Find((x) => x.PropertyName.Equals("Effects") && (x.ViolationCode == (int)ValidationCode.TRUNCATE));
if ((mv != null) && !Core.IsDK)
crewaMessage.ViolationList.Remove(mv);
}
if(crewdMessage != null)
{
MessageViolation mvd = crewdMessage.ViolationList.Find((x) => x.PropertyName.Equals("Effects") && (x.ViolationCode == (int)ValidationCode.TRUNCATE));
if ((mvd != null) && !Core.IsDK)
crewdMessage.ViolationList.Remove(mvd);
}
}
private sealed class ValidationResult
{
internal ValidationResult(List<MessageViolation> violations, List<MessageError> errors, Dictionary<Message, MessageValidationCounts> counts)
{
Violations = violations;
Errors = errors;
Counts = counts;
}
internal List<MessageViolation> Violations { get; }
internal List<MessageError> Errors { get; }
internal Dictionary<Message, MessageValidationCounts> Counts { get; }
}
private sealed class MessageValidationCounts
{
internal int? ErrorCount { get; set; }
internal int? ViolationCount { get; set; }
internal int? PositionViolationCount { get; set; }
}
private void _errorListDialog_RefreshClicked()
{
DetailControl_RequestValidate(true);
DetailControl_RequestValidate();
}
private void _errorListDialog_ErrorSelected(DatabaseEntity obj)

View File

@ -11,7 +11,7 @@ using System.Windows.Controls;
using ENI2.EditControls;
using ENI2.Util;
using ENI2.Locode;
using ClosedXML.Excel;
using ExcelDataReader;
using bsmd.database;
using System.Windows.Media.Imaging;
using System.Linq;
@ -1049,68 +1049,72 @@ namespace ENI2.DetailViewControls
};
if (ofd.ShowDialog() ?? false)
{
FileStream stream;
try
{
using (var stream = new FileStream(ofd.FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var workbook = new XLWorkbook(stream))
{
var worksheet = workbook.Worksheet(1); // Get first worksheet
var rows = worksheet.RangeUsed().RowsUsed().Skip(1); // Skip header row if present
List<CREW> importCrew = new List<CREW>();
foreach (var row in rows)
{
if (row.RowNumber() > worksheet.RangeUsed().RowCount()) break;
// Check if we have at least 13 columns
if (worksheet.RangeUsed().ColumnCount() < 13)
{
throw new InvalidDataException("Sheet must have 13 columns of data");
}
CREW crew = new CREW();
// Check if first two cells are empty
if (row.Cell(1).IsEmpty() && row.Cell(2).IsEmpty()) continue;
if (!row.Cell(1).IsEmpty()) crew.CrewMemberLastName = row.Cell(1).GetString().Clean();
if (crew.CrewMemberLastName?.Equals("Family Name") == true || string.IsNullOrWhiteSpace(crew.CrewMemberLastName)) continue;
if (!row.Cell(2).IsEmpty()) crew.CrewMemberFirstName = row.Cell(2).GetString().Clean();
if (!row.Cell(3).IsEmpty()) crew.CrewMemberGender = GlobalStructures.ParseGender(row.Cell(3).GetString());
if (!row.Cell(4).IsEmpty()) crew.CrewMemberDuty = row.Cell(4).GetString().Clean();
if (!row.Cell(5).IsEmpty()) crew.CrewMemberNationality = row.Cell(5).GetString().Substring(0, 2).ToUpper();
if (!row.Cell(6).IsEmpty()) crew.CrewMemberPlaceOfBirth = row.Cell(6).GetString().Clean();
if (!row.Cell(7).IsEmpty()) crew.CrewMemberCountryOfBirth = row.Cell(7).GetString().Substring(0, 2).ToUpper();
if (!row.Cell(8).IsEmpty()) crew.CrewMemberDateOfBirth = row.Cell(8).GetDateTime();
if (!row.Cell(9).IsEmpty()) crew.CrewMemberIdentityDocumentType = GlobalStructures.ReadIdentityDocumentType(row.Cell(9).GetString());
if (!row.Cell(10).IsEmpty()) crew.CrewMemberIdentityDocumentId = row.Cell(10).GetString().Clean();
if (!row.Cell(11).IsEmpty()) crew.CrewMemberIdentityDocumentIssuingState = row.Cell(11).GetString().Substring(0, 2).ToUpper();
if (!row.Cell(12).IsEmpty()) crew.CrewMemberIdentityDocumentExpiryDate = row.Cell(12).GetDateTime();
if (!row.Cell(13).IsEmpty()) crew.CrewMemberVisaNumber = row.Cell(13).GetString().Clean();
crew.MessageHeader = this._crewMessage;
crew.IsDirty = true;
crew.Identifier = CREW.GetNewIdentifier(this._crewMessage.Elements);
this._crewMessage.Elements.Add(crew);
importCrew.Add(crew);
}
if (importCrew.Count > 0)
{
this.dataGridCrewList.Items.Refresh();
this.SublistElementChanged(Message.NotificationClass.CREWA);
MessageBox.Show(String.Format(Properties.Resources.textCrewImported, importCrew.Count), Properties.Resources.textCaptionInformation, MessageBoxButton.OK, MessageBoxImage.Information);
}
}
stream = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read);
}
catch (Exception ex)
{
MessageBox.Show("Error reading Excel: " + ex.Message, Properties.Resources.textCaptionError, MessageBoxButton.OK, MessageBoxImage.Error);
MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
using (IExcelDataReader reader = ExcelReaderFactory.CreateReader(stream))
{
List<CREW> importCrew = new List<CREW>();
try
{
do
{
while (reader.Read())
{
if(reader.FieldCount < 13)
{
throw new InvalidDataException("Sheet must have 13 columns of data");
}
CREW crew = new CREW();
if (reader.IsDBNull(0) && reader.IsDBNull(1)) continue;
if (!reader.IsDBNull(0)) crew.CrewMemberLastName = reader.GetString(0).Clean();
if (crew.CrewMemberLastName.Equals("Family Name") || (crew.CrewMemberLastName.Trim().Length == 0)) continue;
if (!reader.IsDBNull(1)) crew.CrewMemberFirstName = reader.GetString(1).Clean();
if (!reader.IsDBNull(2)) crew.CrewMemberGender = GlobalStructures.ParseGender(reader.GetString(2));
if (!reader.IsDBNull(3)) crew.CrewMemberDuty = reader.GetString(3).Clean();
if (!reader.IsDBNull(4)) crew.CrewMemberNationality = reader.GetString(4).Substring(0, 2).ToUpper();
if (!reader.IsDBNull(5)) crew.CrewMemberPlaceOfBirth = reader.GetString(5).Clean();
if (!reader.IsDBNull(6)) crew.CrewMemberCountryOfBirth = reader.GetString(6).Substring(0, 2).ToUpper();
if (!reader.IsDBNull(7)) crew.CrewMemberDateOfBirth = reader.GetDateTime(7);
if (!reader.IsDBNull(8)) crew.CrewMemberIdentityDocumentType = GlobalStructures.ReadIdentityDocumentType(reader.GetString(8));
if (!reader.IsDBNull(9)) crew.CrewMemberIdentityDocumentId = reader.ReadAsString(9).Clean();
if (!reader.IsDBNull(10)) crew.CrewMemberIdentityDocumentIssuingState = reader.GetString(10).Substring(0, 2).ToUpper();
if (!reader.IsDBNull(11)) crew.CrewMemberIdentityDocumentExpiryDate = reader.GetDateTime(11);
if (!reader.IsDBNull(12)) crew.CrewMemberVisaNumber = reader.ReadAsString(12).Clean();
crew.MessageHeader = this._crewMessage;
crew.IsDirty = true;
crew.Identifier = CREW.GetNewIdentifier(this._crewMessage.Elements);
this._crewMessage.Elements.Add(crew);
importCrew.Add(crew);
}
} while (reader.NextResult());
}
catch (Exception ex)
{
MessageBox.Show("Error reading Excel: " + ex.Message, Properties.Resources.textCaptionError, MessageBoxButton.OK, MessageBoxImage.Error);
}
if (importCrew.Count > 0)
{
this.dataGridCrewList.Items.Refresh();
this.SublistElementChanged(Message.NotificationClass.CREWA);
MessageBox.Show(String.Format(Properties.Resources.textCrewImported, importCrew.Count), Properties.Resources.textCaptionInformation, MessageBoxButton.OK, MessageBoxImage.Information);
}
}
stream.Close();
}
}
}
private void buttonImportExcelCrewDeparture_Click(object sender, RoutedEventArgs e)
{
@ -1120,69 +1124,74 @@ namespace ENI2.DetailViewControls
};
if (ofd.ShowDialog() ?? false)
{
FileStream stream;
try
{
using (var stream = new FileStream(ofd.FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var workbook = new XLWorkbook(stream))
{
var worksheet = workbook.Worksheet(1); // Get first worksheet
var rows = worksheet.RangeUsed().RowsUsed().Skip(1); // Skip header row if present
List<CREWD> importCrew = new List<CREWD>();
foreach (var row in rows)
{
if (row.RowNumber() > worksheet.RangeUsed().RowCount()) break;
// Check if we have at least 13 columns
if (worksheet.RangeUsed().ColumnCount() < 13)
{
throw new InvalidDataException("Sheet must have 13 columns of data");
}
CREWD crew = new CREWD();
crew.IsDeparture = true;
// Check if first two cells are empty
if (row.Cell(1).IsEmpty() && row.Cell(2).IsEmpty()) continue;
if (!row.Cell(1).IsEmpty()) crew.CrewMemberLastName = row.Cell(1).GetString().Clean();
if (crew.CrewMemberLastName?.Equals("Family Name") == true || string.IsNullOrWhiteSpace(crew.CrewMemberLastName)) continue;
if (!row.Cell(2).IsEmpty()) crew.CrewMemberFirstName = row.Cell(2).GetString().Clean();
if (!row.Cell(3).IsEmpty()) crew.CrewMemberGender = GlobalStructures.ParseGender(row.Cell(3).GetString());
if (!row.Cell(4).IsEmpty()) crew.CrewMemberDuty = row.Cell(4).GetString().Clean();
if (!row.Cell(5).IsEmpty()) crew.CrewMemberNationality = row.Cell(5).GetString().Substring(0, 2).ToUpper();
if (!row.Cell(6).IsEmpty()) crew.CrewMemberPlaceOfBirth = row.Cell(6).GetString().Clean();
if (!row.Cell(7).IsEmpty()) crew.CrewMemberCountryOfBirth = row.Cell(7).GetString().Substring(0, 2).ToUpper();
if (!row.Cell(8).IsEmpty()) crew.CrewMemberDateOfBirth = row.Cell(8).GetDateTime();
if (!row.Cell(9).IsEmpty()) crew.CrewMemberIdentityDocumentType = GlobalStructures.ReadIdentityDocumentType(row.Cell(9).GetString());
if (!row.Cell(10).IsEmpty()) crew.CrewMemberIdentityDocumentId = row.Cell(10).GetString().Clean();
if (!row.Cell(11).IsEmpty()) crew.CrewMemberIdentityDocumentIssuingState = row.Cell(11).GetString().Substring(0, 2).ToUpper();
if (!row.Cell(12).IsEmpty()) crew.CrewMemberIdentityDocumentExpiryDate = row.Cell(12).GetDateTime();
if (!row.Cell(13).IsEmpty()) crew.CrewMemberVisaNumber = row.Cell(13).GetString().Clean();
crew.MessageHeader = this._crewdMessage;
crew.IsDirty = true;
crew.Identifier = CREWD.GetNewIdentifier(this._crewdMessage.Elements);
this._crewdMessage.Elements.Add(crew);
importCrew.Add(crew);
}
if (importCrew.Count > 0)
{
this.dataGridCrewListDeparture.Items.Refresh();
this.SublistElementChanged(Message.NotificationClass.CREWD);
MessageBox.Show(String.Format(Properties.Resources.textCrewImported, importCrew.Count), Properties.Resources.textCaptionInformation, MessageBoxButton.OK, MessageBoxImage.Information);
}
}
stream = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read);
}
catch (Exception ex)
{
MessageBox.Show("Error reading Excel: " + ex.Message, Properties.Resources.textCaptionError, MessageBoxButton.OK, MessageBoxImage.Error);
MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
using (IExcelDataReader reader = ExcelReaderFactory.CreateReader(stream))
{
List<CREWD> importCrew = new List<CREWD>();
try
{
do
{
while (reader.Read())
{
if (reader.FieldCount < 13)
{
throw new InvalidDataException("Sheet must have 13 columns of data");
}
CREWD crew = new CREWD();
crew.IsDeparture = true;
if (reader.IsDBNull(0) && reader.IsDBNull(1)) continue;
if (!reader.IsDBNull(0)) crew.CrewMemberLastName = reader.GetString(0);
if (crew.CrewMemberLastName.Equals("Family Name") || (crew.CrewMemberLastName.Trim().Length == 0)) continue;
if (!reader.IsDBNull(1)) crew.CrewMemberFirstName = reader.GetString(1);
if (!reader.IsDBNull(2)) crew.CrewMemberGender = GlobalStructures.ParseGender(reader.GetString(2));
if (!reader.IsDBNull(3)) crew.CrewMemberDuty = reader.GetString(3).Clean();
if (!reader.IsDBNull(4)) crew.CrewMemberNationality = reader.GetString(4).Substring(0, 2).ToUpper();
if (!reader.IsDBNull(5)) crew.CrewMemberPlaceOfBirth = reader.GetString(5);
if (!reader.IsDBNull(6)) crew.CrewMemberCountryOfBirth = reader.GetString(6).Substring(0, 2).ToUpper();
if (!reader.IsDBNull(7)) crew.CrewMemberDateOfBirth = reader.GetDateTime(7);
if (!reader.IsDBNull(8)) crew.CrewMemberIdentityDocumentType = GlobalStructures.ReadIdentityDocumentType(reader.GetString(8));
if (!reader.IsDBNull(9)) crew.CrewMemberIdentityDocumentId = reader.ReadAsString(9);
if (!reader.IsDBNull(10)) crew.CrewMemberIdentityDocumentIssuingState = reader.GetString(10).Substring(0, 2).ToUpper();
if (!reader.IsDBNull(11)) crew.CrewMemberIdentityDocumentExpiryDate = reader.GetDateTime(11);
if (!reader.IsDBNull(12)) crew.CrewMemberVisaNumber = reader.ReadAsString(12);
crew.MessageHeader = this._crewdMessage;
crew.IsDirty = true;
crew.Identifier = CREWD.GetNewIdentifier(this._crewdMessage.Elements);
this._crewdMessage.Elements.Add(crew);
importCrew.Add(crew);
}
} while (reader.NextResult());
}
catch (Exception ex)
{
MessageBox.Show("Error reading Excel: " + ex.Message, Properties.Resources.textCaptionError, MessageBoxButton.OK, MessageBoxImage.Error);
}
if (importCrew.Count > 0)
{
this.dataGridCrewListDeparture.Items.Refresh();
this.SublistElementChanged(Message.NotificationClass.CREWD);
MessageBox.Show(String.Format(Properties.Resources.textCrewImported, importCrew.Count), Properties.Resources.textCaptionInformation, MessageBoxButton.OK, MessageBoxImage.Information);
}
}
stream.Close();
}
}
}
private void buttonImportExcelPassenger_Click(object sender, RoutedEventArgs e)
{
@ -1192,74 +1201,80 @@ namespace ENI2.DetailViewControls
};
if (ofd.ShowDialog() ?? false)
{
FileStream stream;
try
{
using (var stream = new FileStream(ofd.FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var workbook = new XLWorkbook(stream))
{
var worksheet = workbook.Worksheet(1);
var rows = worksheet.RangeUsed().RowsUsed().Skip(1); // Skip header row if present
List<PAS> importPassenger = new List<PAS>();
foreach (var row in rows)
{
if (row.RowNumber() > worksheet.RangeUsed().RowCount()) break;
if (worksheet.RangeUsed().ColumnCount() < 17)
{
throw new InvalidDataException("Sheet must have 17 columns of data");
}
PAS pas = new PAS();
if (row.Cell(1).IsEmpty() && row.Cell(2).IsEmpty()) continue;
if (!row.Cell(1).IsEmpty()) pas.PassengerLastName = row.Cell(1).GetString().Clean();
if (pas.PassengerLastName?.Equals("Family Name") == true || string.IsNullOrWhiteSpace(pas.PassengerLastName)) continue;
if (!row.Cell(2).IsEmpty()) pas.PassengerFirstName = row.Cell(2).GetString().Clean();
if (!row.Cell(3).IsEmpty()) pas.PassengerGender = GlobalStructures.ParseGender(row.Cell(3).GetString());
if (!row.Cell(4).IsEmpty()) pas.PassengerPortOfEmbarkation = row.Cell(4).GetString().Clean();
if (LocodeDB.PortNameFromLocode(pas.PassengerPortOfEmbarkation) == null)
pas.PassengerPortOfEmbarkation = null;
if (!row.Cell(5).IsEmpty()) pas.PassengerPortOfDisembarkation = row.Cell(5).GetString().Clean();
if (LocodeDB.PortNameFromLocode(pas.PassengerPortOfDisembarkation) == null)
pas.PassengerPortOfDisembarkation = null;
if (!row.Cell(6).IsEmpty()) pas.PassengerInTransit = GlobalStructures.ReadBoolean(row.Cell(6).GetString());
if (!row.Cell(7).IsEmpty()) pas.PassengerNationality = row.Cell(7).GetString().Substring(0, 2).ToUpper();
if (!row.Cell(8).IsEmpty()) pas.PassengerPlaceOfBirth = row.Cell(8).GetString().Clean();
if (!row.Cell(9).IsEmpty()) pas.PassengerCountryOfBirth = row.Cell(9).GetString().Substring(0, 2).ToUpper().Clean();
if (!row.Cell(10).IsEmpty()) pas.PassengerDateOfBirth = row.Cell(10).GetDateTime();
if (!row.Cell(11).IsEmpty()) pas.PassengerIdentityDocumentType = GlobalStructures.ReadIdentityDocumentType(row.Cell(11).GetString());
if (!row.Cell(12).IsEmpty()) pas.PassengerIdentityDocumentId = row.Cell(12).GetString().Clean();
if (!row.Cell(13).IsEmpty()) pas.PassengerIdentityDocumentIssuingState = row.Cell(13).GetString().Substring(0, 2).ToUpper();
if (!row.Cell(14).IsEmpty()) pas.PassengerIdentityDocumentExpiryDate = row.Cell(14).GetDateTime();
if (!row.Cell(15).IsEmpty()) pas.PassengerVisaNumber = row.Cell(15).GetString().Clean();
if (!row.Cell(16).IsEmpty()) pas.EmergencyCare = row.Cell(16).GetString().Clean();
if (!row.Cell(17).IsEmpty()) pas.EmergencyContactNumber = row.Cell(17).GetString().Clean();
pas.MessageHeader = this._pasMessage;
pas.IsDirty = true;
pas.Identifier = PAS.GetNewIdentifier(this._pasMessage.Elements);
this._pasMessage.Elements.Add(pas);
importPassenger.Add(pas);
}
if (importPassenger.Count > 0)
{
this.dataGridPassengerList.Items.Refresh();
this.SublistElementChanged(Message.NotificationClass.PASA);
MessageBox.Show(String.Format(Properties.Resources.textPassengerImported, importPassenger.Count), Properties.Resources.textCaptionInformation, MessageBoxButton.OK, MessageBoxImage.Information);
}
}
stream = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read);
}
catch (Exception ex)
{
MessageBox.Show("Error reading Excel: " + ex.Message, Properties.Resources.textCaptionError, MessageBoxButton.OK, MessageBoxImage.Error);
MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
List<PAS> importPassenger = new List<PAS>();
try
{
do
{
while (reader.Read())
{
if (((IExcelDataReader)reader).FieldCount < 17)
{
throw new InvalidDataException("Sheet must have 17 columns of data");
}
PAS pas = new PAS();
if (reader.IsDBNull(0) && reader.IsDBNull(1)) continue;
if (!reader.IsDBNull(0)) pas.PassengerLastName = reader.GetValue(0).ToString().Clean();
if (pas.PassengerLastName.Equals("Family Name") || (pas.PassengerLastName.Trim().Length == 0)) continue;
if (!reader.IsDBNull(1)) pas.PassengerFirstName = reader.GetValue(1).ToString().Clean();
if (!reader.IsDBNull(2)) pas.PassengerGender = GlobalStructures.ParseGender(reader.GetString(2));
if (!reader.IsDBNull(3)) pas.PassengerPortOfEmbarkation = reader.GetString(3).Clean();
if (LocodeDB.PortNameFromLocode(pas.PassengerPortOfEmbarkation) == null)
pas.PassengerPortOfEmbarkation = null;
if (!reader.IsDBNull(4)) pas.PassengerPortOfDisembarkation = reader.GetString(4).Clean();
if (LocodeDB.PortNameFromLocode(pas.PassengerPortOfDisembarkation) == null)
pas.PassengerPortOfDisembarkation = null;
if (!reader.IsDBNull(5)) pas.PassengerInTransit = GlobalStructures.ReadBoolean(reader.GetString(5));
if (!reader.IsDBNull(6)) pas.PassengerNationality = reader.GetString(6).Substring(0, 2).ToUpper();
if (!reader.IsDBNull(7)) pas.PassengerPlaceOfBirth = reader.GetString(7).Clean();
if (!reader.IsDBNull(8)) pas.PassengerCountryOfBirth = reader.GetString(8).Substring(0, 2).ToUpper().Clean();
if (!reader.IsDBNull(9)) pas.PassengerDateOfBirth = reader.GetDateTime(9);
if (!reader.IsDBNull(10)) pas.PassengerIdentityDocumentType = GlobalStructures.ReadIdentityDocumentType(reader.GetString(10));
if (!reader.IsDBNull(11)) pas.PassengerIdentityDocumentId = reader.ReadAsString(11).Clean();
if (!reader.IsDBNull(12)) pas.PassengerIdentityDocumentIssuingState = reader.GetString(12).Substring(0, 2).ToUpper();
if (!reader.IsDBNull(13)) pas.PassengerIdentityDocumentExpiryDate = reader.GetDateTime(13);
if (!reader.IsDBNull(14)) pas.PassengerVisaNumber = reader.ReadAsString(14).Clean();
if (!reader.IsDBNull(15)) pas.EmergencyCare = reader.GetString(15).Clean();
if (!reader.IsDBNull(16)) pas.EmergencyContactNumber = reader.ReadAsString(16).Clean();
pas.MessageHeader = this._pasMessage;
pas.IsDirty = true;
pas.Identifier = PAS.GetNewIdentifier(this._pasMessage.Elements);
this._pasMessage.Elements.Add(pas);
importPassenger.Add(pas);
}
} while (reader.NextResult());
}
catch (Exception ex)
{
MessageBox.Show("Error reading Excel: " + ex.Message, Properties.Resources.textCaptionError, MessageBoxButton.OK, MessageBoxImage.Error);
}
if (importPassenger.Count > 0)
{
this.dataGridPassengerList.Items.Refresh();
this.SublistElementChanged(Message.NotificationClass.PASA);
MessageBox.Show(String.Format(Properties.Resources.textPassengerImported, importPassenger.Count), Properties.Resources.textCaptionInformation, MessageBoxButton.OK, MessageBoxImage.Information);
}
}
stream.Close();
}
}
}
private void buttonImportExcelPassengerDeparture_Click(object sender, RoutedEventArgs e)
{
@ -1269,74 +1284,80 @@ namespace ENI2.DetailViewControls
};
if (ofd.ShowDialog() ?? false)
{
FileStream stream;
try
{
using (var stream = new FileStream(ofd.FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var workbook = new XLWorkbook(stream))
{
var worksheet = workbook.Worksheet(1);
var rows = worksheet.RangeUsed().RowsUsed().Skip(1); // Skip header row if present
List<PASD> importPassenger = new List<PASD>();
foreach (var row in rows)
{
if (row.RowNumber() > worksheet.RangeUsed().RowCount()) break;
if (worksheet.RangeUsed().ColumnCount() < 17)
{
throw new InvalidDataException("Sheet must have 17 columns of data");
}
PASD pas = new PASD();
if (row.Cell(1).IsEmpty() && row.Cell(2).IsEmpty()) continue;
if (!row.Cell(1).IsEmpty()) pas.PassengerLastName = row.Cell(1).GetString().Clean();
if (pas.PassengerLastName?.Equals("Family Name") == true || string.IsNullOrWhiteSpace(pas.PassengerLastName)) continue;
if (!row.Cell(2).IsEmpty()) pas.PassengerFirstName = row.Cell(2).GetString().Clean();
if (!row.Cell(3).IsEmpty()) pas.PassengerGender = GlobalStructures.ParseGender(row.Cell(3).GetString());
if (!row.Cell(4).IsEmpty()) pas.PassengerPortOfEmbarkation = row.Cell(4).GetString().Clean();
if (LocodeDB.PortNameFromLocode(pas.PassengerPortOfEmbarkation) == null)
pas.PassengerPortOfEmbarkation = null;
if (!row.Cell(5).IsEmpty()) pas.PassengerPortOfDisembarkation = row.Cell(5).GetString().Clean();
if (LocodeDB.PortNameFromLocode(pas.PassengerPortOfDisembarkation) == null)
pas.PassengerPortOfDisembarkation = null;
if (!row.Cell(6).IsEmpty()) pas.PassengerInTransit = GlobalStructures.ReadBoolean(row.Cell(6).GetString());
if (!row.Cell(7).IsEmpty()) pas.PassengerNationality = row.Cell(7).GetString().Substring(0, 2).ToUpper();
if (!row.Cell(8).IsEmpty()) pas.PassengerPlaceOfBirth = row.Cell(8).GetString().Clean();
if (!row.Cell(9).IsEmpty()) pas.PassengerCountryOfBirth = row.Cell(9).GetString().Substring(0, 2).ToUpper();
if (!row.Cell(10).IsEmpty()) pas.PassengerDateOfBirth = row.Cell(10).GetDateTime();
if (!row.Cell(11).IsEmpty()) pas.PassengerIdentityDocumentType = GlobalStructures.ReadIdentityDocumentType(row.Cell(11).GetString());
if (!row.Cell(12).IsEmpty()) pas.PassengerIdentityDocumentId = row.Cell(12).GetString().Clean();
if (!row.Cell(13).IsEmpty()) pas.PassengerIdentityDocumentIssuingState = row.Cell(13).GetString().Substring(0, 2).ToUpper();
if (!row.Cell(14).IsEmpty()) pas.PassengerIdentityDocumentExpiryDate = row.Cell(14).GetDateTime();
if (!row.Cell(15).IsEmpty()) pas.PassengerVisaNumber = row.Cell(15).GetString().Clean();
if (!row.Cell(16).IsEmpty()) pas.EmergencyCare = row.Cell(16).GetString().Clean();
if (!row.Cell(17).IsEmpty()) pas.EmergencyContactNumber = row.Cell(17).GetString().Clean();
pas.MessageHeader = this._pasdMessage;
pas.IsDirty = true;
pas.Identifier = PASD.GetNewIdentifier(this._pasdMessage.Elements);
this._pasdMessage.Elements.Add(pas);
importPassenger.Add(pas);
}
if (importPassenger.Count > 0)
{
this.dataGridPassengerListDeparture.Items.Refresh();
this.SublistElementChanged(Message.NotificationClass.PASD);
MessageBox.Show(String.Format(Properties.Resources.textPassengerImported, importPassenger.Count), Properties.Resources.textCaptionInformation, MessageBoxButton.OK, MessageBoxImage.Information);
}
}
stream = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read);
}
catch (Exception ex)
{
MessageBox.Show("Error reading Excel: " + ex.Message, Properties.Resources.textCaptionError, MessageBoxButton.OK, MessageBoxImage.Error);
MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
List<PASD> importPassenger = new List<PASD>();
try
{
do
{
while (reader.Read())
{
if (((IExcelDataReader)reader).FieldCount < 17)
{
throw new InvalidDataException("Sheet must have 17 columns of data");
}
PASD pas = new PASD();
if (reader.IsDBNull(0) && reader.IsDBNull(1)) continue;
if (!reader.IsDBNull(0)) pas.PassengerLastName = reader.GetValue(0).ToString();
if (pas.PassengerLastName.Equals("Family Name") || (pas.PassengerLastName.Trim().Length == 0)) continue;
if (!reader.IsDBNull(1)) pas.PassengerFirstName = reader.GetValue(1).ToString();
if (!reader.IsDBNull(2)) pas.PassengerGender = GlobalStructures.ParseGender(reader.GetString(2));
if (!reader.IsDBNull(3)) pas.PassengerPortOfEmbarkation = reader.GetString(3);
if (LocodeDB.PortNameFromLocode(pas.PassengerPortOfEmbarkation) == null)
pas.PassengerPortOfEmbarkation = null;
if (!reader.IsDBNull(4)) pas.PassengerPortOfDisembarkation = reader.GetString(4);
if (LocodeDB.PortNameFromLocode(pas.PassengerPortOfDisembarkation) == null)
pas.PassengerPortOfDisembarkation = null;
if (!reader.IsDBNull(5)) pas.PassengerInTransit = GlobalStructures.ReadBoolean(reader.GetString(5));
if (!reader.IsDBNull(6)) pas.PassengerNationality = reader.GetString(6).Substring(0, 2).ToUpper();
if (!reader.IsDBNull(7)) pas.PassengerPlaceOfBirth = reader.GetString(7);
if (!reader.IsDBNull(8)) pas.PassengerCountryOfBirth = reader.GetString(8).Substring(0, 2).ToUpper();
if (!reader.IsDBNull(9)) pas.PassengerDateOfBirth = reader.GetDateTime(9);
if (!reader.IsDBNull(10)) pas.PassengerIdentityDocumentType = GlobalStructures.ReadIdentityDocumentType(reader.GetString(10));
if (!reader.IsDBNull(11)) pas.PassengerIdentityDocumentId = reader.ReadAsString(11);
if (!reader.IsDBNull(12)) pas.PassengerIdentityDocumentIssuingState = reader.GetString(12).Substring(0, 2).ToUpper();
if (!reader.IsDBNull(13)) pas.PassengerIdentityDocumentExpiryDate = reader.GetDateTime(13);
if (!reader.IsDBNull(14)) pas.PassengerVisaNumber = reader.ReadAsString(14);
if (!reader.IsDBNull(15)) pas.EmergencyCare = reader.GetString(15);
if (!reader.IsDBNull(16)) pas.EmergencyContactNumber = reader.ReadAsString(16);
pas.MessageHeader = this._pasMessage;
pas.IsDirty = true;
pas.Identifier = PASD.GetNewIdentifier(this._pasdMessage.Elements);
this._pasdMessage.Elements.Add(pas);
importPassenger.Add(pas);
}
} while (reader.NextResult());
}
catch (Exception ex)
{
MessageBox.Show("Error reading Excel: " + ex.Message, Properties.Resources.textCaptionError, MessageBoxButton.OK, MessageBoxImage.Error);
}
if (importPassenger.Count > 0)
{
this.dataGridPassengerListDeparture.Items.Refresh();
this.SublistElementChanged(Message.NotificationClass.PASD);
MessageBox.Show(String.Format(Properties.Resources.textPassengerImported, importPassenger.Count), Properties.Resources.textCaptionInformation, MessageBoxButton.OK, MessageBoxImage.Information);
}
}
stream.Close();
}
}
}
#endregion

View File

@ -2,16 +2,18 @@
// Description: MDH Meldung Bearbeitungsseite
//
using bsmd.database;
using ClosedXML.Excel;
using ENI2.EditControls;
using ENI2.Util;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Win32;
using System.IO;
using ENI2.EditControls;
using ENI2.Util;
using bsmd.database;
using ExcelDataReader;
namespace ENI2.DetailViewControls
{
@ -281,15 +283,86 @@ namespace ENI2.DetailViewControls
private void ButtonImportFromExcel_Click(object sender, RoutedEventArgs e)
{
int cnt = Excel.ExcelLocalImportHelper.ImportLast30Days(this._mdh);
if (cnt > 0)
OpenFileDialog ofd = new OpenFileDialog
{
this.dataGridPortOfCallLast30Days.Items.Refresh();
this.SublistElementChanged(Message.NotificationClass.MDH);
MessageBox.Show(String.Format(Properties.Resources.textPoC30Imported, cnt),
Properties.Resources.textCaptionInformation,
MessageBoxButton.OK, MessageBoxImage.Information);
Filter = "Excel Files|*.xls;*.xlsx"
};
if (ofd.ShowDialog() ?? false)
{
FileStream stream;
try
{
stream = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
List<PortOfCallLast30Days> importPoC30 = new List<PortOfCallLast30Days>();
try
{
do
{
while (reader.Read())
{
if (reader.FieldCount < 3)
{
throw new InvalidDataException("Sheet must have at least 3 Columns of data");
}
PortOfCallLast30Days poc30 = new PortOfCallLast30Days();
if (reader.IsDBNull(0) && reader.IsDBNull(1)) continue;
if (!reader.IsDBNull(0)) poc30.PortOfCallLast30DaysLocode = reader.GetString(0);
if (!reader.IsDBNull(1)) poc30.PortOfCallLast30DaysDateOfDeparture = reader.GetDateTime(1);
string boolString = "";
if (!reader.IsDBNull(2)) boolString = reader.GetString(2);
poc30.PortOfCallLast30DaysCrewMembersJoined = (boolString.Equals("y", StringComparison.OrdinalIgnoreCase) || (boolString.Equals("yes", StringComparison.OrdinalIgnoreCase)) ||
(boolString.Equals("j", StringComparison.OrdinalIgnoreCase)));
if(reader.FieldCount > 3)
{
string allNewCrew = reader.GetString(3)?.Trim();
if(!allNewCrew.IsNullOrEmpty())
{
string[] crewNames = allNewCrew.Split(',', ';');
for(int i=0;i<crewNames.Length;i++)
{
string crewName = crewNames[i].Trim();
if (crewName.IsNullOrEmpty()) continue;
PortOfCallLast30DaysCrewJoinedShip poc30Crew = new PortOfCallLast30DaysCrewJoinedShip();
poc30Crew.PortOfCallLast30DaysCrewJoinedShipName = crewName;
poc30Crew.PortOfCallLast30Days = poc30;
poc30.CrewJoinedShip.Add(poc30Crew);
}
}
}
poc30.MDH = this._mdh;
this._mdh.PortOfCallLast30Days.Add(poc30);
importPoC30.Add(poc30);
}
} while (reader.NextResult());
}
catch (Exception ex)
{
MessageBox.Show("Error reading Excel: " + ex.Message, Properties.Resources.textCaptionError, MessageBoxButton.OK, MessageBoxImage.Error);
}
if (importPoC30.Count > 0)
{
this.dataGridPortOfCallLast30Days.Items.Refresh();
this.SublistElementChanged(Message.NotificationClass.MDH);
MessageBox.Show(String.Format(Properties.Resources.textPoC30Imported, importPoC30.Count), Properties.Resources.textCaptionInformation,
MessageBoxButton.OK, MessageBoxImage.Information);
}
}
stream.Close();
}
}

View File

@ -11,7 +11,7 @@
xmlns:data="clr-namespace:bsmd.database;assembly=bsmd.database"
xmlns:local="clr-namespace:ENI2.DetailViewControls"
mc:Ignorable="d"
d:DesignHeight="768" d:DesignWidth="1024">
d:DesignHeight="300" d:DesignWidth="800">
<xctk:BusyIndicator Name="busyIndicator">
<xctk:BusyIndicator.ProgressBarStyle>
<Style TargetType="ProgressBar">
@ -26,144 +26,104 @@
</StackPanel>
</xctk:BusyIndicator.BusyContent>
<GroupBox Name="visitTransitGroupBox" Header="{x:Static p:Resources.textOverview}">
<GroupBox Name="visitTransitGroupBox" Header="{x:Static p:Resources.textVisitTransit}">
<ScrollViewer PreviewMouseWheel="ScrollViewer_PreviewMouseWheel">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="28" />
<RowDefinition Height="28" />
<RowDefinition Height="28" />
<RowDefinition Height="28" />
<RowDefinition Height="28" />
<RowDefinition Height="4" />
<RowDefinition Height="32" />
<RowDefinition Height="32" />
<RowDefinition Height="4" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="400" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="1*" />
</Grid.ColumnDefinitions>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2*" />
<ColumnDefinition Width="2*" />
<ColumnDefinition Width="2*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="28" />
<RowDefinition Height="28" />
<RowDefinition Height="28" />
<RowDefinition Height="28" />
<RowDefinition Height="28" />
<RowDefinition Height="28" />
<RowDefinition Height="28" />
<RowDefinition Height="28" />
<RowDefinition Height="28" />
<RowDefinition Height="28" />
<RowDefinition Height="4" />
<RowDefinition Height="36" />
<RowDefinition Height="4" />
<RowDefinition Height="28" />
<RowDefinition Height="28" />
<RowDefinition Height="4" />
<RowDefinition Height="28" />
<RowDefinition Height="28" />
<RowDefinition Height="28" />
<RowDefinition Height="28" />
<RowDefinition Height="28" />
<RowDefinition Height="28" />
<RowDefinition Height="28" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Label HorizontalContentAlignment="Right" Grid.Row="0" Grid.Column="0" Content="{x:Static p:Resources.textVisitTransitId}" Margin="0,0,10,0" />
<TextBox Name="textBoxDisplayId" Grid.Row="0" Grid.Column="1" Grid.ColumnSpan="2" IsReadOnly="True" Margin="2" VerticalContentAlignment="Center" />
<Label HorizontalContentAlignment="Right" Grid.Row="1" Grid.Column="0" Content="{x:Static p:Resources.textPortCall}" Margin="0,0,10,0"/>
<enictrl:LocodeControl Grid.Column="1" Grid.ColumnSpan="2" Grid.Row="1" Width="Auto" x:Name="locodePoC" LocodeValue="{Binding PoC, Mode=TwoWay}" IsEnabled="False" />
<Label HorizontalContentAlignment="Right" Grid.Row="2" Grid.Column="0" Content="{x:Static p:Resources.textIMO}" Margin="0,0,10,0" />
<TextBox Name="textBoxIMO" Grid.Row="2" Grid.ColumnSpan="2" Grid.Column="1" Text="{Binding IMO, Mode=TwoWay, Converter={util:TrimStringConverter}}" Margin="2" IsReadOnly="True" VerticalContentAlignment="Center"/>
<Label HorizontalContentAlignment="Right" Grid.Row="3" Grid.Column="0" Content="{x:Static p:Resources.textENI}" Margin="0,0,10,0" />
<TextBox Name="textBoxENI" Grid.Row="3" Grid.Column="1" Grid.ColumnSpan="2" Text="{Binding ENI, Mode=TwoWay, Converter={util:TrimStringConverter}}" Margin="2" IsReadOnly="True" VerticalContentAlignment="Center"/>
<Label HorizontalContentAlignment="Right" Grid.Row="4" Grid.Column="0" Content="{x:Static p:Resources.textETAPortOfCall}" Margin="0,0,10,0" />
<xctk:DateTimePicker Grid.Column="1" Grid.ColumnSpan="2" Grid.Row="4" Value="{Binding ETAToPortOfCall, Mode=TwoWay, Converter={util:UtcToLocalDateTimeConverter}}" Name="dateTimePickerETA" Format="Custom" FormatString="dd.MM.yyyy HH:mm" ShowButtonSpinner="False" VerticalContentAlignment="Center" Margin="2" AllowTextInput="True" ContextMenu="{DynamicResource ClearContextMenu}" TextAlignment="Left" Minimum="1899.12.31 00:00" Maximum="2100.12.31 00:00" />
<Label HorizontalContentAlignment="Right" Grid.Row="5" Grid.Column="0" Content="{x:Static p:Resources.textETDPortOfCall}" Margin="0,0,10,0" />
<xctk:DateTimePicker Grid.Column="1" Grid.ColumnSpan="2" Grid.Row="5" Value="{Binding ETDFromPortOfCall, Mode=TwoWay, Converter={util:UtcToLocalDateTimeConverter}}" Name="dateTimePickerETD" Format="Custom" FormatString="dd.MM.yyyy HH:mm" ShowButtonSpinner="False" VerticalContentAlignment="Center" Margin="2" AllowTextInput="True" ContextMenu="{DynamicResource ClearContextMenu}" TextAlignment="Left" Minimum="1899.12.31 00:00" Maximum="2100.12.31 00:00"/>
<Label HorizontalContentAlignment="Right" Grid.Row="6" Grid.Column="0" Content="{x:Static p:Resources.textATAPortOfCall}" Margin="0,0,10,0" />
<xctk:DateTimePicker Grid.Column="1" Grid.ColumnSpan="2" Grid.Row="6" Value="{Binding ATAPortOfCall, Mode=TwoWay, Converter={util:UtcToLocalDateTimeConverter}}" Name="dateTimePickerATA" Format="Custom" FormatString="dd.MM.yyyy HH:mm" ShowButtonSpinner="False" VerticalContentAlignment="Center" Margin="2" AllowTextInput="True" ContextMenu="{DynamicResource ClearContextMenu}" TextAlignment="Left" Minimum="1899.12.31 00:00" Maximum="2100.12.31 00:00"/>
<Label HorizontalContentAlignment="Right" Grid.Row="7" Grid.Column="0" Content="{x:Static p:Resources.textATDPortOfCall}" Margin="0,0,10,0" />
<xctk:DateTimePicker Grid.Column="1" Grid.ColumnSpan="2" Grid.Row="7" Value="{Binding ATDPortOfCall, Mode=TwoWay, Converter={util:UtcToLocalDateTimeConverter}}" Name="dateTimePickerATD" Format="Custom" FormatString="dd.MM.yyyy HH:mm" ShowButtonSpinner="False" VerticalContentAlignment="Center" Margin="2" AllowTextInput="True" ContextMenu="{DynamicResource ClearContextMenu}" TextAlignment="Left" Minimum="1899.12.31 00:00" Maximum="2100.12.31 00:00"/>
<Label HorizontalAlignment="Right" Grid.Row="8" Grid.Column="0" Content="{x:Static p:Resources.textRemarks}" Margin="0,0,10,0" />
<TextBox Name="textBoxTicketNo" Grid.Column="1" Grid.Row="8" Grid.ColumnSpan="2" Text="{Binding TicketNo, Mode=TwoWay, Converter={util:TrimStringConverter}}" Margin="2" VerticalContentAlignment="Center" MaxLength="50"/>
<Label HorizontalContentAlignment="Right" Grid.Row="9" Grid.Column="0" Content="{x:Static p:Resources.textCreated}" Margin="0,0,10,0" />
<Label Name="labelCreated" Grid.Column="1" Grid.Row="9" Margin="2, 0, 0, 0" />
<Label Grid.Column="2" Grid.Row="9" Margin="0,0,10,0" HorizontalContentAlignment="Right" Name="labelBSMDStatusInternal" Content="{Binding BSMDStatusInternal, StringFormat={}{0}}" VerticalContentAlignment="Center" FontWeight="Bold" />
<StackPanel Orientation="Horizontal" Grid.Column="1" Grid.Row="11">
<Button Name="buttonRefresh" Margin="2" Click="buttonRefresh_Click" BorderThickness="0" Background="Transparent" ToolTip="{x:Static p:Resources.textTooltipRefresh}">
<StackPanel Orientation="Horizontal">
<Image Source="../Resources/nav_refresh_blue.png" Margin="0,0,5,0" Height="24"/>
<!--TextBlock Text="{x:Static p:Resources.textRefresh}" VerticalAlignment="Center"/-->
</StackPanel>
</Button>
<Button Name="buttonInfoCore" Margin="2" Click="buttonInfoCore_Click" BorderThickness="0" Background="Transparent" ToolTip="{x:Static p:Resources.textTooltipDetails}">
<Image Source="../Resources/document_view.png" Margin="0,0,5,0" Height="24" />
</Button>
<Button Name="buttonValidate" Margin="2" Click="buttonValidate_Click" BorderThickness="0" Background="Transparent" ToolTip="{x:Static p:Resources.textTooltipValidation}">
<Image Source="../Resources/hand_point.png" Margin="0,0,5,0" Height="24" />
</Button>
<!--
<Button Name="buttonWarnings" Margin="2" Click="buttonWarnings_Click" BorderThickness="0" Background="Transparent" Visibility="Hidden">
<Image Source="../Resources/sign_warning.png" Margin="0,0,5,0" Height="24" />
</Button>
-->
<Label HorizontalContentAlignment="Right" Grid.Row="0" Grid.Column="0" Content="{x:Static p:Resources.textPortCall}" Margin="0,0,10,0"/>
<enictrl:LocodeControl Grid.Column="1" Grid.ColumnSpan="2" Grid.Row="0" Width="Auto" x:Name="locodePoC" LocodeValue="{Binding PoC, Mode=TwoWay}" IsEnabled="False" />
<!--Grid Grid.Column="1" Grid.Row="0" Width="Auto">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<xctk:WatermarkComboBox Grid.Column="0" x:Name="comboBoxPoC" Margin="2" IsEditable="True" Watermark="Type for Locode.." TextBoxBase.TextChanged="ComboBox_TextChanged" ItemsSource="{Binding LocodePoCList, Mode=TwoWay}" SelectedItem="{Binding PoC, Mode=TwoWay}" />
<Image Name="imagePoCState" Grid.Column="1" Source="../Resources/bullet_ball_grey.png" />
</-->
<Label HorizontalContentAlignment="Right" Grid.Row="0" Grid.Column="3" Content="{x:Static p:Resources.textVisitTransitId}" Margin="0,0,10,0" />
<TextBox Name="textBoxDisplayId" Grid.Row="0" Grid.Column="4" Grid.ColumnSpan="2" IsReadOnly="True" Margin="2" VerticalContentAlignment="Center" />
<Label HorizontalContentAlignment="Right" Grid.Row="1" Grid.Column="0" Content="{x:Static p:Resources.textIMO}" Margin="0,0,10,0" />
<TextBox Name="textBoxIMO" Grid.Row="1" Grid.ColumnSpan="2" Grid.Column="1" Text="{Binding IMO, Mode=TwoWay, Converter={util:TrimStringConverter}}" Margin="2" IsReadOnly="True" VerticalContentAlignment="Center"/>
<Label HorizontalContentAlignment="Right" Grid.Row="1" Grid.Column="3" Content="{x:Static p:Resources.textENI}" Margin="0,0,10,0" />
<TextBox Name="textBoxENI" Grid.Row="1" Grid.Column="4" Grid.ColumnSpan="2" Text="{Binding ENI, Mode=TwoWay, Converter={util:TrimStringConverter}}" Margin="2" IsReadOnly="True" VerticalContentAlignment="Center"/>
<Label HorizontalContentAlignment="Right" Grid.Row="2" Grid.Column="0" Content="{x:Static p:Resources.textETAPortOfCall}" Margin="0,0,10,0" />
<Label HorizontalContentAlignment="Right" Grid.Row="2" Grid.Column="3" Content="{x:Static p:Resources.textETDPortOfCall}" Margin="0,0,10,0" />
<Label HorizontalContentAlignment="Right" Grid.Row="3" Grid.Column="0" Content="{x:Static p:Resources.textATAPortOfCall}" Margin="0,0,10,0" />
<Label HorizontalContentAlignment="Right" Grid.Row="3" Grid.Column="3" Content="{x:Static p:Resources.textATDPortOfCall}" Margin="0,0,10,0" />
<xctk:DateTimePicker Grid.Column="1" Grid.ColumnSpan="2" Grid.Row="2" Value="{Binding ETAToPortOfCall, Mode=TwoWay, Converter={util:UtcToLocalDateTimeConverter}}" Name="dateTimePickerETA" Format="Custom" FormatString="dd.MM.yyyy HH:mm" ShowButtonSpinner="False" VerticalContentAlignment="Center" Margin="2" AllowTextInput="True" ContextMenu="{DynamicResource ClearContextMenu}" TextAlignment="Left" Minimum="1899.12.31 00:00" Maximum="2100.12.31 00:00" />
<xctk:DateTimePicker Grid.Column="4" Grid.ColumnSpan="2" Grid.Row="2" Value="{Binding ETDFromPortOfCall, Mode=TwoWay, Converter={util:UtcToLocalDateTimeConverter}}" Name="dateTimePickerETD" Format="Custom" FormatString="dd.MM.yyyy HH:mm" ShowButtonSpinner="False" VerticalContentAlignment="Center" Margin="2" AllowTextInput="True" ContextMenu="{DynamicResource ClearContextMenu}" TextAlignment="Left" Minimum="1899.12.31 00:00" Maximum="2100.12.31 00:00"/>
<xctk:DateTimePicker Grid.Column="1" Grid.ColumnSpan="2" Grid.Row="3" Value="{Binding ATAPortOfCall, Mode=TwoWay, Converter={util:UtcToLocalDateTimeConverter}}" Name="dateTimePickerATA" Format="Custom" FormatString="dd.MM.yyyy HH:mm" ShowButtonSpinner="False" VerticalContentAlignment="Center" Margin="2" AllowTextInput="True" ContextMenu="{DynamicResource ClearContextMenu}" TextAlignment="Left" Minimum="1899.12.31 00:00" Maximum="2100.12.31 00:00"/>
<xctk:DateTimePicker Grid.Column="4" Grid.ColumnSpan="2" Grid.Row="3" Value="{Binding ATDPortOfCall, Mode=TwoWay, Converter={util:UtcToLocalDateTimeConverter}}" Name="dateTimePickerATD" Format="Custom" FormatString="dd.MM.yyyy HH:mm" ShowButtonSpinner="False" VerticalContentAlignment="Center" Margin="2" AllowTextInput="True" ContextMenu="{DynamicResource ClearContextMenu}" TextAlignment="Left" Minimum="1899.12.31 00:00" Maximum="2100.12.31 00:00"/>
<Label HorizontalAlignment="Right" Grid.Row="4" Grid.Column="0" Content="{x:Static p:Resources.textTicketNo}" Margin="0,0,10,0" />
<Label HorizontalContentAlignment="Right" Grid.Row="4" Grid.Column="3" Content="{x:Static p:Resources.textCreated}" Margin="0,0,10,0" />
<Label Name="labelCreated" Grid.Column="4" Grid.Row="4" Margin="2, 0, 0, 0" />
<Button Name="buttonFormblattNeu" Grid.Column="4" Grid.Row="7" Margin="2" Click="buttonFormblattNeu_Click" >
<StackPanel Orientation="Horizontal">
<TextBlock Text="Formblatt neu"></TextBlock>
<Image Source="../Resources/excel.png" Margin="10,0,5,0" Height="16"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Grid.Column="2" Grid.Row="11" Visibility="Hidden" Name="stackPanelLock">
<Image Source="../Resources/lock.png" Margin="0,0,5,0" Height="24" />
<TextBlock Name="textBlockLockUserName" VerticalAlignment="Center" />
</Button>
<TextBox Name="textBoxTicketNo" Grid.Column="1" Grid.Row="4" Grid.ColumnSpan="2" Text="{Binding TicketNo, Mode=TwoWay, Converter={util:TrimStringConverter}}" Margin="2" VerticalContentAlignment="Center" MaxLength="50"/>
<Label Grid.Column="0" Grid.Row="6" Margin="0,0,10,0" HorizontalContentAlignment="Right" Name="labelBSMDStatusInternal" Content="{Binding BSMDStatusInternal, StringFormat={}{0}}" VerticalContentAlignment="Center" FontWeight="Bold" />
<Button IsEnabled="True" Name="buttonStorno" Grid.Column="1" Grid.Row="6" Margin="2" Click="buttonStorno_Click" Content="{x:Static p:Resources.textCancelDeclaration}" Background="Red"/>
<Button IsEnabled="True" Name="buttonCopy" Grid.Column="2" Grid.Row="6" Margin="2" Click="buttonCopy_Click" Content="{x:Static p:Resources.textCopyData}"/>
<Button IsEnabled="True" Name="buttonSendPDF" Grid.Column="3" Grid.Row="6" Margin="2" Click="buttonSendPDF_Click">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{x:Static p:Resources.textCreatePDF}"></TextBlock>
<Image Source="../Resources/document_pdf.png" Margin="10,0,5,0" Height="16"/>
</StackPanel>
<Label Grid.Column="0" Grid.Row="13" Margin="0,0,10,0" HorizontalContentAlignment="Right" Name="labelHIS" VerticalContentAlignment="Center" Content="{x:Static p:Resources.textSendToHIS}" />
<ComboBox Grid.Column="1" Grid.Row="13" Margin="2" Name="comboBoxInitialHis" VerticalContentAlignment="Center" SelectedValuePath="Key" DisplayMemberPath="Value" SelectedValue="{Binding Path=InitialHIS}" />
<Button IsEnabled="True" Name="buttonSendAll" Grid.Column="1" Grid.Row="14" Content="{x:Static p:Resources.textSendAll}" Margin="2" Click="buttonSendAll_Click" />
<Button Grid.Column="1" Grid.Row="16" Margin="2" Name="buttonExcelImport" Click="buttonExcelImport_Click">
</Button>
<Button Name="buttonQueryHIS" Grid.Column="4" Grid.Row="6" Margin="2" Click="buttonQueryHIS_Click" Content="{x:Static p:Resources.textQueryHIS}"/>
<StackPanel Orientation="Horizontal" Grid.Column="5" Grid.Row="6">
<Button Name="buttonRefresh" Margin="2" Click="buttonRefresh_Click" BorderThickness="0" Background="Transparent" ToolTip="{x:Static p:Resources.textTooltipRefresh}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{x:Static p:Resources.textExcelImport}"></TextBlock>
<Image Source="../Resources/excel.png" Margin="10,0,5,0" Height="16"/>
<Image Source="../Resources/nav_refresh_blue.png" Margin="0,0,5,0" Height="24"/>
<!--TextBlock Text="{x:Static p:Resources.textRefresh}" VerticalAlignment="Center"/-->
</StackPanel>
</Button>
<Button IsEnabled="True" Name="buttonSendPDF" Grid.Column="1" Grid.Row="17" Margin="2" Click="buttonSendPDF_Click">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{x:Static p:Resources.textCreatePDF}"></TextBlock>
<Image Source="../Resources/document_pdf.png" Margin="10,0,5,0" Height="16"/>
</StackPanel>
<Button Name="buttonInfoCore" Margin="2" Click="buttonInfoCore_Click" BorderThickness="0" Background="Transparent" ToolTip="{x:Static p:Resources.textTooltipDetails}">
<Image Source="../Resources/document_view.png" Margin="0,0,5,0" Height="24" />
</Button>
<Button Name="buttonQueryHIS" Grid.Column="1" Grid.Row="18" Margin="2" Click="buttonQueryHIS_Click" Content="{x:Static p:Resources.textQueryHIS}"/>
<Button IsEnabled="True" Name="buttonCopy" Grid.Column="1" Grid.Row="19" Margin="2" Click="buttonCopy_Click" Content="{x:Static p:Resources.textCopyData}"/>
<Button Name="buttonFormblattNeu" Grid.Column="1" Grid.Row="20" Margin="2" Click="buttonFormblattNeu_Click" >
<StackPanel Orientation="Horizontal">
<TextBlock Text="Formblatt neu"></TextBlock>
<Image Source="../Resources/excel.png" Margin="10,0,5,0" Height="16"/>
</StackPanel>
<Button Name="buttonValidate" Margin="2" Click="buttonValidate_Click" BorderThickness="0" Background="Transparent" ToolTip="{x:Static p:Resources.textTooltipValidation}">
<Image Source="../Resources/hand_point.png" Margin="0,0,5,0" Height="24" />
</Button>
<Button IsEnabled="True" Name="buttonStorno" Grid.Column="1" Grid.Row="22" Margin="2" Click="buttonStorno_Click" Content="{x:Static p:Resources.textCancelDeclaration}" Background="Red"/>
<Label Grid.Column="2" Grid.Row="21" Margin="0,0,10,0" HorizontalContentAlignment="Right" Name="labelCancelled" VerticalContentAlignment="Center" FontWeight="Bold" />
<!--
<Button Name="buttonWarnings" Margin="2" Click="buttonWarnings_Click" BorderThickness="0" Background="Transparent" Visibility="Hidden">
<Image Source="../Resources/sign_warning.png" Margin="0,0,5,0" Height="24" />
</Button>
-->
</StackPanel>
<Label Grid.Column="0" Grid.Row="7" Margin="0,0,10,0" HorizontalContentAlignment="Right" Name="labelCancelled" VerticalContentAlignment="Center" FontWeight="Bold" />
<Label Grid.Column="1" Grid.Row="7" Margin="0,0,10,0" HorizontalContentAlignment="Right" Name="labelHIS" VerticalContentAlignment="Center" Content="{x:Static p:Resources.textSendToHIS}" />
<ComboBox Grid.Column="2" Grid.Row="7" Margin="2" Name="comboBoxInitialHis" VerticalContentAlignment="Center" SelectedValuePath="Key" DisplayMemberPath="Value" SelectedValue="{Binding Path=InitialHIS}" />
<Button Grid.Column="3" Grid.Row="7" Margin="2" Name="buttonExcelImport" Click="buttonExcelImport_Click">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{x:Static p:Resources.textExcelImport}"></TextBlock>
<Image Source="../Resources/excel.png" Margin="10,0,5,0" Height="16"/>
</StackPanel>
</Button>
<!--
<Button Grid.Column="4" Grid.Row="7" Margin="2" Name="buttonExcelExport" Click="buttonExcelExport_Click">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{x:Static p:Resources.textExcelExport}"></TextBlock>
@ -171,64 +131,14 @@
</StackPanel>
</Button>
-->
</Grid>
<StackPanel Orientation="Horizontal" Grid.Column="5" Grid.Row="4" Visibility="Hidden" Name="stackPanelLock">
<Image Source="../Resources/lock.png" Margin="0,0,5,0" Height="24" />
<TextBlock Name="textBlockLockUserName" VerticalAlignment="Center" />
</StackPanel>
<!-- Data Grid -->
<DataGrid Grid.Row="0" Grid.ColumnSpan="1" Grid.Column="1" Margin="2" x:Name="dataGridMessages" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" CanUserAddRows="False"
SelectionMode="Extended" AutoGenerateColumns="False" MouseDoubleClick="dataGrid_MouseDoubleClick" PreviewKeyDown="dataGrid_PreviewKeyDown">
<DataGrid.Resources>
<Style TargetType="{x:Type DataGridColumnHeadersPresenter}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGridColumnHeadersPresenter}">
<Grid Background="Transparent" Grid.IsSharedSizeScope="True">
<!-- 3 header rows: 0 = main title, 1 = group headers, 2 = real column headers -->
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<!-- One ColumnDefinition per DataGridTextColumn (or sharedsize groups) -->
<Grid.ColumnDefinitions>
<ColumnDefinition Width="{Binding Columns[0].ActualWidth, RelativeSource={RelativeSource AncestorType=DataGrid}}"/>
<ColumnDefinition Width="{Binding Columns[1].ActualWidth, RelativeSource={RelativeSource AncestorType=DataGrid}}"/>
<ColumnDefinition Width="{Binding Columns[2].ActualWidth, RelativeSource={RelativeSource AncestorType=DataGrid}}"/>
<ColumnDefinition Width="{Binding Columns[3].ActualWidth, RelativeSource={RelativeSource AncestorType=DataGrid}}"/>
<ColumnDefinition Width="{Binding Columns[4].ActualWidth, RelativeSource={RelativeSource AncestorType=DataGrid}}"/>
<ColumnDefinition Width="{Binding Columns[5].ActualWidth, RelativeSource={RelativeSource AncestorType=DataGrid}}"/>
<ColumnDefinition Width="{Binding Columns[6].ActualWidth, RelativeSource={RelativeSource AncestorType=DataGrid}}"/>
<ColumnDefinition Width="{Binding Columns[7].ActualWidth, RelativeSource={RelativeSource AncestorType=DataGrid}}"/>
<ColumnDefinition Width="{Binding Columns[8].ActualWidth, RelativeSource={RelativeSource AncestorType=DataGrid}}"/>
<ColumnDefinition Width="{Binding Columns[9].ActualWidth, RelativeSource={RelativeSource AncestorType=DataGrid}}"/>
<ColumnDefinition Width="{Binding Columns[10].ActualWidth, RelativeSource={RelativeSource AncestorType=DataGrid}}"/>
<ColumnDefinition Width="{Binding Columns[11].ActualWidth, RelativeSource={RelativeSource AncestorType=DataGrid}}"/>
<ColumnDefinition Width="{Binding Columns[12].ActualWidth, RelativeSource={RelativeSource AncestorType=DataGrid}}"/>
<ColumnDefinition Width="{Binding Columns[13].ActualWidth, RelativeSource={RelativeSource AncestorType=DataGrid}}"/>
<ColumnDefinition Width="{Binding Columns[14].ActualWidth, RelativeSource={RelativeSource AncestorType=DataGrid}}"/>
<ColumnDefinition Width="{Binding Columns[15].ActualWidth, RelativeSource={RelativeSource AncestorType=DataGrid}}"/>
<!-- …add as many as you need… -->
</Grid.ColumnDefinitions>
<!-- Row0: A single big header across all columns -->
<!--TextBlock Grid.Row="0" Grid.ColumnSpan="4" Text="Main Application" HorizontalAlignment="Center" FontWeight="Bold"/ -->
<!-- Row1: your “banded” group headers -->
<TextBlock Grid.Row="0" Grid.Column="5" Grid.ColumnSpan="2" Text="{x:Static p:Resources.textENIStatus}" HorizontalAlignment="Stretch" TextAlignment="Center" Padding="0,2,0,4" Background="AntiqueWhite" />
<TextBlock Grid.Row="0" Grid.Column="7" Grid.ColumnSpan="9" Text="{x:Static p:Resources.textNSWStatus}" HorizontalAlignment="Stretch" TextAlignment="Center" Padding="0,2,0,4" Background="AliceBlue"/>
<!-- Row2: the real column headers -->
<!-- This invisible filler ensures the layout lines up -->
<DataGridColumnHeader x:Name="PART_FillerColumnHeader" Grid.Row="1" Grid.ColumnSpan="14" IsHitTestVisible="False"/>
<!-- And here the ItemsPresenter will place each DataGridColumnHeader -->
<ItemsPresenter Grid.Row="1" Grid.ColumnSpan="16"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</DataGrid.Resources>
<DataGrid Grid.Row="9" Grid.ColumnSpan="6" Margin="0,8,0,0" x:Name="dataGridMessages" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" CanUserAddRows="False"
SelectionMode="Extended" AutoGenerateColumns="False" MouseDoubleClick="dataGrid_MouseDoubleClick" PreviewKeyDown="dataGrid_PreviewKeyDown">
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Style.Triggers>
@ -252,40 +162,22 @@ SelectionMode="Extended" AutoGenerateColumns="False" MouseDoubleClick="dataGrid_
</MultiDataTrigger.Conditions>
<Setter Property="Background" Value="Yellow" />
</MultiDataTrigger>
<DataTrigger Binding="{Binding SendSuccess}" Value="True">
<Setter Property="Background" Value="#92F592"></Setter>
</DataTrigger>
<DataTrigger Binding="{Binding InternalStatus}" Value="UPDATED">
<Setter Property="Background" Value="#DFFDDF"></Setter>
</DataTrigger>
<DataTrigger Binding="{Binding InternalStatus}" Value="TOSEND">
<Setter Property="Background" Value="#BFFDBF"></Setter>
</DataTrigger>
<DataTrigger Binding="{Binding InternalStatus}" Value="SENT">
<Setter Property="Background" Value="#BFFDBF"></Setter>
</DataTrigger>
<DataTrigger Binding="{Binding HasSystemErrors}" Value="True">
<Setter Property="Background" Value="MistyRose"></Setter>
</DataTrigger>
<!--DataTrigger Binding="{Binding HasErrors}" Value="True">
<Setter Property="Background" Value="PaleVioletRed"></Setter>
</DataTrigger-->
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
<DataGrid.Columns>
<DataGridTemplateColumn Header=" " Width="SizeToCells" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<!--Image Source="{Binding src:Util.ImageDict[ENINotificationDetailGroup]}" /-->
<!--Image Source="{Binding Source={x:Static src:Util.ImageDict}, Path=[ENINotificationDetailGroup]}"></-->
<Image Source="{Binding ENINotificationIconString, Converter={util:NullImageConverter}}" Height="24" />
<Image Source="{Binding ENINotificationIconString, Converter={util:NullImageConverter}}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="{x:Static p:Resources.textNotificationClass}" Binding="{Binding MessageNotificationClassDisplay}" IsReadOnly="True" Width="0.1*" FontWeight="Bold">
<DataGridTextColumn Header="{x:Static p:Resources.textNotificationClass}" Binding="{Binding MessageNotificationClassDisplay}"
IsReadOnly="True" Width="0.075*" FontWeight="Bold">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="VerticalAlignment" Value="Center"/>
@ -293,75 +185,6 @@ SelectionMode="Extended" AutoGenerateColumns="False" MouseDoubleClick="dataGrid_
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn Header="{x:Static p:Resources.textStatus}" Binding="{Binding BSMDStatusOverviewDisplay}" IsReadOnly="True" Width="0.1*">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="VerticalAlignment" Value="Center"/>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn Header="{x:Static p:Resources.textChangedBy}" Binding="{Binding ChangedBy}" IsReadOnly="True" Width="0.2*">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="VerticalAlignment" Value="Center"/>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn Header="{x:Static p:Resources.textChanged}" Binding="{Binding Changed}" IsReadOnly="True" Width="0.15*">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="VerticalAlignment" Value="Center"/>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn Header="{x:Static p:Resources.textErrors}" IsReadOnly="True" Width="0.06*" Binding="{Binding ErrorCount}">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="HorizontalAlignment" Value="Center" />
<Setter Property="FontWeight" Value="DemiBold" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn Header="{x:Static p:Resources.textViolations}" IsReadOnly="True" Width="0.06*" Binding="{Binding ViolationCount}">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="HorizontalAlignment" Value="Center" />
<Setter Property="FontWeight" Value="DemiBold" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn Header="HIS" Binding="{Binding HISOverviewDisplay}" IsReadOnly="True" Width="0.06*">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="VerticalAlignment" Value="Center"/>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn Header="{x:Static p:Resources.textReceivedAt}" Binding="{Binding ReceivedAt}" IsReadOnly="True" Width="0.15*">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="VerticalAlignment" Value="Center"/>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn Header="{x:Static p:Resources.textSentBy}" Binding="{Binding SentBy}" IsReadOnly="True" Width="0.1*">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="VerticalAlignment" Value="Center"/>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTemplateColumn Header="" Width="SizeToCells" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
@ -399,29 +222,29 @@ SelectionMode="Extended" AutoGenerateColumns="False" MouseDoubleClick="dataGrid_
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<!--DataGridTemplateColumn Header="" Width="SizeToCells" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Image x:Name="imageHasUpdate"/>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Path=HasUpdates}" Value="True">
<Setter Property="Source" Value="/Resources/recycle.png" TargetName="imageHasUpdate"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</-->
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Image x:Name="imageHasUpdate"/>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Path=HasUpdates}" Value="True">
<Setter Property="Source" Value="/Resources/recycle.png" TargetName="imageHasUpdate"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</-->
<!--DataGridTemplateColumn Header="" Width="SizeToCells" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Image x:Name="imageHasReminder"/>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Path=HasReminder}" Value="True">
<Setter Property="Source" Value="/Resources/hand_point.png" TargetName="imageHasReminder"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</-->
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Image x:Name="imageHasReminder"/>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Path=HasReminder}" Value="True">
<Setter Property="Source" Value="/Resources/hand_point.png" TargetName="imageHasReminder"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</-->
<DataGridTemplateColumn Header="" Width="SizeToCells" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
@ -434,7 +257,6 @@ SelectionMode="Extended" AutoGenerateColumns="False" MouseDoubleClick="dataGrid_
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="" Width="SizeToCells" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
@ -447,7 +269,41 @@ SelectionMode="Extended" AutoGenerateColumns="False" MouseDoubleClick="dataGrid_
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="{x:Static p:Resources.textChanged}" Binding="{Binding Changed}" IsReadOnly="True" Width="0.15*">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="VerticalAlignment" Value="Center"/>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn Header="{x:Static p:Resources.textReceivedAt}" Binding="{Binding ReceivedAt}" IsReadOnly="True" Width="0.15*">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="VerticalAlignment" Value="Center"/>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn Header="{x:Static p:Resources.textStatus}" Binding="{Binding InternalStatus}" IsReadOnly="True" Width="0.1*">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="VerticalAlignment" Value="Center"/>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn Header="HIS" Binding="{Binding HIS}" IsReadOnly="True" Width="0.1*">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="VerticalAlignment" Value="Center"/>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn Header="{x:Static p:Resources.textSentBy}" Binding="{Binding SentBy}" IsReadOnly="True" Width="0.1*">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="VerticalAlignment" Value="Center"/>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn Header="{x:Static p:Resources.textStatusInfo}" Binding="{Binding StatusInfo}" IsReadOnly="True" Width="0.2*">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
@ -455,7 +311,13 @@ SelectionMode="Extended" AutoGenerateColumns="False" MouseDoubleClick="dataGrid_
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn Header="{x:Static p:Resources.textChangedBy}" Binding="{Binding ChangedBy}" IsReadOnly="True" Width="0.2*">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="VerticalAlignment" Value="Center"/>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>

View File

@ -21,8 +21,6 @@ using Microsoft.Win32;
using System.Diagnostics;
using System.ComponentModel;
using static bsmd.database.Message;
using PdfSharp.Fonts;
using System.Linq;
namespace ENI2.DetailViewControls
{
@ -31,9 +29,6 @@ namespace ENI2.DetailViewControls
/// </summary>
public partial class OverViewDetailControl : DetailBaseControl
{
#region Fields
private Message _message = null;
private Message _ataMessage;
private Message _atdMessage;
@ -43,20 +38,12 @@ namespace ENI2.DetailViewControls
private readonly object _collectionLock = new object();
// private MessageSendStatusDialog mssd = null;
#endregion
#region Construction
public OverViewDetailControl()
{
InitializeComponent();
this.Loaded += OverViewDetailControl_Loaded;
}
#endregion
#region Initialize
private void OverViewDetailControl_Loaded(object sender, RoutedEventArgs e)
{
// die Controls nach Änderungen monitoren
@ -65,7 +52,7 @@ namespace ENI2.DetailViewControls
this.textBoxDisplayId.TextChanged += CoreTextBox_TextChanged;
this.textBoxIMO.TextChanged += CoreTextBox_TextChanged;
this.textBoxENI.TextChanged += CoreTextBox_TextChanged;
this.locodePoC.PropertyChanged += CoreLocode_LocodeChanged;
this.locodePoC.PropertyChanged += CoreLocode_LocodeChanged;
this.RegisterDateTimePickerChange(this.dateTimePickerATA, Message.NotificationClass.ATA);
this.RegisterDateTimePickerChange(this.dateTimePickerATD, Message.NotificationClass.ATD);
@ -73,6 +60,18 @@ namespace ENI2.DetailViewControls
this.RegisterDateTimePickerChange(this.dateTimePickerETD, Message.NotificationClass.NOA_NOD);
}
private void CoreLocode_LocodeChanged(object sender, PropertyChangedEventArgs e)
{
this.OnNotificationClassChanged(null);
}
private void CoreTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
this.OnNotificationClassChanged(null);
}
#region Initialize
public override void Initialize()
{
bool iAmAdmin = DBManager.Instance.GetReportingPartyDict()[App.UserId.Value].IsAdmin;
@ -317,9 +316,7 @@ namespace ENI2.DetailViewControls
BindingOperations.EnableCollectionSynchronization(this.Messages, _collectionLock);
this.dataGridMessages.ItemsSource = this.Messages;
this.OnRequestValidate(false);
base.Initialize(); // wenn Meldeklassen erst bei der Init. erzeugt werden, fehlen die Handler, die hier erneut festgelegt werden
this._initialized = true;
}
@ -357,9 +354,6 @@ namespace ENI2.DetailViewControls
this.buttonExcelImport.IsEnabled = !this.Core.DisplayId.IsNullOrEmpty();
this.dataGridMessages.ItemsSource = null;
this.dataGridMessages.ItemsSource = this.Messages;
//MessageBox.Show(string.Format("Visit/Transit ID updated: {0}", this.Core.DisplayId));
//ShowIdDialog sid = new ShowIdDialog(this.Core)
//{
@ -370,11 +364,6 @@ namespace ENI2.DetailViewControls
this.Core.IsDirty = false; // ist ja schon gespeichert..
}
internal void RefreshMessageGrid()
{
this.dataGridMessages?.Items?.Refresh();
}
#endregion
#region private methods
@ -442,50 +431,44 @@ namespace ENI2.DetailViewControls
MessageBoxResult result = MessageBox.Show(Properties.Resources.textConfirmSend, Properties.Resources.textConfirm, MessageBoxButton.YesNo, MessageBoxImage.Question);
if (result == MessageBoxResult.Yes)
{
this.SendMessages(this.dataGridMessages.SelectedItems.Cast<Message>());
}
}
private void SendMessages(IEnumerable<Message> messages)
{
bool somethingsNotSaved = false;
foreach (Message selectedMessage in messages)
{
if (selectedMessage.IsDirty) somethingsNotSaved = true;
}
if (somethingsNotSaved)
{
if (MessageBox.Show(Properties.Resources.textUnsavedChangesSendAnyWay, Properties.Resources.textConfirmation, MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No) == MessageBoxResult.No)
return;
}
List<Message> watchList = new List<Message>();
foreach (Message selectedMessage in messages)
{
if (selectedMessage.Reset) selectedMessage.Reset = false; // "nochmal" Versenden ist möglich
selectedMessage.InternalStatus = Message.BSMDStatus.TOSEND;
string userName = "?";
if (App.UserId.HasValue && DBManager.Instance.GetReportingPartyDict().ContainsKey(App.UserId.Value))
bool somethingsNotSaved = false;
foreach (Message selectedMessage in this.dataGridMessages.SelectedItems)
{
userName = DBManager.Instance.GetReportingPartyDict()[App.UserId.Value].Logon;
if (selectedMessage.IsDirty) somethingsNotSaved = true;
}
selectedMessage.ChangedBy = string.Format("{0} at {1} (Send)", userName, DateTime.Now);
selectedMessage.StatusInfo = string.Format(Properties.Resources.textMessageSentAt, DateTime.Now);
DBManager.GetSingleCon(Properties.Settings.Default.ConnectionString).Save(selectedMessage);
watchList.Add(selectedMessage);
}
// komplette Anmeldung auf "zu versenden" stellen
this.Core.BSMDStatusInternal = MessageCore.BSMDStatus.TOSEND;
this.Core.DefaultReportingPartyId = App.UserId;
if(somethingsNotSaved)
{
if (MessageBox.Show(Properties.Resources.textUnsavedChangesSendAnyWay, Properties.Resources.textConfirmation, MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No) == MessageBoxResult.No)
return;
}
DBManager.GetSingleCon(Properties.Settings.Default.ConnectionString).Save(this.Core); // löst auch den Watchdog aus
this.OnRequestSendValidation();
this.dataGridMessages.Items.Refresh();
List<Message> watchList = new List<Message>();
foreach (Message selectedMessage in this.dataGridMessages.SelectedItems)
{
if (selectedMessage.Reset) selectedMessage.Reset = false; // "nochmal" Versenden ist möglich
selectedMessage.InternalStatus = Message.BSMDStatus.TOSEND;
string userName = "?";
if (App.UserId.HasValue && DBManager.Instance.GetReportingPartyDict().ContainsKey(App.UserId.Value))
{
userName = DBManager.Instance.GetReportingPartyDict()[App.UserId.Value].Logon;
}
selectedMessage.ChangedBy = string.Format("{0} at {1} (Send)", userName, DateTime.Now);
selectedMessage.StatusInfo = string.Format(Properties.Resources.textMessageSentAt, DateTime.Now);
DBManager.GetSingleCon(Properties.Settings.Default.ConnectionString).Save(selectedMessage);
watchList.Add(selectedMessage);
}
/*
// komplette Anmeldung auf "zu versenden" stellen
this.Core.BSMDStatusInternal = MessageCore.BSMDStatus.TOSEND;
this.Core.DefaultReportingPartyId = App.UserId;
DBManager.GetSingleCon(Properties.Settings.Default.ConnectionString).Save(this.Core); // löst auch den Watchdog aus
this.OnRequestSendValidation();
this.dataGridMessages.Items.Refresh();
/*
if (this.mssd == null)
{
this.mssd = new MessageSendStatusDialog(this.Core);
@ -505,6 +488,7 @@ namespace ENI2.DetailViewControls
this.mssd.Activate(); // bring to foreground
this.mssd.AddMessages(watchList);
*/
}
}
private void contextResetMessage(object sender, RoutedEventArgs e)
@ -590,13 +574,7 @@ namespace ENI2.DetailViewControls
if (sfd.ShowDialog() ?? false)
{
Util.UIHelper.SetBusyState();
ReportManager rm = new ReportManager();
// TODO!!
// https://docs.pdfsharp.net/PDFsharp/Topics/Fonts/Font-Resolving.html
// https://docs.pdfsharp.net/MigraDoc/DOM/Document/MigraDocSettings.html
GlobalFontSettings.UseWindowsFontsUnderWindows = true;
GlobalFontSettings.UseWindowsFontsUnderWsl2 = true;
ReportManager rm = new ReportManager();
// create PDF from message classes
if (rm.Create(sfd.FileName, this.Core, sicd.SelectedClasses, out string importResultText))
@ -638,16 +616,6 @@ namespace ENI2.DetailViewControls
#region event handler
private void CoreLocode_LocodeChanged(object sender, PropertyChangedEventArgs e)
{
this.OnNotificationClassChanged(null);
}
private void CoreTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
this.OnNotificationClassChanged(null);
}
private void _checkStatusTimer_Elapsed(object sender, ElapsedEventArgs e)
{
bool? statusFlag = DBManager.GetSingleCon(Properties.Settings.Default.ConnectionString).GetMessageCoreQueryStatusFlag(this.Core.Id.Value);
@ -756,7 +724,7 @@ namespace ENI2.DetailViewControls
private void buttonValidate_Click(object sender, RoutedEventArgs e)
{
this.OnRequestValidate(true);
this.OnRequestValidate();
}
/// <summary>
@ -786,7 +754,7 @@ namespace ENI2.DetailViewControls
this.OnRequestReload(this.Core.Id.Value);
// validate all selected import classes (Finger with "selection")
this.OnRequestValidate(true);
this.OnRequestValidate();
}
else
@ -840,74 +808,7 @@ namespace ENI2.DetailViewControls
}
}
private void buttonSendAll_Click(object sender, RoutedEventArgs e)
{
SelectImportClassesDialog sicd = new SelectImportClassesDialog();
List<Message.NotificationClass> readyToSendMessages = new List<Message.NotificationClass>();
// Evaluate a number of criteria for messages that should not be preselected for sending
bool addToSend;
foreach (Message message in this.Messages)
{
addToSend = true;
// if ((message.ErrorCount ?? 0) > 0) continue; // skip selection if there are any errors left
switch(message.MessageNotificationClass)
{
case NotificationClass.HAZA:
addToSend = XtraSendLogic.ShouldSendMessage(message); break;
case NotificationClass.HAZD:
addToSend = XtraSendLogic.ShouldSendMessage(message); break;
case NotificationClass.BPOL:
if (message.Elements.Count > 0)
{
if (message.Elements[0] is BPOL bpol)
{
if (bpol.PortOfItineraries.Count == 0) addToSend = false;
}
}
break;
case NotificationClass.WAS_RCPT:
addToSend = false;
break;
case NotificationClass.INFO:
if (Core.PoC == "DEHAM") addToSend = false;
break;
default:
if(Message.IsListClass(message.MessageNotificationClass) && (message.Elements.Count == 0)) addToSend = false;
break;
}
if(addToSend)
readyToSendMessages.Add(message.MessageNotificationClass);
}
sicd.Messages = this.Messages;
sicd.PreselectedClasses.AddRange(readyToSendMessages);
sicd.IsTransit = this.Core.IsTransit;
sicd.IsImportMode = false;
if ((sicd.ShowDialog() ?? false) && (sicd.SelectedClasses.Count > 0))
{
// now send all selected messages
List<Message> toSendMessages = new List<Message>();
foreach(NotificationClass notificationClass in sicd.SelectedClasses)
{
Message selectedMessage = this.Messages.Find(x => x.MessageNotificationClass == notificationClass);
if (selectedMessage != null)
{
toSendMessages.Add(selectedMessage);
}
}
if (toSendMessages.Count > 0)
{
this.SendMessages(toSendMessages);
}
}
}
#endregion
#endregion
}
}

View File

@ -12,7 +12,7 @@
mc:Ignorable="d"
d:DesignHeight="600" d:DesignWidth="800">
<GroupBox Name="portCallGroupBox" Header="{x:Static p:Resources.textPortCall}">
<ScrollViewer>
<ScrollViewer PreviewMouseWheel="ScrollViewer_PreviewMouseWheel">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="300" />
@ -92,9 +92,8 @@
<Label HorizontalContentAlignment="Right" Grid.Row="6" Grid.Column="0" Content="{x:Static p:Resources.textPhone}" Name="label_AgentPhone" Margin="0,0,10,0"/>
<Label HorizontalContentAlignment="Right" Grid.Row="7" Grid.Column="0" Content="{x:Static p:Resources.textEMail}" Name="label_AgentEMail" Margin="0,0,10,0" />
<Label HorizontalContentAlignment="Right" Grid.Row="3" Grid.Column="2" Content="{x:Static p:Resources.textCity}" Name="label_AgentCity" Margin="0,0,10,0" />
<Label HorizontalContentAlignment="Right" Grid.Row="5" Grid.Column="2" Content="{x:Static p:Resources.textFirstName}" Name="label_AgentFirstName" Margin="0,0,10,0"/>
<Label HorizontalContentAlignment="Right" Grid.Row="6" Grid.Column="2" Content="{x:Static p:Resources.textFax}" Name="label_AgentFax" Margin="0,0,10,0"/>
<Label HorizontalContentAlignment="Right" Grid.Row="7" Grid.Column="2" Content="{x:Static p:Resources.textWasteDisposalServiceProvider}" Margin="0,0,10,0" />
<Label HorizontalContentAlignment="Right" Grid.Row="6" Grid.Column="2" Content="{x:Static p:Resources.textFirstName}" Name="label_AgentFirstName" Margin="0,0,10,0"/>
<Label HorizontalContentAlignment="Right" Grid.Row="7" Grid.Column="2" Content="{x:Static p:Resources.textFax}" Name="label_AgentFax" Margin="0,0,10,0"/>
<Label HorizontalContentAlignment="Right" Grid.Row="3" Grid.Column="0" Content="{x:Static p:Resources.textCountry}" Name="label_AgentCountry" Margin="0,0,10,0"/>
<Label HorizontalContentAlignment="Right" Grid.Row="0" Grid.Column="2" Content="{x:Static p:Resources.textAgentTemplate}" Name="labelAgentTemplate" Margin="0,0,10,0"/>
<Label HorizontalContentAlignment="Right" Grid.Row="1" Grid.Column="2" Content="{x:Static p:Resources.textTitle}" Name="labelAgentTemplateTitle" Margin="0,0,10,0" Visibility="Hidden" />
@ -105,11 +104,10 @@
<TextBox Grid.Row="3" Grid.Column="3" Name="textBox_AgentCity" MaxLength="99" Margin="2" Text="{Binding AgentCity, Converter={util:TrimStringConverter}}" VerticalContentAlignment="Center"/>
<TextBox Grid.Row="3" Grid.Column="1" Name="textBox_AgentCountry" MaxLength="99" Margin="2" Text="{Binding AgentCountry, Converter={util:TrimStringConverter}}" VerticalContentAlignment="Center" />
<TextBox Grid.Row="5" Grid.Column="1" Name="textBox_AgentLastName" MaxLength="99" Margin="2" Text="{Binding AgentLastName, Converter={util:TrimStringConverter}}" VerticalContentAlignment="Center"/>
<TextBox Grid.Row="5" Grid.Column="3" Name="textBox_AgentFirstName" MaxLength="99" Margin="2" Text="{Binding AgentFirstName, Converter={util:TrimStringConverter}}" VerticalContentAlignment="Center"/>
<TextBox Grid.Row="6" Grid.Column="3" Name="textBox_AgentFirstName" MaxLength="99" Margin="2" Text="{Binding AgentFirstName, Converter={util:TrimStringConverter}}" VerticalContentAlignment="Center"/>
<TextBox Grid.Row="6" Grid.Column="1" Name="textBox_AgentPhone" MaxLength="99" Margin="2" Text="{Binding AgentPhone, Converter={util:TrimStringConverter}}" VerticalContentAlignment="Center"/>
<TextBox Grid.Row="6" Grid.Column="3" Name="textBox_AgentFax" MaxLength="99" Margin="2" Text="{Binding AgentFax, Converter={util:TrimStringConverter}}" VerticalContentAlignment="Center"/>
<TextBox Grid.Row="7" Grid.Column="3" Name="textBox_AgentFax" MaxLength="99" Margin="2" Text="{Binding AgentFax, Converter={util:TrimStringConverter}}" VerticalContentAlignment="Center"/>
<TextBox Grid.Row="7" Grid.Column="1" Name="textBox_AgentEMail" MaxLength="99" Margin="2" Text="{Binding AgentEMail, Converter={util:TrimStringConverter}}" VerticalContentAlignment="Center"/>
<TextBox Grid.Row="7" Grid.Column="3" Name="textBox_WasteDisposalServiceProvider" MaxLength="99" Margin="2" Text="{Binding WasteDisposalServiceProviderText, Converter={util:TrimStringConverter}}" VerticalContentAlignment="Center"/>
<ComboBox Grid.Row="0" Grid.Column="3" Name="comboBox_AgentTemplate" Margin="2" SelectedValuePath="Id" DisplayMemberPath="AgentTitle" SelectionChanged="comboBox_AgentTemplate_SelectionChanged" />
<Grid Grid.Column="2" Grid.Row="1" HorizontalAlignment="Right">

View File

@ -25,7 +25,6 @@ namespace ENI2.DetailViewControls
private NOA_NOD _noa_nod;
private AGNT _agnt;
private WAS _was;
private static List<AGNT_Template> _agntTemplates = null;
private AGNT_Template _currentTemplate;
private AGNT_Template _undoTemplate;
@ -69,9 +68,6 @@ namespace ENI2.DetailViewControls
this.RegisterTextboxChange(this.textBox_AgentStreetAndNumber, Message.NotificationClass.AGNT);
this.RegisterTextboxChange(this.textBox_AgentCountry, Message.NotificationClass.AGNT);
// WAS
this.RegisterTextboxChange(this.textBox_WasteDisposalServiceProvider, Message.NotificationClass.WAS);
this.buttonSaveTemplate.IsEnabled = DBManager.Instance.GetReportingPartyDict()[App.UserId.Value].IsEditor;
this.buttonDeleteTemplate.IsEnabled = DBManager.Instance.GetReportingPartyDict()[App.UserId.Value].IsEditor;
}
@ -99,16 +95,6 @@ namespace ENI2.DetailViewControls
_agnt = new AGNT();
this.ControlMessages.Add(aMessage);
}
if(aMessage.MessageNotificationClass == Message.NotificationClass.WAS)
{
if (aMessage.Elements.Count > 0)
_was = aMessage.Elements[0] as WAS;
else
_was = new WAS();
this.ControlMessages.Add(aMessage);
}
}
this.dateTimePicker_ETAToKielCanal.IsEnabled = this.Core.IsTransit;
@ -137,8 +123,6 @@ namespace ENI2.DetailViewControls
this.dateTimePicker_ETDFromLastPort.DataContext = _noa_nod;
this.dateTimePicker_ETDFromPortOfCall.DataContext = _noa_nod;
this.textBox_WasteDisposalServiceProvider.DataContext = _was;
this.checkBox_IsAnchored.IsEnabled = this.Core.IsDK;
if(_agntTemplates == null)
@ -256,7 +240,7 @@ namespace ENI2.DetailViewControls
}
}
#endregion
#endregion
#region AGNT templates combo
@ -284,7 +268,7 @@ namespace ENI2.DetailViewControls
DBManager.Instance.Delete(_currentTemplate);
_agntTemplates.Remove(_currentTemplate);
this.textBoxTemplateTitle.Text = null;
this.buttonDeleteTemplate.IsEnabled = false;
this.buttonDeleteTemplate.IsEnabled = false;
this.comboBox_AgentTemplate.ItemsSource = _agntTemplates;
this.buttonSetTemplate.IsEnabled = false;
}
@ -353,8 +337,6 @@ namespace ENI2.DetailViewControls
this.textBox_AgentPostalCode.GetBindingExpression(TextBox.TextProperty).UpdateSource();
this.textBox_AgentStreetAndNumber.Text = this._undoTemplate.AgentStreetAndNumber;
this.textBox_AgentStreetAndNumber.GetBindingExpression(TextBox.TextProperty).UpdateSource();
this.textBox_WasteDisposalServiceProvider.Text = this._undoTemplate.WasteDisposalServiceProviderName;
this.textBox_WasteDisposalServiceProvider.GetBindingExpression(TextBox.TextProperty).UpdateSource();
this.buttonUndoTemplate.IsEnabled = false; // can't undo after undo
}
@ -363,13 +345,6 @@ namespace ENI2.DetailViewControls
{
if (this._currentTemplate == null) return;
// confirm overwrite of waste disposal service provider
if (this.textBox_WasteDisposalServiceProvider.Text.Length > 0)
{
string message = string.Format(Properties.Resources.textConfirmWSDPOverwrite, this.textBox_WasteDisposalServiceProvider.Text, this._currentTemplate.WasteDisposalServiceProviderName);
if (MessageBox.Show(message, Properties.Resources.textConfirmation, MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No) == MessageBoxResult.No) { return; }
}
this._undoTemplate = createFromCurrentText(null, null);
this.textBox_AgentCity.Text = this._currentTemplate.AgentCity;
@ -381,7 +356,7 @@ namespace ENI2.DetailViewControls
this.textBox_AgentEMail.Text = this._currentTemplate.AgentEMail;
this.textBox_AgentEMail.GetBindingExpression(TextBox.TextProperty).UpdateSource();
this.textBox_AgentFax.Text = this._currentTemplate.AgentFax;
this.textBox_AgentFax.GetBindingExpression (TextBox.TextProperty).UpdateSource();
this.textBox_AgentEMail.GetBindingExpression(TextBox.TextProperty).UpdateSource();
this.textBox_AgentFirstName.Text = this._currentTemplate.AgentFirstName;
this.textBox_AgentFirstName.GetBindingExpression(TextBox.TextProperty).UpdateSource();
this.textBox_AgentLastName.Text = this._currentTemplate.AgentLastName;
@ -392,11 +367,6 @@ namespace ENI2.DetailViewControls
this.textBox_AgentPostalCode.GetBindingExpression(TextBox.TextProperty).UpdateSource();
this.textBox_AgentStreetAndNumber.Text = this._currentTemplate.AgentStreetAndNumber;
this.textBox_AgentStreetAndNumber.GetBindingExpression(TextBox.TextProperty).UpdateSource();
if ((this._currentTemplate.WasteDisposalServiceProviderName ?? "").Trim() != (this.textBox_WasteDisposalServiceProvider.Text ?? "").Trim())
{
this.textBox_WasteDisposalServiceProvider.Text = this._currentTemplate.WasteDisposalServiceProviderName;
this.textBox_WasteDisposalServiceProvider.GetBindingExpression(TextBox.TextProperty).UpdateSource();
}
this.buttonUndoTemplate.IsEnabled = true;
this.buttonSetTemplate.IsEnabled = false;
@ -410,7 +380,7 @@ namespace ENI2.DetailViewControls
AGNT_Template at = new AGNT_Template();
if (existingTemplate != null)
at = existingTemplate;
at.AgentTitle = title;
at.AgentCity = this.textBox_AgentCity.Text;
at.AgentCompanyName = this.textBox_AgentCompanyName.Text;
@ -422,7 +392,6 @@ namespace ENI2.DetailViewControls
at.AgentPhone = this.textBox_AgentPhone.Text;
at.AgentPostalCode = this.textBox_AgentPostalCode.Text;
at.AgentStreetAndNumber = textBox_AgentStreetAndNumber.Text;
at.WasteDisposalServiceProviderName = textBox_WasteDisposalServiceProvider.Text;
return at;
}

View File

@ -24,11 +24,11 @@
</col:ArrayList>
</UserControl.Resources>
<GroupBox Name="portNotificationGroupBox" Header="{x:Static p:Resources.textPortNotification}">
<ScrollViewer>
<ScrollViewer PreviewMouseWheel="ScrollViewer_PreviewMouseWheel">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="50" />
<RowDefinition Height="194" />
<RowDefinition Height="220" />
<RowDefinition Height="200" />
<RowDefinition Height="200" />
</Grid.RowDefinitions>
@ -36,12 +36,10 @@
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="4*" />
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="5*" />
</Grid.ColumnDefinitions>
<Label HorizontalContentAlignment="Right" Grid.Row="0" Grid.Column="0" Content="{x:Static p:Resources.textNameMaster}" Name="label_nameMaster" Margin="0,0,10,0"/>
<TextBox Grid.Row="0" Grid.Column="1" Name="textBox_NameMaster" MaxLength="100" Margin="2" Text="{Binding NameOfMaster, Converter={util:TrimStringConverter}}" VerticalContentAlignment="Center" VerticalAlignment="Center"/>
<Button x:Name="buttonCopyNameFromCREWA" Grid.Row="0" Grid.Column="2" Margin="2" Content="{x:Static p:Resources.textCopyFromCREWA}" Click="buttonCopyNameFromCREWA_Click"/>
</Grid>
</GroupBox>
<GroupBox Name="infoGroupBox" Header="{x:Static p:Resources.textInfo}" Grid.Row="1" Margin="0,5,0,5">
@ -59,84 +57,35 @@
<RowDefinition Height="26" />
<RowDefinition Height="26" />
<RowDefinition Height="26" />
<RowDefinition Height="26" />
</Grid.RowDefinitions>
<Label HorizontalContentAlignment="Right" Grid.Row="0" Grid.Column="0" Content="{x:Static p:Resources.textShippingArea}" Name="label_INFOShippingArea" VerticalContentAlignment="Center" Margin="0,0,10,0"/>
<Label HorizontalContentAlignment="Right" Grid.Row="0" Grid.Column="2" Content="{x:Static p:Resources.textMaerskSeago}" Name="label_MaerskSeaGo" VerticalContentAlignment="Center" Margin="0,0,10,0"/>
<Label HorizontalContentAlignment="Right" Grid.Row="1" Grid.Column="0" Content="{x:Static p:Resources.textPortArea}" Name="label_INFOPortArea" VerticalContentAlignment="Center" Margin="0,0,10,0"/>
<Label HorizontalContentAlignment="Right" Grid.Row="2" Grid.Column="0" Content="{x:Static p:Resources.textRequestedPositionInPortOfCall}" Name="label_INFORequestedBerth" VerticalContentAlignment="Center" Margin="0,0,10,0"/>
<Label HorizontalContentAlignment="Right" Grid.Row="3" Grid.Column="0" Content="{x:Static p:Resources.textBowThrusterPower}" Name="label_INFOBowThrusterPower" VerticalContentAlignment="Center" Margin="0,0,10,0"/>
<Label HorizontalContentAlignment="Right" Grid.Row="4" Grid.Column="0" Content="{x:Static p:Resources.textSternThrusterPower}" Name="label_INFOSternThrusterPower" VerticalContentAlignment="Center" Margin="0,0,10,0"/>
<Label HorizontalContentAlignment="Right" Grid.Row="5" Grid.Column="0" Content="{x:Static p:Resources.textFumigatedBulkCargo}" Name="label_INFOFumigatedBulkCargo" VerticalContentAlignment="Center" Margin="0,0,10,0"/>
<Label HorizontalContentAlignment="Right" Grid.Row="0" Grid.Column="2" Content="{x:Static p:Resources.textDeplacementSummerDraught}" Name="label_INFODeplacementSummerDraught" VerticalContentAlignment="Center" Margin="0,0,10,0"/>
<Label HorizontalContentAlignment="Right" Grid.Row="1" Grid.Column="2" Content="{x:Static p:Resources.textSpecialRequirementsOfShipAtBerth}" Name="label_INFOSpecialRequirements" VerticalContentAlignment="Center" Margin="0,0,10,0"/>
<Label HorizontalContentAlignment="Right" Grid.Row="3" Grid.Column="2" Content="{x:Static p:Resources.textConstructionCharacteristics}" Name="label_INFOConstructionCharacteristics" VerticalContentAlignment="Center" Margin="0,0,10,0"/>
<Label HorizontalContentAlignment="Right" Grid.Row="6" Grid.Column="0" Content="{x:Static p:Resources.textDeplacementSummerDraught}" Name="label_INFODeplacementSummerDraught" VerticalContentAlignment="Center" Margin="0,0,10,0"/>
<Label HorizontalContentAlignment="Right" Grid.Row="3" Grid.Column="2" Content="{x:Static p:Resources.textSpecialRequirementsOfShipAtBerth}" Name="label_INFOSpecialRequirements" VerticalContentAlignment="Center" Margin="0,0,10,0"/>
<Label HorizontalContentAlignment="Right" Grid.Row="5" Grid.Column="2" Content="{x:Static p:Resources.textConstructionCharacteristics}" Name="label_INFOConstructionCharacteristics" VerticalContentAlignment="Center" Margin="0,0,10,0"/>
<ComboBox Grid.Row="0" Grid.Column="1" x:Name="comboBoxShippingArea" Margin="2" SelectedIndex="{Binding ShippingArea, Converter={util:ByteConverter}}" ContextMenu="{DynamicResource ClearContextMenu}" />
<Grid Grid.Row="1" Grid.Column="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="110" />
</Grid.ColumnDefinitions>
<ComboBox Grid.Column="0" Name="comboBoxPortArea" Margin="2" SelectedValue="{Binding PortArea}" SelectedValuePath="Key" DisplayMemberPath="Value" ContextMenu="{DynamicResource ClearContextMenu}" />
<Button Grid.Column="1" x:Name="buttonSearchPortArea" Margin="2" Content="Lookup port area" Click="buttonSearchPortArea_Click" />
</Grid>
<ComboBox Grid.Row="0" Grid.Column="3" x:Name="comboBoxGroup" Margin="2,2,4,2" ItemsSource="{StaticResource arrList}"
DisplayMemberPath="Key" SelectedValuePath="Value" SelectionChanged="comboBoxGroup_SelectionChanged" ContextMenu="{DynamicResource ClearContextMenu}" />
<Button Grid.Row="1" Grid.Column="3" x:Name="buttonSearchPortArea" Margin="2" Content="Lookup port area" Click="buttonSearchPortArea_Click" />
<ComboBox Grid.Row="1" Grid.Column="1" Name="comboBoxPortArea" Margin="2" SelectedValue="{Binding PortArea}" SelectedValuePath="Key" DisplayMemberPath="Value" ContextMenu="{DynamicResource ClearContextMenu}" />
<TextBox Grid.Row="2" Grid.Column="1" Name="textRequestedPostionInPortOfCall" Margin="2" Text="{Binding RequestedPositionInPortOfCall, Converter={util:TrimStringConverter}}" VerticalContentAlignment="Center"/>
<TextBox Grid.Row="3" Grid.Column="1" Name="textBowThrusterPower" Margin="2" Text="{Binding BowThrusterPower, Converter={util:TrimStringConverter}}" VerticalContentAlignment="Center"/>
<TextBox Grid.Row="4" Grid.Column="1" Name="textSternThrusterPower" Margin="2" Text="{Binding SternThrusterPower, Converter={util:TrimStringConverter}}" VerticalContentAlignment="Center"/>
<CheckBox Grid.Row="5" Grid.Column="1" Name="checkBoxFumigatedBulkCargo" VerticalContentAlignment="Center" IsChecked="{Binding FumigatedBulkCargoBool, Mode=TwoWay}" Margin="2"/>
<xctk:DoubleUpDown Grid.Row="0" Grid.Column="3" Name="doubleUpDownDisplacementSummerDraught" ShowButtonSpinner="False" ParsingNumberStyle="Any" Value="{Binding DeplacementSummerDraught_TNE}" Margin="4,2,0,2" FormatString="N1" TextAlignment="Left"/>
<TextBox Grid.Row="1" Grid.Column="3" Grid.RowSpan="2" Name="textSpecialRequirements" Margin="2" Text="{Binding SpecialRequirementsOfShipAtBerth, Converter={util:TrimStringConverter}}" VerticalContentAlignment="Top" />
<TextBox Grid.Row="3" Grid.Column="3" Grid.RowSpan="2" Name="textConstructionCharacteristics" Margin="2" Text="{Binding ConstructionCharacteristicsOfShip, Converter={util:TrimStringConverter}}" VerticalContentAlignment="Top"/>
<xctk:DoubleUpDown Grid.Row="6" Grid.Column="1" Name="doubleUpDownDisplacementSummerDraught" ShowButtonSpinner="False" ParsingNumberStyle="Any" Value="{Binding DeplacementSummerDraught_TNE}" Margin="4,2,0,2" FormatString="N1" TextAlignment="Left"/>
<TextBox Grid.Row="3" Grid.Column="3" Grid.RowSpan="2" Name="textSpecialRequirements" Margin="2" Text="{Binding SpecialRequirementsOfShipAtBerth, Converter={util:TrimStringConverter}}" VerticalContentAlignment="Top" />
<TextBox Grid.Row="5" Grid.Column="3" Grid.RowSpan="2" Name="textConstructionCharacteristics" Margin="2" Text="{Binding ConstructionCharacteristicsOfShip, Converter={util:TrimStringConverter}}" VerticalContentAlignment="Top"/>
</Grid>
</GroupBox>
<GroupBox Name="servGroupBox" Header="{x:Static p:Resources.textServ}" Grid.Row="2">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="28" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid Grid.Row="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width=".1*" />
<ColumnDefinition Width=".2*" />
<ColumnDefinition Width="26" />
<ColumnDefinition Width="26" />
<ColumnDefinition Width="26" />
<ColumnDefinition Width="26" />
<ColumnDefinition Width="26" />
<ColumnDefinition Width=".2*" />
</Grid.ColumnDefinitions>
<Label HorizontalContentAlignment="Right" Grid.Row="0" Grid.Column="0" Content="{x:Static p:Resources.textSERVTemplate}" Name="label_MaerskSeaGo" VerticalContentAlignment="Center" Margin="0,0,10,0"/>
<ComboBox Grid.Row="0" Grid.Column="1" x:Name="comboBoxGroup" Margin="2,2,4,2" DisplayMemberPath="ServiceName"
SelectionChanged="comboBoxGroup_SelectionChanged" ContextMenu="{DynamicResource ClearContextMenu}" />
<Button Name="buttonSetTemplate" Margin="2" Click="buttonSetTemplate_Click" BorderThickness="0" Background="Transparent" Grid.Column="2"
ToolTip="Apply template" HorizontalContentAlignment="Right" IsEnabled="False">
<StackPanel Orientation="Horizontal">
<Image Source="../Resources/check.png" Margin="0,0,0,0" Height="20" Width="20" />
</StackPanel>
</Button>
<Button Name="buttonEditTemplate" Grid.Column="4" Grid.Row="0" Margin="2" Click="buttonEditTemplate_Click" BorderThickness="0" Background="Transparent" ToolTip="Edit template">
<StackPanel Orientation="Horizontal">
<Image Source="../Resources/pencil.png" Margin="0,0,0,0" Height="20" Width="20" />
</StackPanel>
</Button>
<Button Name="buttonNewTemplate" Grid.Column="5" Grid.Row="0" Margin="2" Click="buttonNewTemplate_Click" BorderThickness="0" Background="Transparent" ToolTip="New template">
<StackPanel Orientation="Horizontal">
<Image Source="../Resources/document_plain_new.png" Margin="0,0,0,0" Height="20" Width="20" />
</StackPanel>
</Button>
<Button Name="buttonDeleteTemplate" Grid.Column="6" Grid.Row="0" Margin="2" Click="buttonDeleteTemplate_Click" BorderThickness="0" Background="Transparent" ToolTip="Delete template" IsEnabled="False">
<StackPanel Orientation="Horizontal">
<Image Source="../Resources/delete.png" Margin="0,0,0,0" Height="20" Width="20" />
</StackPanel>
</Button>
</Grid>
<enictrl:ENIDataGrid Grid.Row="1" x:Name="dataGridSERV" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch"
<enictrl:ENIDataGrid x:Name="dataGridSERV" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch"
AutoGenerateColumns="False" Margin="0,5,0,0">
<DataGrid.Columns>
<DataGridTextColumn Header="" Binding="{Binding Identifier}" IsReadOnly="True" />
@ -145,7 +94,7 @@
<DataGridTextColumn Header="{x:Static p:Resources.textServiceInvoiceRecipient}" Binding="{Binding ServiceInvoiceRecipient, Mode=TwoWay}" IsReadOnly="True" Width="0.4*" />
</DataGrid.Columns>
</enictrl:ENIDataGrid>
</Grid>
</GroupBox>
<GroupBox Name="ladgGroupBox" Header="{x:Static p:Resources.textLadg}" Grid.Row="3">
<enictrl:ENIDataGrid x:Name="dataGridLADG" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch"

View File

@ -16,8 +16,6 @@ using ENI2.EditControls;
using ENI2.Util;
using bsmd.database;
using System.Threading.Tasks;
using System.Diagnostics;
namespace ENI2.DetailViewControls
{
@ -27,18 +25,11 @@ namespace ENI2.DetailViewControls
public partial class PortNotificationDetailControl : DetailBaseControl
{
#region Fields
private Message _nameMessage;
private Message _infoMessage;
private Message _servMessage;
private Message _ladgMessage;
private Message _crewaMessage;
private Dictionary<string, string> portAreas = null;
private static List<SERV_Template> _servTemplates = null;
private SERV_Template _currentTemplate;
#endregion
private static readonly string[] shippingAreas = {
Properties.Resources.textShippingAreaNORTHBALTIC,
@ -68,7 +59,7 @@ namespace ENI2.DetailViewControls
this.dataGridLADG.CellEditEnding += (obj, ev) => { this.OnNotificationClassChanged(Message.NotificationClass.LADG); };
}
public override async void Initialize()
public override void Initialize()
{
base.Initialize();
@ -78,7 +69,6 @@ namespace ENI2.DetailViewControls
if (aMessage.MessageNotificationClass == Message.NotificationClass.INFO) { this._infoMessage = aMessage; this.ControlMessages.Add(aMessage); }
if (aMessage.MessageNotificationClass == Message.NotificationClass.SERV) { this._servMessage = aMessage; this.ControlMessages.Add(aMessage); }
if (aMessage.MessageNotificationClass == Message.NotificationClass.LADG) { this._ladgMessage = aMessage; this.ControlMessages.Add(aMessage); }
if(aMessage.MessageNotificationClass == Message.NotificationClass.CREWA) { this._crewaMessage = aMessage;}
}
#region init NAME
@ -165,22 +155,16 @@ namespace ENI2.DetailViewControls
this.dataGridLADG.DeleteRequested += DataGridLADG_DeleteRequested;
this.dataGridLADG.CreateRequested += DataGridLADG_CreateRequested;
#endregion
#endregion
#region init SERV templates
#region init helper Maersk / SeaGo Field
if(_servTemplates == null)
{
_servTemplates = await DBManagerAsync.GetSERVTemplatesAsync(); // initial load
_servTemplates.Sort();
Trace.WriteLine($"{_servTemplates.Count} SERV templates loaded");
}
this.comboBoxGroup.ItemsSource = _servTemplates;
this.buttonDeleteTemplate.Visibility = DBManager.Instance.GetReportingPartyDict()[App.UserId.Value].IsEditor ? Visibility.Visible : Visibility.Hidden;
this.buttonEditTemplate.Visibility = DBManager.Instance.GetReportingPartyDict()[App.UserId.Value].IsEditor ? Visibility.Visible : Visibility.Hidden;
this.buttonNewTemplate.Visibility = DBManager.Instance.GetReportingPartyDict()[App.UserId.Value].IsEditor ? Visibility.Visible : Visibility.Hidden;
if (this.Core.IsFlagSet(MessageCore.CoreFlags.MAERSK_BHV)) this.comboBoxGroup.SelectedIndex = 1;
if (this.Core.IsFlagSet(MessageCore.CoreFlags.SEAGO_BHV)) this.comboBoxGroup.SelectedIndex = 2;
if (this.Core.IsFlagSet(MessageCore.CoreFlags.SEAGO_WHV)) this.comboBoxGroup.SelectedIndex = 3;
if (this.Core.IsFlagSet(MessageCore.CoreFlags.HOEGH)) this.comboBoxGroup.SelectedIndex = 4;
if (this.Core.IsFlagSet(MessageCore.CoreFlags.ELBE_BULK)) this.comboBoxGroup.SelectedIndex = 5;
if (this.Core.IsFlagSet(MessageCore.CoreFlags.FCT_JUNGE)) this.comboBoxGroup.SelectedIndex = 6;
#endregion
@ -381,100 +365,157 @@ namespace ENI2.DetailViewControls
#endregion
#region SERV template event handler
#region Spezialbalkon für die Gruppenauswahl im Core (Maersk BHV / Seago usw.)
private void comboBoxGroup_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if(this.comboBoxGroup.SelectedItem is SERV_Template st)
{
this.buttonDeleteTemplate.IsEnabled = true;
this.buttonSetTemplate.IsEnabled = true;
this._currentTemplate = st;
// clear all
this.Core.SetFlag(false, MessageCore.CoreFlags.MAERSK_BHV);
this.Core.SetFlag(false, MessageCore.CoreFlags.SEAGO_BHV);
this.Core.SetFlag(false, MessageCore.CoreFlags.SEAGO_WHV);
this.Core.SetFlag(false, MessageCore.CoreFlags.HOEGH);
this.Core.SetFlag(false, MessageCore.CoreFlags.ELBE_BULK);
this.Core.SetFlag(false, MessageCore.CoreFlags.FCT_JUNGE);
if (this.comboBoxGroup.SelectedItem == null)
{
this.comboBoxGroup.SelectedIndex = 0;
DBManager.Instance.Save(this.Core);
}
}
private void buttonSetTemplate_Click(object sender, RoutedEventArgs e)
{
if (this.comboBoxGroup.SelectedItem is SERV_Template st)
else
{
bool found = false;
foreach (SERV serv in _servMessage.Elements.Cast<SERV>())
DictionaryEntry selectedItem = (DictionaryEntry)this.comboBoxGroup.SelectedItem;
if (Int32.TryParse((string)selectedItem.Value, out int selectedValue))
{
if (serv.ServiceName.Equals(st.ServiceName))
{
found = true; break;
}
}
if (!found)
{
SERV newServ = new SERV();
newServ.ServiceName = st.ServiceName;
newServ.ServiceBeneficiary = st.ServiceBeneficiary;
newServ.ServiceInvoiceRecipient = st.ServiceInvoiceRecipient;
newServ.MessageHeader = this._servMessage;
newServ.Identifier = SERV.GetNewIdentifier(_servMessage.Elements);
this._servMessage.Elements.Add(newServ);
this.dataGridSERV.Items.Refresh();
this.SublistElementChanged(Message.NotificationClass.SERV);
}
}
}
private void buttonNewTemplate_Click(object sender, RoutedEventArgs e)
{
SERV_Template newTemplate = new SERV_Template();
EditSERVDialog esd = new EditSERVDialog();
esd.AddVisible = false;
esd.SERV_Template = newTemplate;
if(esd.ShowDialog() ?? false)
{
_ = DBManagerAsync.SaveAsync(esd.SERV_Template);
this.comboBoxGroup.ItemsSource = null;
_servTemplates.Add(newTemplate);
_servTemplates.Sort();
this.comboBoxGroup.ItemsSource = _servTemplates;
}
}
private void buttonEditTemplate_Click(object sender, RoutedEventArgs e)
{
if (this.comboBoxGroup.SelectedItem is SERV_Template st)
{
EditSERVDialog editSERVDialog = new EditSERVDialog();
editSERVDialog.AddVisible = false;
editSERVDialog.SERV_Template = st;
if (editSERVDialog.ShowDialog() ?? false)
{
_ = DBManagerAsync.SaveAsync(st);
this.comboBoxGroup.ItemsSource = null;
_servTemplates.Sort();
this.comboBoxGroup.ItemsSource = _servTemplates;
}
}
}
private void buttonDeleteTemplate_Click(object sender, RoutedEventArgs e)
{
if (_currentTemplate != null)
{
if (MessageBox.Show("Delete this template?", "Confirmation", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No) == MessageBoxResult.Yes)
{
this.comboBoxGroup.SelectedItem = null;
this.comboBoxGroup.ItemsSource = null;
_ = DBManagerAsync.DeleteAsync(_currentTemplate);
_servTemplates.Remove(_currentTemplate);
this.buttonDeleteTemplate.IsEnabled = false;
this.comboBoxGroup.ItemsSource = _servTemplates;
this.buttonSetTemplate.IsEnabled = false;
if (selectedValue == (int)MessageCore.CoreFlags.MAERSK_BHV) CheckServiceEntryMaerskBHV();
if (selectedValue == (int)MessageCore.CoreFlags.SEAGO_BHV) CheckServiceEntrySeaGoBHV();
if (selectedValue == (int)MessageCore.CoreFlags.HOEGH) CheckServiceEntryHoegh();
if (selectedValue == (int)MessageCore.CoreFlags.ELBE_BULK) CheckServiceEntryElbeBulk();
if (selectedValue == (int)MessageCore.CoreFlags.FCT_JUNGE) CheckServiceEntryFctJunge();
this.Core.SetFlag(true, (MessageCore.CoreFlags)selectedValue);
DBManager.Instance.Save(this.Core);
}
}
}
#endregion
#region other event handler
#region special entry ship service check
private void CheckServiceEntryMaerskBHV()
{
bool found = false;
foreach(SERV serv in _servMessage.Elements.Cast<SERV>())
{
if (serv.ServiceBeneficiary.Equals("Maersk A/S, Esplanaden 50, DK-1263 Copenhagen K, VAT-ID: DK53139655"))
found = true;
}
if(!found)
{
SERV newServ = new SERV();
newServ.ServiceBeneficiary = "Maersk A/S, Esplanaden 50, DK-1263 Copenhagen K, VAT-ID: DK53139655";
newServ.ServiceInvoiceRecipient = "Maersk Deutschland A/S & Co.KG, Johanniswall 7, 20095 Hamburg";
newServ.ServiceName = "Maersk BHV";
newServ.MessageHeader = this._servMessage;
newServ.Identifier = SERV.GetNewIdentifier(_servMessage.Elements);
this._servMessage.Elements.Add(newServ);
this.dataGridSERV.Items.Refresh();
this.SublistElementChanged(Message.NotificationClass.SERV);
}
}
private void CheckServiceEntrySeaGoBHV()
{
bool found = false;
foreach (SERV serv in _servMessage.Elements.Cast<SERV>())
{
if (serv.ServiceBeneficiary.Equals("Sealand Europe A/S, Dampfaergevej 10, 3.tv, DK- 2100 Copenhagen, VAT-ID: DK53139655"))
found = true;
}
if (!found)
{
SERV newServ = new SERV();
newServ.ServiceBeneficiary = "Sealand Europe A/S, Dampfaergevej 10, 3.tv, DK- 2100 Copenhagen, VAT-ID: DK53139655";
newServ.ServiceInvoiceRecipient = "Maersk Deutschland A/S & Co. KG on behalf of Sealand Europe A/S, Johanniswall 7, 20095 Hamburg";
newServ.ServiceName = "SeaGo BHV";
newServ.MessageHeader = this._servMessage;
newServ.Identifier = SERV.GetNewIdentifier(_servMessage.Elements);
this._servMessage.Elements.Add(newServ);
this.dataGridSERV.Items.Refresh();
this.SublistElementChanged(Message.NotificationClass.SERV);
}
}
private void CheckServiceEntryHoegh()
{
bool found = false;
foreach (SERV serv in _servMessage.Elements.Cast<SERV>())
{
if (serv.ServiceBeneficiary.Equals("Höegh Autoliners AS, Oslo, Norway"))
found = true;
}
if (!found)
{
SERV newServ = new SERV();
newServ.ServiceBeneficiary = "Höegh Autoliners AS, Oslo, Norway";
newServ.ServiceInvoiceRecipient = " PWL Port Services GmbH & Co. KG";
newServ.ServiceName = "HOEGH BHV";
newServ.MessageHeader = this._servMessage;
newServ.Identifier = SERV.GetNewIdentifier(_servMessage.Elements);
this._servMessage.Elements.Add(newServ);
this.dataGridSERV.Items.Refresh();
this.SublistElementChanged(Message.NotificationClass.SERV);
}
}
private void CheckServiceEntryFctJunge()
{
bool found = false;
foreach (SERV serv in _servMessage.Elements.Cast<SERV>())
{
if (serv.ServiceName.Equals("Fct Junge - Hamburg"))
found = true;
}
if (!found)
{
SERV newServ = new SERV();
newServ.ServiceBeneficiary = "";
newServ.ServiceInvoiceRecipient = " Frachtcontor Junge & Co. GmbH";
newServ.ServiceName = "Fct Junge - Hamburg";
newServ.MessageHeader = this._servMessage;
newServ.Identifier = SERV.GetNewIdentifier(_servMessage.Elements);
this._servMessage.Elements.Add(newServ);
this.dataGridSERV.Items.Refresh();
this.SublistElementChanged(Message.NotificationClass.SERV);
}
}
private void CheckServiceEntryElbeBulk()
{
bool found = false;
foreach (SERV serv in _servMessage.Elements.Cast<SERV>())
{
if (serv.ServiceName.Equals("Elbe Bulk Schiffe - Hamburg"))
found = true;
}
if (!found)
{
SERV newServ = new SERV();
newServ.ServiceBeneficiary = "";
newServ.ServiceInvoiceRecipient = " Division Elbe Bulk, Frachtcontor Junge & Co. GmbH";
newServ.ServiceName = "Elbe Bulk Schiffe - Hamburg";
newServ.MessageHeader = this._servMessage;
newServ.Identifier = SERV.GetNewIdentifier(_servMessage.Elements);
this._servMessage.Elements.Add(newServ);
this.dataGridSERV.Items.Refresh();
this.SublistElementChanged(Message.NotificationClass.SERV);
}
}
private void buttonSearchPortArea_Click(object sender, RoutedEventArgs e)
{
@ -495,28 +536,16 @@ namespace ENI2.DetailViewControls
}
}
private void buttonCopyNameFromCREWA_Click(object sender, RoutedEventArgs e)
{
CREW crewA = null;
if (this._crewaMessage.Elements.Count > 0)
{
crewA = this._crewaMessage.Elements[0] as CREW;
}
SelectCrewMemberDialog scmd = new SelectCrewMemberDialog();
scmd.CREW = crewA;
scmd.AddVisible = false;
if (scmd.ShowDialog() ?? false)
{
this.textBox_NameMaster.Text = $"{crewA.CrewMemberFirstName} {crewA.CrewMemberLastName}";
this.SublistElementChanged(Message.NotificationClass.NAME);
var binding = textBox_NameMaster.GetBindingExpression(TextBox.TextProperty);
binding?.UpdateSource();
}
}
#endregion
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
}
private void contextMenuClearMaersk_Click(object sender, RoutedEventArgs e)
{
}
}
}

View File

@ -2,17 +2,18 @@
// Description: SEC Meldung Bearbeitungsseite
//
using bsmd.database;
using ClosedXML.Excel;
using ENI2.EditControls;
using ENI2.Util;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using ENI2.EditControls;
using ENI2.Util;
using bsmd.database;
using System.Windows.Data;
using System;
using Microsoft.Win32;
using System.IO;
using ExcelDataReader;
using System.Collections.Generic;
namespace ENI2.DetailViewControls
{
@ -337,14 +338,83 @@ namespace ENI2.DetailViewControls
private void buttonImportExcel_Click(object sender, RoutedEventArgs e)
{
int importedCount = Excel.ExcelLocalImportHelper.ImportLast10PortFacilities(this._sec);
if (importedCount > 0)
OpenFileDialog ofd = new OpenFileDialog
{
this.dataGridLast10PortFacilities.Items.Refresh();
this.SublistElementChanged(Message.NotificationClass.SEC);
MessageBox.Show(String.Format(Properties.Resources.textL10PImported, importedCount),
Properties.Resources.textCaptionInformation, MessageBoxButton.OK, MessageBoxImage.Information);
Filter = "Excel Files|*.xls;*.xlsx"
};
if (ofd.ShowDialog() ?? false)
{
FileStream stream;
try
{
stream = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
List<LastTenPortFacilitiesCalled> importL10C = new List<LastTenPortFacilitiesCalled>();
try
{
do
{
int cnt = 0;
while (reader.Read() && (cnt < 10))
{
if (((IExcelDataReader)reader).FieldCount < 8)
{
throw new InvalidDataException("Sheet must have 8 Columns of data");
}
LastTenPortFacilitiesCalled l10c = new LastTenPortFacilitiesCalled();
if (reader.IsDBNull(0) && reader.IsDBNull(1)) continue;
if (!reader.IsDBNull(0)) l10c.PortFacilityPortName = reader.GetString(0);
if (!reader.IsDBNull(2)) l10c.PortFacilityPortCountry = reader.GetString(2);
if (!reader.IsDBNull(3)) l10c.PortFacilityPortLoCode = reader.GetString(3);
object o = null;
if (!reader.IsDBNull(4)) o = reader.GetValue(4);
if(o != null) l10c.PortFacilityDateOfArrival = Convert.ToDateTime(o);
if (!reader.IsDBNull(5)) o = reader.GetValue(5);
if (o != null) l10c.PortFacilityDateOfDeparture = Convert.ToDateTime(o);
// if (!reader.IsDBNull(4)) l10c.PortFacilityDateOfArrival = reader.GetDateTime(4);
// if (!reader.IsDBNull(5)) l10c.PortFacilityDateOfDeparture = reader.GetDateTime(5);
if (!reader.IsDBNull(6)) o = reader.GetValue(6);
if (o != null) l10c.PortFacilityShipSecurityLevel = Convert.ToByte(o);
if (!reader.IsDBNull(7)) o = reader.GetValue(7);
int gisis = Convert.ToInt32(o);
if (!reader.IsDBNull(7)) l10c.PortFacilityGISISCode = gisis.ToString().PadLeft(4, '0');
if (!reader.IsDBNull(8)) l10c.PortFacilitySecurityMattersToReport = reader.GetString(8);
if (l10c.PortFacilitySecurityMattersToReport.Equals("nil", StringComparison.CurrentCultureIgnoreCase))
l10c.PortFacilitySecurityMattersToReport = null;
if (!reader.IsDBNull(9)) l10c.PortFacilityGISISCodeLocode = reader.GetString(9);
l10c.SEC = this._sec;
l10c.IsDirty = true;
l10c.Identifier = LastTenPortFacilitiesCalled.GetNewIdentifier(this._sec.LastTenPortFacilitesCalled);
this._sec.LastTenPortFacilitesCalled.Add(l10c);
importL10C.Add(l10c);
cnt++;
}
} while (reader.NextResult());
}
catch (Exception ex)
{
MessageBox.Show("Error reading Excel: " + ex.Message, Properties.Resources.textCaptionError, MessageBoxButton.OK, MessageBoxImage.Error);
}
if (importL10C.Count > 0)
{
this.dataGridLast10PortFacilities.Items.Refresh();
this.SublistElementChanged(Message.NotificationClass.SEC);
MessageBox.Show(String.Format(Properties.Resources.textL10PImported, importL10C.Count), Properties.Resources.textCaptionInformation, MessageBoxButton.OK, MessageBoxImage.Information);
}
}
stream.Close();
}
}

View File

@ -12,7 +12,7 @@
mc:Ignorable="d"
d:DesignHeight="600" d:DesignWidth="800">
<GroupBox Name="shipDataGroupBox" Header="{x:Static p:Resources.textShipData}" >
<ScrollViewer PreviewMouseWheel="ScrollViewer_PreviewMouseWheel">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="260" />
@ -104,6 +104,6 @@
</Grid>
</GroupBox>
</Grid>
</ScrollViewer>
</GroupBox>
</src:DetailBaseControl>

View File

@ -35,6 +35,7 @@
<RowDefinition Height="28" />
<RowDefinition Height="*" />
<RowDefinition Height="28" />
<RowDefinition Height="28" />
</Grid.RowDefinitions>
<Label HorizontalContentAlignment="Right" Grid.Row="0" Grid.Column="0" Content="{x:Static p:Resources.textAccurateDetailsGiven}" Name="label_AccurateDetailsGiven" Margin="0,0,10,0"/>
<!--TextBlock Grid.Row="0" Grid.Column="0" Text="{x:Static p:Resources.textAccurateDetailsGiven}" Name="label_ETAToPortOfCall" Margin="0,0,10,0" TextWrapping="Wrap" FontSize="10"/-->
@ -55,9 +56,38 @@
<enictrl:LocodeControl Grid.Row="2" Grid.Column="1" x:Name="locodeCtrlLastWastePort" LocodeValue="{Binding LastWasteDisposalPort, Mode=TwoWay}" LocodeSource="SSN" />
<enictrl:LocodeControl Grid.Row="3" Grid.Column="1" x:Name="locodeCtrlNextWastePort" LocodeValue="{Binding NextWasteDisposalPort, Mode=TwoWay}" LocodeSource="SSN" />
<TextBox Grid.Row="4" Grid.Column="1" Grid.ColumnSpan="3" Grid.RowSpan="2" Name="textBoxWasteDisposalServiceProviders" Text="{Binding WasteDisposalServiceProviderText, Converter={util:TrimStringConverter}}" Margin="2" />
<Button Grid.Row="6" Grid.Column="1" Grid.ColumnSpan="1" Name="buttonAddMissingEntries" Content="{x:Static p:Resources.textAddMissingEntries}" Margin="2" Click="buttonAddMissingEntries_Click"/>
<Button Grid.Row="6" Grid.Column="2" Grid.ColumnSpan="1" Name="buttonImportFromExcel" Content="{x:Static p:Resources.textImportFromExcel}" Margin="2" Click="buttonImportFromExcel_Click" />
<Label Grid.Row="6" Grid.Column="0" HorizontalContentAlignment="Right" Content="{x:Static p:Resources.textAgentTemplate}" Margin="0,0,10,0" />
<ComboBox Grid.Row="6" Grid.Column="1" Grid.ColumnSpan="2" Name="comboBox_WSDPTemplate" Margin="2" SelectedValuePath="Id" DisplayMemberPath="Remark" SelectionChanged="comboBox_WSDPTemplate_SelectionChanged" />
<Grid Grid.Row="6" Grid.Column="3" Grid.ColumnSpan="1" Name="gridTemplateControls" Visibility="Visible">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<!-- Name -->
<ColumnDefinition Width="26"/>
<!-- Save button -->
<ColumnDefinition Width="26"/>
<!-- Delete button -->
<ColumnDefinition Width="52"/>
<!-- Undo button -->
</Grid.ColumnDefinitions>
<TextBox Grid.Column="0" Margin="2" Name="textBoxTemplateTitle" VerticalContentAlignment="Center"/>
<Button Name="buttonSaveTemplate" Grid.Column="1" Grid.Row="0" Margin="2" Click="buttonSaveTemplate_Click" BorderThickness="0" Background="Transparent" ToolTip="Save template">
<StackPanel Orientation="Horizontal">
<Image Source="../Resources/floppy_disk_blue.png" Margin="0,0,0,0" Height="20" Width="20" />
</StackPanel>
</Button>
<Button Name="buttonDeleteTemplate" Grid.Column="2" Grid.Row="0" Margin="2" Click="buttonDeleteTemplate_Click" BorderThickness="0" Background="Transparent" ToolTip="Delete template" IsEnabled="False">
<StackPanel Orientation="Horizontal">
<Image Source="../Resources/delete.png" Margin="0,0,0,0" Height="20" Width="20" />
</StackPanel>
</Button>
<Button Name="buttonUndoTemplate" Grid.Column="3" Grid.Row="0" Margin="22,2,2,2" Click="buttonUndoTemplate_Click" BorderThickness="0" Background="Transparent" ToolTip="Undo last overwrite" IsEnabled="False">
<StackPanel Orientation="Horizontal">
<Image Source="../Resources/undo.png" Margin="0,0,0,0" Height="20" Width="20" />
</StackPanel>
</Button>
</Grid>
<Button Grid.Row="7" Grid.Column="1" Grid.ColumnSpan="1" Name="buttonAddMissingEntries" Content="{x:Static p:Resources.textAddMissingEntries}" Margin="2" Click="buttonAddMissingEntries_Click"/>
<Button Grid.Row="7" Grid.Column="2" Grid.ColumnSpan="1" Name="buttonImportFromExcel" Content="{x:Static p:Resources.textImportFromExcel}" Margin="2" Click="buttonImportFromExcel_Click" />
</Grid>
<enictrl:ENIDataGrid x:Name="dataGridWaste" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch"
AutoGenerateColumns="False" Margin="0,5,0,0" Grid.Row="1" CanUserAddRows="False">

View File

@ -2,18 +2,19 @@
// Description: Detailansicht Müllmeldung
//
using bsmd.database;
using ClosedXML.Excel;
using ENI2.EditControls;
using ENI2.Excel;
using ENI2.Util;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using ENI2.EditControls;
using ENI2.Util;
using bsmd.database;
using ExcelDataReader;
using System.IO;
using System;
using Microsoft.Win32;
using System.Diagnostics;
using System.Threading.Tasks;
namespace ENI2.DetailViewControls
{
@ -23,14 +24,14 @@ namespace ENI2.DetailViewControls
public partial class WasteDetailControl : DetailBaseControl
{
#region Fields
private Message _wasMessage;
private WAS _was;
private Message _wasRcptMessage;
private WAS_RCPT _selectedWAS_RCPT;
#endregion
private static List<WasteDisposalServiceProvider_Template> _wsdpTemplates = null;
private WasteDisposalServiceProvider_Template _currentTemplate;
private string _undoTemplate;
public WasteDetailControl()
{
@ -45,7 +46,7 @@ namespace ENI2.DetailViewControls
this.RegisterLocodeChange(this.locodeCtrlNextWastePort, Message.NotificationClass.WAS);
this.RegisterCheckboxChange(this.checkBoxAccurateCorrectDetails, Message.NotificationClass.WAS);
this.RegisterCheckboxChange(this.checkBoxValidExemption, Message.NotificationClass.WAS);
this.RegisterDatePickerChange(this.datePickerDateLastDisposal, Message.NotificationClass.WAS);
this.RegisterDatePickerChange(this.datePickerDateLastDisposal, Message.NotificationClass.WAS);
this.RegisterTextboxChange(this.textBoxWasteDisposalServiceProviders, Message.NotificationClass.WAS);
this.dataGridWasteReceived.CellEditEnding += (obj, ev) => { this.SublistElementChanged(Message.NotificationClass.WAS_RCPT); };
}
@ -76,7 +77,7 @@ namespace ENI2.DetailViewControls
WasteCapacity_MTQ = 0,
WasteDescription = "",
WasteDisposalAmount_MTQ = 0,
WasteDisposalPort = "ZZUKN"
WasteDisposalPort = "ZZUKN"
};
this._was.Waste.Add(newWaste);
}
@ -95,7 +96,7 @@ namespace ENI2.DetailViewControls
}
}
public override void Initialize()
public async override void Initialize()
{
base.Initialize();
@ -122,7 +123,7 @@ namespace ENI2.DetailViewControls
was.MessageCore = this.Core;
was.MessageHeader = this._wasMessage;
_wasMessage.Elements.Add(was);
}
}
else
{
// remove "old" Waste Entries from display (not deleted in the DB!)
@ -130,14 +131,14 @@ namespace ENI2.DetailViewControls
{
if (was.Waste[i].WasteType > 999)
was.Waste.RemoveAt(i);
}
}
}
this.wasGroupBox.DataContext = was;
this._was = was;
this.dataGridWaste.Initialize();
this.dataGridWaste.ItemsSource = was.Waste;
this.dataGridWaste.ItemsSource = was.Waste;
this.dataGridWaste.AddingNewItem += DataGridWaste_AddingNewItem;
this.dataGridWaste.EditRequested += DataGridWaste_EditRequested;
this.dataGridWaste.DeleteRequested += DataGridWaste_DeleteRequested;
@ -176,6 +177,14 @@ namespace ENI2.DetailViewControls
#endregion
#region init WSDP provider
await InitTemplates();
this.comboBox_WSDPTemplate.ItemsSource = _wsdpTemplates;
#endregion
}
public override int SelectedTabIndex
@ -186,7 +195,7 @@ namespace ENI2.DetailViewControls
#region Waste receipt grid event handler
private void DataGridWasteReceipt_CreateRequested()
private async void DataGridWasteReceipt_CreateRequested()
{
EditWasteReceiptDialog epd = new EditWasteReceiptDialog();
epd.WAS_RCPT = new WAS_RCPT();
@ -214,11 +223,11 @@ namespace ENI2.DetailViewControls
this.dataGridWasteReceipt.Items.Refresh();
this.dataGridWasteReceipt.SelectedItem = epd.WAS_RCPT;
this.SublistElementChanged(Message.NotificationClass.WAS_RCPT);
this.dataGridWasteReceived.ItemsSource = null;
this.dataGridWasteReceived.ItemsSource = null;
dataGridWasteReceipt_SelectionChanged(this, null);
}
await InitTemplates(); // templates might have changed in the dialog
}
private void DataGridWasteReceipt_DeleteRequested(DatabaseEntity obj)
@ -237,7 +246,7 @@ namespace ENI2.DetailViewControls
}
}
private void DataGridWasteReceipt_EditRequested(DatabaseEntity obj)
private async void DataGridWasteReceipt_EditRequested(DatabaseEntity obj)
{
EditWasteReceiptDialog epd = new EditWasteReceiptDialog();
epd.WAS_RCPT = obj as WAS_RCPT;
@ -260,11 +269,11 @@ namespace ENI2.DetailViewControls
if (!_wasRcptMessage.Elements.Contains(epd.WAS_RCPT))
_wasRcptMessage.Elements.Add(epd.WAS_RCPT);
}
this.dataGridWasteReceipt.SelectedItem = epd.WAS_RCPT;
this.dataGridWasteReceipt.SelectedItem = epd.WAS_RCPT;
this.dataGridWasteReceipt.Items.Refresh();
this.SublistElementChanged(Message.NotificationClass.WAS_RCPT);
dataGridWasteReceipt_SelectionChanged(this, null);
await InitTemplates(); // templates might have changed in the dialog
}
private void DataGridWasteReceipt_AddingNewItem(object sender, AddingNewItemEventArgs e)
@ -416,7 +425,7 @@ namespace ENI2.DetailViewControls
{
// are you sure dialog is in base class
_was.Waste.Remove(waste);
DBManager.GetSingleCon(Properties.Settings.Default.ConnectionString).Delete(waste);
DBManager.GetSingleCon(Properties.Settings.Default.ConnectionString).Delete(waste);
DatabaseEntity.ResetIdentifiers(new List<DatabaseEntity>(_was.Waste));
this.SublistElementChanged(Message.NotificationClass.WAS);
this.dataGridWaste.Items.Refresh();
@ -474,24 +483,210 @@ namespace ENI2.DetailViewControls
HighlightService.HighlightControl(this.wasGroupBox, HighlightService.HighlightStyle.VIOLATION, this._wasMessage);
}
#endregion
#endregion
#region Excel file import
private void buttonImportFromExcel_Click(object sender, RoutedEventArgs e)
{
int importWasteListCnt = ExcelLocalImportHelper.ImportWaste(_was);
if (importWasteListCnt > 0)
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Excel Files|*.xls;*.xlsx";
if (ofd.ShowDialog() ?? false)
{
this.dataGridWaste.Items.Refresh();
this.SublistElementChanged(Message.NotificationClass.WAS);
MessageBox.Show(String.Format(Properties.Resources.textWasteImported, importWasteListCnt), Properties.Resources.textCaptionInformation, MessageBoxButton.OK, MessageBoxImage.Information);
}
FileStream stream;
try
{
stream = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
List<Waste> importWasteList = new List<Waste>();
try
{
do
{
// skip first three rows
reader.Read();
reader.Read();
reader.Read();
int cnt = 0;
object o = null;
// Diese Funktion kann das "alte" Sheet Format nicht mehr einlesen!
while (reader.Read() && (cnt < 35))
{
if (reader.FieldCount < 9)
{
throw new InvalidDataException("Sheet must have 9 Columns of data");
}
if (!reader.IsDBNull(1)) o = reader.GetValue(1); else o = null;
if ((o != null) && Int32.TryParse(o.ToString(), out int wasteType))
{
Waste waste = _was.GetWasteForType(wasteType);
if (waste == null)
{
waste = new Waste();
waste.WasteType = wasteType;
waste.WAS = this._was;
waste.IsDirty = true;
waste.Identifier = Waste.GetNewIdentifier(this._was.Waste);
this._was.Waste.Add(waste);
}
else
{
waste.IsDirty = true;
}
if (!reader.IsDBNull(4)) waste.WasteDescription = reader.GetString(4);
if (waste.WasteDescription.IsNullOrEmpty())
waste.WasteDescription = "-";
if (!reader.IsDBNull(5)) o = reader.GetValue(5); else o = null;
if (o != null) waste.WasteDisposalAmount_MTQ = Convert.ToDouble(o);
if (!reader.IsDBNull(6)) o = reader.GetValue(6); else o = null;
if (o != null) waste.WasteCapacity_MTQ = Convert.ToDouble(o);
if (!reader.IsDBNull(7)) o = reader.GetValue(7); else o = null;
if (o != null) waste.WasteAmountRetained_MTQ = Convert.ToDouble(o);
if (!reader.IsDBNull(8)) waste.WasteDisposalPort = reader.GetString(8).ToUpper();
if (!reader.IsDBNull(9)) o = reader.GetValue(9); else o = null;
if (o != null) waste.WasteAmountGeneratedTillNextPort_MTQ = Convert.ToDouble(o);
importWasteList.Add(waste);
cnt++;
}
}
} while (reader.NextResult());
}
catch (Exception ex)
{
MessageBox.Show("Error reading Excel: " + ex.Message, Properties.Resources.textCaptionError, MessageBoxButton.OK, MessageBoxImage.Error);
}
if (importWasteList.Count > 0)
{
this.dataGridWaste.Items.Refresh();
this.SublistElementChanged(Message.NotificationClass.WAS);
MessageBox.Show(String.Format(Properties.Resources.textWasteImported, importWasteList.Count), Properties.Resources.textCaptionInformation, MessageBoxButton.OK, MessageBoxImage.Information);
}
}
stream.Close();
}
}
#endregion
#endregion
#region Waste disposal Service Provider templates event handler
private async Task InitTemplates()
{
_wsdpTemplates = await DBManagerAsync.GetWastDisposalServiceProviderTemplatesAsync();
_wsdpTemplates.Sort();
this.comboBox_WSDPTemplate.ItemsSource = null;
this.comboBox_WSDPTemplate.ItemsSource = _wsdpTemplates;
Trace.WriteLine($"{_wsdpTemplates.Count} WSDP templates loaded");
}
private void comboBox_WSDPTemplate_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Trace.WriteLine("WSDP combo selection changed");
if(this.comboBox_WSDPTemplate.SelectedItem is WasteDisposalServiceProvider_Template wdsp_t)
{
this.textBoxTemplateTitle.Text = wdsp_t.Remark;
this.buttonDeleteTemplate.IsEnabled = true;
this._currentTemplate = wdsp_t;
this._undoTemplate = this.textBoxWasteDisposalServiceProviders.Text.Trim();
this.buttonUndoTemplate.IsEnabled = this._undoTemplate.Length > 0;
this.textBoxWasteDisposalServiceProviders.Text = wdsp_t.WasteDisposalServiceProviderName;
}
}
private async void buttonSaveTemplate_Click(object sender, RoutedEventArgs e)
{
string currentWSDPProviderName = this.textBoxWasteDisposalServiceProviders.Text.Trim();
string currentRemark = this.textBoxTemplateTitle.Text.Trim();
if ((currentWSDPProviderName.Length == 0) || (currentRemark.Length == 0)) return;
WasteDisposalServiceProvider_Template existingTemplate = null;
foreach(WasteDisposalServiceProvider_Template wdsp_template in _wsdpTemplates)
{
// bei gefundenem Match wird ggf. der Remark überschrieben
if (wdsp_template.Remark.Equals(currentRemark))
{
existingTemplate = wdsp_template;
break;
}
}
if(existingTemplate != null)
{
if (MessageBox.Show("A template with this name already exists, overwrite?", "Confirmation", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No) == MessageBoxResult.No)
return;
existingTemplate.WasteDisposalServiceProviderName = currentWSDPProviderName;
await DBManagerAsync.SaveAsync(existingTemplate);
return;
}
WasteDisposalServiceProvider_Template newTemplate = new WasteDisposalServiceProvider_Template();
newTemplate.WasteDisposalServiceProviderName = currentWSDPProviderName;
newTemplate.Remark = currentRemark;
await DBManagerAsync.SaveAsync(newTemplate);
comboBox_WSDPTemplate.ItemsSource = null;
_wsdpTemplates.Add(newTemplate);
_wsdpTemplates.Sort();
comboBox_WSDPTemplate.ItemsSource = _wsdpTemplates;
MessageBox.Show("Template saved", "OK", MessageBoxButton.OK, MessageBoxImage.Information);
}
private void buttonDeleteTemplate_Click(object sender, RoutedEventArgs e)
{
if(_currentTemplate != null)
{
if (MessageBox.Show("Delete this template?", "Confirmation", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No) == MessageBoxResult.Yes)
{
this.comboBox_WSDPTemplate.SelectedItem = null;
this.comboBox_WSDPTemplate.ItemsSource = null;
DBManager.Instance.Delete(_currentTemplate);
_wsdpTemplates.Remove(_currentTemplate);
this.textBoxTemplateTitle.Text = null;
this.buttonDeleteTemplate.IsEnabled = false;
this.comboBox_WSDPTemplate.ItemsSource = _wsdpTemplates;
}
}
}
private void buttonUndoTemplate_Click(object sender, RoutedEventArgs e)
{
if(this._undoTemplate != null)
{
this.textBoxWasteDisposalServiceProviders.Text = this._undoTemplate;
this.buttonUndoTemplate.IsEnabled = false;
this._undoTemplate = null;
this.comboBox_WSDPTemplate.SelectedItem = null;
}
}
#endregion
#region Copy WAS to WAS_RCPT handler
@ -499,7 +694,7 @@ namespace ENI2.DetailViewControls
{
if (_selectedWAS_RCPT == null) return;
if(MessageBox.Show(Properties.Resources.textCopyToWASConfirmation, Properties.Resources.textConfirmation,
if(MessageBox.Show(Properties.Resources.textCopyToWASConfirmation, Properties.Resources.textConfirmation,
MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No) == MessageBoxResult.Yes)
{
foreach(Waste waste in _was.Waste)

View File

@ -9,7 +9,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>ENI2</RootNamespace>
<AssemblyName>ENI2Test</AssemblyName>
<TargetFrameworkVersion>v4.8.1</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<WarningLevel>4</WarningLevel>
@ -36,8 +36,8 @@
<MinimumRequiredVersion>5.4.0.0</MinimumRequiredVersion>
<CreateWebPageOnPublish>true</CreateWebPageOnPublish>
<WebPage>publish.html</WebPage>
<ApplicationRevision>2</ApplicationRevision>
<ApplicationVersion>7.2.14.2</ApplicationVersion>
<ApplicationRevision>1</ApplicationRevision>
<ApplicationVersion>7.2.8.1</ApplicationVersion>
<UseApplicationTrust>false</UseApplicationTrust>
<CreateDesktopShortcut>true</CreateDesktopShortcut>
<PublishWizardCompleted>true</PublishWizardCompleted>
@ -134,92 +134,63 @@
<CodeAnalysisRuleSet>..\code.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<Reference Include="ClosedXML, Version=0.105.0.0, Culture=neutral, PublicKeyToken=fd1eb21b62ae805b, processorArchitecture=MSIL">
<HintPath>packages\ClosedXML.0.105.0\lib\netstandard2.0\ClosedXML.dll</HintPath>
<Reference Include="ExcelDataReader, Version=3.7.0.0, Culture=neutral, PublicKeyToken=93517dbe6a4012fa, processorArchitecture=MSIL">
<HintPath>packages\ExcelDataReader.3.7.0\lib\net462\ExcelDataReader.dll</HintPath>
</Reference>
<Reference Include="ClosedXML.Parser, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1d5f7376574c51ec, processorArchitecture=MSIL">
<HintPath>packages\ClosedXML.Parser.2.0.0\lib\netstandard2.0\ClosedXML.Parser.dll</HintPath>
<Reference Include="log4net, Version=3.0.4.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<HintPath>packages\log4net.3.0.4\lib\net462\log4net.dll</HintPath>
</Reference>
<Reference Include="DocumentFormat.OpenXml, Version=3.3.0.0, Culture=neutral, PublicKeyToken=8fb06cb64d019a17, processorArchitecture=MSIL">
<HintPath>packages\DocumentFormat.OpenXml.3.3.0\lib\net46\DocumentFormat.OpenXml.dll</HintPath>
<Reference Include="Microsoft.Bcl.AsyncInterfaces, Version=9.0.0.4, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.Bcl.AsyncInterfaces.9.0.4\lib\net462\Microsoft.Bcl.AsyncInterfaces.dll</HintPath>
</Reference>
<Reference Include="DocumentFormat.OpenXml.Framework, Version=3.3.0.0, Culture=neutral, PublicKeyToken=8fb06cb64d019a17, processorArchitecture=MSIL">
<HintPath>packages\DocumentFormat.OpenXml.Framework.3.3.0\lib\net46\DocumentFormat.OpenXml.Framework.dll</HintPath>
<Reference Include="Microsoft.Extensions.DependencyInjection, Version=9.0.0.4, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.Extensions.DependencyInjection.9.0.4\lib\net462\Microsoft.Extensions.DependencyInjection.dll</HintPath>
</Reference>
<Reference Include="ExcelNumberFormat, Version=1.1.0.0, Culture=neutral, PublicKeyToken=23c6f5d73be07eca, processorArchitecture=MSIL">
<HintPath>packages\ExcelNumberFormat.1.1.0\lib\net20\ExcelNumberFormat.dll</HintPath>
<Reference Include="Microsoft.Extensions.DependencyInjection.Abstractions, Version=9.0.0.4, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.Extensions.DependencyInjection.Abstractions.9.0.4\lib\net462\Microsoft.Extensions.DependencyInjection.Abstractions.dll</HintPath>
</Reference>
<Reference Include="log4net, Version=3.2.0.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<HintPath>packages\log4net.3.2.0\lib\net462\log4net.dll</HintPath>
<Reference Include="Microsoft.Extensions.Logging, Version=9.0.0.4, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.Extensions.Logging.9.0.4\lib\net462\Microsoft.Extensions.Logging.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Bcl.AsyncInterfaces, Version=10.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.Bcl.AsyncInterfaces.10.0.0\lib\net462\Microsoft.Bcl.AsyncInterfaces.dll</HintPath>
<Reference Include="Microsoft.Extensions.Logging.Abstractions, Version=9.0.0.4, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.Extensions.Logging.Abstractions.9.0.4\lib\net462\Microsoft.Extensions.Logging.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Bcl.Cryptography, Version=10.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.Bcl.Cryptography.10.0.0\lib\net462\Microsoft.Bcl.Cryptography.dll</HintPath>
<Reference Include="Microsoft.Extensions.Options, Version=9.0.0.4, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.Extensions.Options.9.0.4\lib\net462\Microsoft.Extensions.Options.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Bcl.HashCode, Version=6.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.Bcl.HashCode.6.0.0\lib\net462\Microsoft.Bcl.HashCode.dll</HintPath>
<Reference Include="Microsoft.Extensions.Primitives, Version=9.0.0.4, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.Extensions.Primitives.9.0.4\lib\net462\Microsoft.Extensions.Primitives.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.DependencyInjection, Version=10.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.Extensions.DependencyInjection.10.0.0\lib\net462\Microsoft.Extensions.DependencyInjection.dll</HintPath>
<Reference Include="Microsoft.Office.Interop.Excel, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.Office.Interop.Excel.15.0.4795.1001\lib\net20\Microsoft.Office.Interop.Excel.dll</HintPath>
<EmbedInteropTypes>True</EmbedInteropTypes>
</Reference>
<Reference Include="Microsoft.Extensions.DependencyInjection.Abstractions, Version=10.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.Extensions.DependencyInjection.Abstractions.10.0.0\lib\net462\Microsoft.Extensions.DependencyInjection.Abstractions.dll</HintPath>
<Reference Include="MigraDoc.DocumentObjectModel, Version=6.1.1.0, Culture=neutral, PublicKeyToken=f94615aa0424f9eb, processorArchitecture=MSIL">
<HintPath>packages\PDFsharp-MigraDoc.6.1.1\lib\netstandard2.0\MigraDoc.DocumentObjectModel.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Logging, Version=10.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.Extensions.Logging.10.0.0\lib\net462\Microsoft.Extensions.Logging.dll</HintPath>
<Reference Include="MigraDoc.Rendering, Version=6.1.1.0, Culture=neutral, PublicKeyToken=f94615aa0424f9eb, processorArchitecture=MSIL">
<HintPath>packages\PDFsharp-MigraDoc.6.1.1\lib\netstandard2.0\MigraDoc.Rendering.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Logging.Abstractions, Version=10.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.Extensions.Logging.Abstractions.10.0.0\lib\net462\Microsoft.Extensions.Logging.Abstractions.dll</HintPath>
<Reference Include="MigraDoc.RtfRendering, Version=6.1.1.0, Culture=neutral, PublicKeyToken=f94615aa0424f9eb, processorArchitecture=MSIL">
<HintPath>packages\PDFsharp-MigraDoc.6.1.1\lib\netstandard2.0\MigraDoc.RtfRendering.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Options, Version=10.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.Extensions.Options.10.0.0\lib\net462\Microsoft.Extensions.Options.dll</HintPath>
<Reference Include="PdfSharp, Version=6.1.1.0, Culture=neutral, PublicKeyToken=f94615aa0424f9eb, processorArchitecture=MSIL">
<HintPath>packages\PDFsharp-MigraDoc.6.1.1\lib\netstandard2.0\PdfSharp.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Extensions.Primitives, Version=10.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.Extensions.Primitives.10.0.0\lib\net462\Microsoft.Extensions.Primitives.dll</HintPath>
<Reference Include="PdfSharp.Charting, Version=6.1.1.0, Culture=neutral, PublicKeyToken=f94615aa0424f9eb, processorArchitecture=MSIL">
<HintPath>packages\PDFsharp-MigraDoc.6.1.1\lib\netstandard2.0\PdfSharp.Charting.dll</HintPath>
</Reference>
<Reference Include="MigraDoc.DocumentObjectModel, Version=6.2.3.0, Culture=neutral, PublicKeyToken=f94615aa0424f9eb, processorArchitecture=MSIL">
<HintPath>packages\PDFsharp-MigraDoc.6.2.3\lib\netstandard2.0\MigraDoc.DocumentObjectModel.dll</HintPath>
<Reference Include="PdfSharp.Quality, Version=6.1.1.0, Culture=neutral, PublicKeyToken=f94615aa0424f9eb, processorArchitecture=MSIL">
<HintPath>packages\PDFsharp-MigraDoc.6.1.1\lib\netstandard2.0\PdfSharp.Quality.dll</HintPath>
</Reference>
<Reference Include="MigraDoc.Rendering, Version=6.2.3.0, Culture=neutral, PublicKeyToken=f94615aa0424f9eb, processorArchitecture=MSIL">
<HintPath>packages\PDFsharp-MigraDoc.6.2.3\lib\netstandard2.0\MigraDoc.Rendering.dll</HintPath>
<Reference Include="PdfSharp.Snippets, Version=6.1.1.0, Culture=neutral, PublicKeyToken=f94615aa0424f9eb, processorArchitecture=MSIL">
<HintPath>packages\PDFsharp-MigraDoc.6.1.1\lib\netstandard2.0\PdfSharp.Snippets.dll</HintPath>
</Reference>
<Reference Include="MigraDoc.RtfRendering, Version=6.2.3.0, Culture=neutral, PublicKeyToken=f94615aa0424f9eb, processorArchitecture=MSIL">
<HintPath>packages\PDFsharp-MigraDoc.6.2.3\lib\netstandard2.0\MigraDoc.RtfRendering.dll</HintPath>
<Reference Include="PdfSharp.System, Version=6.1.1.0, Culture=neutral, PublicKeyToken=f94615aa0424f9eb, processorArchitecture=MSIL">
<HintPath>packages\PDFsharp-MigraDoc.6.1.1\lib\netstandard2.0\PdfSharp.System.dll</HintPath>
</Reference>
<Reference Include="PdfSharp, Version=6.2.3.0, Culture=neutral, PublicKeyToken=f94615aa0424f9eb, processorArchitecture=MSIL">
<HintPath>packages\PDFsharp.6.2.3\lib\netstandard2.0\PdfSharp.dll</HintPath>
</Reference>
<Reference Include="PdfSharp.BarCodes, Version=6.2.3.0, Culture=neutral, PublicKeyToken=f94615aa0424f9eb, processorArchitecture=MSIL">
<HintPath>packages\PDFsharp.6.2.3\lib\netstandard2.0\PdfSharp.BarCodes.dll</HintPath>
</Reference>
<Reference Include="PdfSharp.Charting, Version=6.2.3.0, Culture=neutral, PublicKeyToken=f94615aa0424f9eb, processorArchitecture=MSIL">
<HintPath>packages\PDFsharp.6.2.3\lib\netstandard2.0\PdfSharp.Charting.dll</HintPath>
</Reference>
<Reference Include="PdfSharp.Cryptography, Version=6.2.3.0, Culture=neutral, PublicKeyToken=f94615aa0424f9eb, processorArchitecture=MSIL">
<HintPath>packages\PDFsharp.6.2.3\lib\netstandard2.0\PdfSharp.Cryptography.dll</HintPath>
</Reference>
<Reference Include="PdfSharp.Quality, Version=6.2.3.0, Culture=neutral, PublicKeyToken=f94615aa0424f9eb, processorArchitecture=MSIL">
<HintPath>packages\PDFsharp.6.2.3\lib\netstandard2.0\PdfSharp.Quality.dll</HintPath>
</Reference>
<Reference Include="PdfSharp.Shared, Version=6.2.3.0, Culture=neutral, PublicKeyToken=f94615aa0424f9eb, processorArchitecture=MSIL">
<HintPath>packages\PDFsharp.6.2.3\lib\netstandard2.0\PdfSharp.Shared.dll</HintPath>
</Reference>
<Reference Include="PdfSharp.Snippets, Version=6.2.3.0, Culture=neutral, PublicKeyToken=f94615aa0424f9eb, processorArchitecture=MSIL">
<HintPath>packages\PDFsharp.6.2.3\lib\netstandard2.0\PdfSharp.Snippets.dll</HintPath>
</Reference>
<Reference Include="PdfSharp.System, Version=6.2.3.0, Culture=neutral, PublicKeyToken=f94615aa0424f9eb, processorArchitecture=MSIL">
<HintPath>packages\PDFsharp.6.2.3\lib\netstandard2.0\PdfSharp.System.dll</HintPath>
</Reference>
<Reference Include="PdfSharp.WPFonts, Version=6.2.3.0, Culture=neutral, PublicKeyToken=f94615aa0424f9eb, processorArchitecture=MSIL">
<HintPath>packages\PDFsharp.6.2.3\lib\netstandard2.0\PdfSharp.WPFonts.dll</HintPath>
</Reference>
<Reference Include="RBush, Version=4.0.0.0, Culture=neutral, PublicKeyToken=c77e27b81f4d0187, processorArchitecture=MSIL">
<HintPath>packages\RBush.Signed.4.0.0\lib\net47\RBush.dll</HintPath>
</Reference>
<Reference Include="SixLabors.Fonts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=d998eea7b14cab13, processorArchitecture=MSIL">
<HintPath>packages\SixLabors.Fonts.1.0.0\lib\netstandard2.0\SixLabors.Fonts.dll</HintPath>
<Reference Include="PdfSharp.WPFonts, Version=6.1.1.0, Culture=neutral, PublicKeyToken=f94615aa0424f9eb, processorArchitecture=MSIL">
<HintPath>packages\PDFsharp-MigraDoc.6.1.1\lib\netstandard2.0\PdfSharp.WPFonts.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Buffers, Version=4.0.5.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
@ -231,13 +202,10 @@
<Reference Include="System.Data.SQLite, Version=1.0.119.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139, processorArchitecture=MSIL">
<HintPath>packages\Stub.System.Data.SQLite.Core.NetFramework.1.0.119.0\lib\net46\System.Data.SQLite.dll</HintPath>
</Reference>
<Reference Include="System.Diagnostics.DiagnosticSource, Version=10.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>packages\System.Diagnostics.DiagnosticSource.10.0.0\lib\net462\System.Diagnostics.DiagnosticSource.dll</HintPath>
<Reference Include="System.Diagnostics.DiagnosticSource, Version=9.0.0.4, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>packages\System.Diagnostics.DiagnosticSource.9.0.4\lib\net462\System.Diagnostics.DiagnosticSource.dll</HintPath>
</Reference>
<Reference Include="System.Drawing" />
<Reference Include="System.Formats.Asn1, Version=10.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>packages\System.Formats.Asn1.10.0.0\lib\net462\System.Formats.Asn1.dll</HintPath>
</Reference>
<Reference Include="System.IO.Compression" />
<Reference Include="System.Memory, Version=4.0.5.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>packages\System.Memory.4.6.3\lib\net462\System.Memory.dll</HintPath>
@ -250,10 +218,6 @@
<HintPath>packages\System.Runtime.CompilerServices.Unsafe.6.1.2\lib\net462\System.Runtime.CompilerServices.Unsafe.dll</HintPath>
</Reference>
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.Security" />
<Reference Include="System.Security.Cryptography.Pkcs, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>packages\System.Security.Cryptography.Pkcs.10.0.0\lib\net462\System.Security.Cryptography.Pkcs.dll</HintPath>
</Reference>
<Reference Include="System.ServiceModel" />
<Reference Include="System.ServiceModel.Web" />
<Reference Include="System.ServiceProcess" />
@ -274,20 +238,20 @@
<Reference Include="WindowsBase" />
<Reference Include="PresentationCore" />
<Reference Include="PresentationFramework" />
<Reference Include="Xceed.Wpf.AvalonDock, Version=5.0.0.0, Culture=neutral, PublicKeyToken=3e4669d2f30244f4, processorArchitecture=MSIL">
<HintPath>packages\Extended.Wpf.Toolkit.5.0.0\lib\net40\Xceed.Wpf.AvalonDock.dll</HintPath>
<Reference Include="Xceed.Wpf.AvalonDock, Version=4.7.0.0, Culture=neutral, PublicKeyToken=3e4669d2f30244f4, processorArchitecture=MSIL">
<HintPath>packages\Extended.Wpf.Toolkit.4.7.25104.5739\lib\net40\Xceed.Wpf.AvalonDock.dll</HintPath>
</Reference>
<Reference Include="Xceed.Wpf.AvalonDock.Themes.Aero, Version=5.0.0.0, Culture=neutral, PublicKeyToken=3e4669d2f30244f4, processorArchitecture=MSIL">
<HintPath>packages\Extended.Wpf.Toolkit.5.0.0\lib\net40\Xceed.Wpf.AvalonDock.Themes.Aero.dll</HintPath>
<Reference Include="Xceed.Wpf.AvalonDock.Themes.Aero, Version=4.7.0.0, Culture=neutral, PublicKeyToken=3e4669d2f30244f4, processorArchitecture=MSIL">
<HintPath>packages\Extended.Wpf.Toolkit.4.7.25104.5739\lib\net40\Xceed.Wpf.AvalonDock.Themes.Aero.dll</HintPath>
</Reference>
<Reference Include="Xceed.Wpf.AvalonDock.Themes.Metro, Version=5.0.0.0, Culture=neutral, PublicKeyToken=3e4669d2f30244f4, processorArchitecture=MSIL">
<HintPath>packages\Extended.Wpf.Toolkit.5.0.0\lib\net40\Xceed.Wpf.AvalonDock.Themes.Metro.dll</HintPath>
<Reference Include="Xceed.Wpf.AvalonDock.Themes.Metro, Version=4.7.0.0, Culture=neutral, PublicKeyToken=3e4669d2f30244f4, processorArchitecture=MSIL">
<HintPath>packages\Extended.Wpf.Toolkit.4.7.25104.5739\lib\net40\Xceed.Wpf.AvalonDock.Themes.Metro.dll</HintPath>
</Reference>
<Reference Include="Xceed.Wpf.AvalonDock.Themes.VS2010, Version=5.0.0.0, Culture=neutral, PublicKeyToken=3e4669d2f30244f4, processorArchitecture=MSIL">
<HintPath>packages\Extended.Wpf.Toolkit.5.0.0\lib\net40\Xceed.Wpf.AvalonDock.Themes.VS2010.dll</HintPath>
<Reference Include="Xceed.Wpf.AvalonDock.Themes.VS2010, Version=4.7.0.0, Culture=neutral, PublicKeyToken=3e4669d2f30244f4, processorArchitecture=MSIL">
<HintPath>packages\Extended.Wpf.Toolkit.4.7.25104.5739\lib\net40\Xceed.Wpf.AvalonDock.Themes.VS2010.dll</HintPath>
</Reference>
<Reference Include="Xceed.Wpf.Toolkit, Version=5.0.0.0, Culture=neutral, PublicKeyToken=3e4669d2f30244f4, processorArchitecture=MSIL">
<HintPath>packages\Extended.Wpf.Toolkit.5.0.0\lib\net40\Xceed.Wpf.Toolkit.dll</HintPath>
<Reference Include="Xceed.Wpf.Toolkit, Version=4.7.0.0, Culture=neutral, PublicKeyToken=3e4669d2f30244f4, processorArchitecture=MSIL">
<HintPath>packages\Extended.Wpf.Toolkit.4.7.25104.5739\lib\net40\Xceed.Wpf.Toolkit.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
@ -314,9 +278,6 @@
<Compile Include="Controls\ConditionGroupControl.xaml.cs">
<DependentUpon>ConditionGroupControl.xaml</DependentUpon>
</Compile>
<Compile Include="Controls\EasyPeasyControl.xaml.cs">
<DependentUpon>EasyPeasyControl.xaml</DependentUpon>
</Compile>
<Compile Include="Controls\EditWindowBase.cs" />
<Compile Include="Controls\ENIDataGrid.cs" />
<Compile Include="Controls\IHighlightControlContainer.cs" />
@ -347,16 +308,12 @@
<Compile Include="EditControls\NewDGItemDialog.xaml.cs">
<DependentUpon>NewDGItemDialog.xaml</DependentUpon>
</Compile>
<Compile Include="EditControls\SelectCrewMemberDialog.xaml.cs">
<DependentUpon>SelectCrewMemberDialog.xaml</DependentUpon>
</Compile>
<Compile Include="EditControls\SelectPortAreaDialog.xaml.cs">
<DependentUpon>SelectPortAreaDialog.xaml</DependentUpon>
</Compile>
<Compile Include="Excel\DakosyUtil.cs" />
<Compile Include="Excel\ExcelBase.cs" />
<Compile Include="Excel\ExcelComparer.cs" />
<Compile Include="Excel\ExcelLocalImportHelper.cs" />
<Compile Include="Excel\ExcelManager.cs" />
<Compile Include="Excel\ExcelReader.cs" />
<Compile Include="Excel\ExcelSimpleWriter.cs" />
@ -579,7 +536,6 @@
<Compile Include="Util\ByteConverter.cs" />
<Compile Include="Util\CutoffConverter.cs" />
<Compile Include="Util\DatabaseEntityWatchdog.cs" />
<Compile Include="Util\EasyPeasyState.cs" />
<Compile Include="Util\EnumHelper.cs" />
<Compile Include="Util\EnumToBooleanConverter.cs" />
<Compile Include="Util\EnumToCollectionConverter.cs" />
@ -609,10 +565,6 @@
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="Controls\EasyPeasyControl.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="Controls\LocodeControl.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
@ -841,10 +793,6 @@
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="EditControls\SelectCrewMemberDialog.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="EditControls\SelectImportClassesDialog.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
@ -1073,7 +1021,6 @@
<Content Include="Report\Logo.png">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Resource Include="Resources\pencil.png" />
<Content Include="x64\SQLite.Interop.dll">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>

View File

@ -1,5 +1,5 @@
// Copyright (c) 2017 schick Informatik
// Description: Edit SERV and SERV_template entities
// Description:
//
using System.Windows;
@ -14,78 +14,36 @@ namespace ENI2.EditControls
/// </summary>
public partial class EditSERVDialog : EditWindowBase
{
#region Construction
public EditSERVDialog()
{
InitializeComponent();
Loaded += EditSERVDialog_Loaded;
}
#endregion
#region Properties
public SERV SERV { get; set; }
public SERV_Template SERV_Template { get; set; }
#endregion
#region event handler
private void EditSERVDialog_Loaded(object sender, RoutedEventArgs e)
{
this.OKClicked += EditSERVDialog_OKClicked;
// copy into fields
if (this.SERV != null)
{
this.textBoxServiceName.Text = this.SERV.ServiceName;
this.textBoxServiceBeneficiary.Text = this.SERV.ServiceBeneficiary;
this.textBoxServiceInvoiceRecipient.Text = this.SERV.ServiceInvoiceRecipient;
this.AddVisible = true;
}
if (this.SERV_Template != null)
{
this.textBoxServiceName.Text = this.SERV_Template.ServiceName;
this.textBoxServiceBeneficiary.Text = this.SERV_Template.ServiceBeneficiary;
this.textBoxServiceInvoiceRecipient.Text = this.SERV_Template.ServiceInvoiceRecipient;
}
this.textBoxServiceName.Text = this.SERV.ServiceName;
this.textBoxServiceBeneficiary.Text = this.SERV.ServiceBeneficiary;
this.textBoxServiceInvoiceRecipient.Text = this.SERV.ServiceInvoiceRecipient;
this.AddVisible = true;
}
private void EditSERVDialog_OKClicked()
{
this.CopyValuesToEntity();
}
#endregion
#region public methods
public void CopyValuesToEntity()
{
if (this.SERV != null)
{
// copy back
this.SERV.ServiceName = this.textBoxServiceName.Text.Trim();
this.SERV.ServiceBeneficiary = this.textBoxServiceBeneficiary.Text.Trim();
this.SERV.ServiceInvoiceRecipient = this.textBoxServiceInvoiceRecipient.Text.Trim();
}
if (this.SERV_Template != null)
{
// copy back
this.SERV_Template.ServiceName = this.textBoxServiceName.Text.Trim();
this.SERV_Template.ServiceBeneficiary = this.textBoxServiceBeneficiary.Text.Trim();
this.SERV_Template.ServiceInvoiceRecipient = this.textBoxServiceInvoiceRecipient.Text.Trim();
}
// copy back
this.SERV.ServiceName = this.textBoxServiceName.Text.Trim();
this.SERV.ServiceBeneficiary = this.textBoxServiceBeneficiary.Text.Trim();
this.SERV.ServiceInvoiceRecipient = this.textBoxServiceInvoiceRecipient.Text.Trim();
}
#endregion
private void EditSERVDialog_OKClicked()
{
this.CopyValuesToEntity();
}
public SERV SERV { get; set; }
}
}

View File

@ -45,7 +45,7 @@ namespace ENI2.EditControls
OKClicked += EditWasteReceiptDialog_OKClicked;
this.AddVisible = true;
_wsdpTemplates = await DBManagerAsync.GetWasteDisposalServiceProviderTemplatesAsync();
_wsdpTemplates = await DBManagerAsync.GetWastDisposalServiceProviderTemplatesAsync();
_wsdpTemplates.Sort();
Trace.WriteLine($"{_wsdpTemplates.Count} WSDP templates loaded");

View File

@ -1,32 +0,0 @@
<enictrl:EditWindowBase x:Class="ENI2.EditControls.SelectCrewMemberDialog"
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:enictrl="clr-namespace:ENI2.Controls"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ENI2.EditControls"
xmlns:p="clr-namespace:ENI2.Properties"
mc:Ignorable="d"
Title="{x:Static p:Resources.textSelectCrewMember}" Height="160" Width="400" Background="AliceBlue">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width=".5*" />
<ColumnDefinition Width=".5*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="28"/>
<RowDefinition Height="28"/>
<RowDefinition Height="28"/>
<RowDefinition Height="28"/>
</Grid.RowDefinitions>
<Label Grid.Row="0" Grid.Column="0" Content="{x:Static p:Resources.textLastName}" />
<Label Grid.Row="1" Grid.Column="0" Content="{x:Static p:Resources.textFirstName}" />
<Label Grid.Row="2" Grid.Column="0" Content="{x:Static p:Resources.textCrewFunctionOnBoard}" />
<TextBlock Text="{Binding CrewMemberLastName}" Grid.Row="0" Grid.Column="1" VerticalAlignment="Center" />
<TextBlock Text="{Binding CrewMemberFirstName}" Grid.Row="1" Grid.Column="1" VerticalAlignment="Center" />
<TextBlock Text="{Binding CrewMemberDuty}" Grid.Row="2" Grid.Column="1" VerticalAlignment="Center" />
</Grid>
</enictrl:EditWindowBase>

View File

@ -1,41 +0,0 @@
// Copyright (c) 2017- schick Informatik
// Description:
//
using bsmd.database;
using ENI2.Controls;
using System.Windows;
namespace ENI2.EditControls
{
/// <summary>
/// Interaction logic for SelectCrewMemberDialog.xaml
/// </summary>
public partial class SelectCrewMemberDialog : EditWindowBase
{
public SelectCrewMemberDialog()
{
InitializeComponent();
Loaded += SelectCrewMemberDialog_Loaded;
}
#region Properties
public CREW CREW { get; set; }
#endregion
#region event handler
private void SelectCrewMemberDialog_Loaded(object sender, RoutedEventArgs e)
{
if (CREW != null)
{
this.DataContext = CREW;
}
}
#endregion
}
}

View File

@ -8,7 +8,7 @@
xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
xmlns:p="clr-namespace:ENI2.Properties"
mc:Ignorable="d"
Title="{x:Static p:Resources.textSelectImportClasses}" Height="660" Width="250" Background="AliceBlue">
Title="{x:Static p:Resources.textSelectImportClasses}" Height="600" Width="250" Background="AliceBlue">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="1*" />

View File

@ -1,13 +1,14 @@
// Copyright (c) 2017-today schick Informatik
// Description: Select classes for import via Excel or for sending them once completed
// Description: Select classes for import
// Returns: Array of selected classes as property
using bsmd.database;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;
using bsmd.database;
namespace ENI2.EditControls
{
/// <summary>
@ -16,8 +17,7 @@ namespace ENI2.EditControls
public partial class SelectImportClassesDialog : ENI2.Controls.EditWindowBase
{
private readonly List<SelectClass> _selectClasses = new List<SelectClass>();
private readonly List<Message.NotificationClass> _selectedClasses = new List<Message.NotificationClass>();
private readonly List<Message.NotificationClass> _preselectedClasses = new List<Message.NotificationClass>();
private readonly List<bsmd.database.Message.NotificationClass> _selectedClasses = new List<Message.NotificationClass>();
public SelectImportClassesDialog()
{
@ -25,61 +25,33 @@ namespace ENI2.EditControls
this.Loaded += SelectImportClassesDialog_Loaded;
}
/// <summary>
/// List of all message classes that are available for selection
/// </summary>
public List<Message.NotificationClass> SelectedClasses
{
get { return _selectedClasses; }
}
/// <summary>
/// Classes that should be checked already when the dialog is opened (relevant for send mode)
/// </summary>
public List<Message.NotificationClass > PreselectedClasses
{
get { return _preselectedClasses; }
}
/// <summary>
/// These messages are needed to derive message classes from, already sorted in the right manner
/// </summary>
public List<Message> Messages { get; set; }
/// <summary>
/// Flag to reduce selection amount in case of transit
/// </summary>
public bool IsTransit { get; set; }
/// <summary>
/// Flag if dialog is used in import mode (default true). Set false for send all mode.
/// </summary>
public bool IsImportMode { get; set; } = true;
private void SelectImportClassesDialog_Loaded(object sender, RoutedEventArgs e)
{
foreach (Message aMessage in this.Messages)
foreach(Message aMessage in this.Messages)
{
// these are of no interest
if ((aMessage.MessageNotificationClass == Message.NotificationClass.VISIT) ||
(aMessage.MessageNotificationClass == Message.NotificationClass.TRANSIT) ||
(aMessage.MessageNotificationClass == Message.NotificationClass.STO))
continue;
// these are neither imported nor sent by the Send all function
if ((aMessage.MessageNotificationClass == Message.NotificationClass.ATA) ||
(aMessage.MessageNotificationClass == Message.NotificationClass.ATD))
continue;
// filter out messages not relevant for transit
if (IsTransit && (
(aMessage.MessageNotificationClass == Message.NotificationClass.ATA) ||
(aMessage.MessageNotificationClass == Message.NotificationClass.ATD) ||
(aMessage.MessageNotificationClass == Message.NotificationClass.BKRD) ||
(aMessage.MessageNotificationClass == Message.NotificationClass.STO)
) continue;
if (IsTransit &&
((aMessage.MessageNotificationClass == Message.NotificationClass.BKRD) ||
(aMessage.MessageNotificationClass == Message.NotificationClass.BPOL) ||
(aMessage.MessageNotificationClass == Message.NotificationClass.HAZD) ||
(aMessage.MessageNotificationClass == Message.NotificationClass.INFO) ||
(aMessage.MessageNotificationClass == Message.NotificationClass.LADG) ||
@ -90,16 +62,15 @@ namespace ENI2.EditControls
(aMessage.MessageNotificationClass == Message.NotificationClass.TOWD) ||
(aMessage.MessageNotificationClass == Message.NotificationClass.WAS) ||
(aMessage.MessageNotificationClass == Message.NotificationClass.WAS_RCPT)
)) continue;
)) continue;
SelectClass sc = new SelectClass();
sc.Name = Enum.GetName(typeof(Message.NotificationClass), aMessage.MessageNotificationClass);
sc.Name = Enum.GetName(typeof(bsmd.database.Message.NotificationClass), aMessage.MessageNotificationClass);
sc.Class = aMessage.MessageNotificationClass;
sc.IsSelected = this._preselectedClasses.Contains(sc.Class);
sc.IsSelected = false;
_selectClasses.Add(sc);
}
this.checkListBoxClasses.ItemsSource = _selectClasses;
this.OKClicked += SelectImportClassesDialog_OKClicked;
}
@ -126,7 +97,7 @@ namespace ENI2.EditControls
OnPropertyChanged("IsSelected");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{

View File

@ -1,15 +1,13 @@
// Copyright (c) 2017-today Informatikbüro Daniel Schick
// Base class excel access (named ranges, colorizing, etc.)
// Base class excel (writer not yet implemented but eventually..)
using System;
using System.Collections.Generic;
using ClosedXML.Excel;
using Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
using log4net;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Drawing;
using System.Linq;
using System.IO;
namespace ENI2.Excel
{
@ -22,9 +20,10 @@ namespace ENI2.Excel
protected CountryMode _countryMode = CountryMode.DE;
protected XLWorkbook _workBook;
protected FileStream _workBookStream;
protected Dictionary<string, IXLDefinedName> _nameDict;
protected Workbooks _excelWorkbooks;
protected Workbook _workBook;
protected Application _excelApp;
protected Dictionary<string, Name> _nameDict;
protected ILog _log;
#endregion Fields
@ -33,7 +32,12 @@ namespace ENI2.Excel
public ExcelBase()
{
_log = LogManager.GetLogger(this.GetType().Name);
this._excelApp = new Application();
this._excelApp.DisplayAlerts = false;
this._excelWorkbooks = _excelApp.Workbooks;
}
#endregion Construction
@ -42,9 +46,9 @@ namespace ENI2.Excel
internal CountryMode Mode { get { return _countryMode; } }
internal Dictionary<string, IXLDefinedName> NameDict { get { return _nameDict; } }
internal Dictionary<string, Name> NameDict { get { return _nameDict; } }
internal IXLWorksheets Worksheets { get { return _workBook?.Worksheets; } }
internal Sheets Worksheets { get { return _workBook.Worksheets; } }
#endregion
@ -52,17 +56,17 @@ namespace ENI2.Excel
protected void InitNameFields()
{
_nameDict = new Dictionary<string, IXLDefinedName>();
_nameDict = new Dictionary<string, Name>();
int bookCnt = 0;
// Get workbook-level defined names
foreach (var definedName in _workBook.DefinedNames)
foreach (Name name in _workBook.Names)
{
string nameKey = definedName.Name;
string theValue = name.Value;
// Namensbezug: =SheetZelle. Leere Referenzen überspringen (kommt immer mal wieder vor!)
string nameKey = name.Name;
try
{
// Handle sheet-scoped names (Sheet1!Name format)
if (nameKey.Contains("!"))
nameKey = nameKey.Substring(nameKey.IndexOf('!') + 1);
}
@ -72,43 +76,36 @@ namespace ENI2.Excel
continue;
}
// Check if the defined name is valid (not a broken reference)
if (definedName.IsValid)
if ((theValue != "=#REF!#REF!") && (theValue != "=#BEZUG!#BEZUG!"))
{
_nameDict[nameKey] = definedName;
_nameDict[nameKey] = name;
bookCnt++;
}
}
_log.DebugFormat("{0} defined names found at Workbook level", bookCnt);
_log.DebugFormat("{0} named ranges found at Workbook level", bookCnt);
// Get worksheet-level defined names
foreach (var ws in _workBook.Worksheets)
foreach (Worksheet ws in _workBook.Worksheets)
{
int wsCnt = 0;
foreach (var definedName in ws.DefinedNames)
foreach (Name name in ws.Names)
{
string nameKey = definedName.Name;
if (!_nameDict.ContainsKey(nameKey))
string theValue = name.Value;
// Namensbezug: =SheetZelle. Leere Referenzen überspringen (kommt immer mal wieder vor!)
if (!_nameDict.ContainsKey(name.Name))
{
if (definedName.IsValid)
if ((theValue != "=#REF!#REF!") && (theValue != "=#BEZUG!#BEZUG!"))
{
_nameDict[nameKey] = definedName;
_nameDict[name.Name] = name;
wsCnt++;
}
}
}
if (wsCnt > 0)
_log.DebugFormat("{0} defined names found in Worksheet {1}", wsCnt, ws.Name);
_log.DebugFormat("{0} named ranges found in Worksheet {1}", wsCnt, ws.Name);
}
}
protected void OpenWorkbookReadOnly(string path)
{
_workBookStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
_workBook = new XLWorkbook(_workBookStream);
}
private static double? ParseAnyDouble(string val)
{
double? result = null;
@ -130,40 +127,27 @@ namespace ENI2.Excel
{
if (_nameDict.ContainsKey(lookup))
{
var definedName = _nameDict[lookup];
var ranges = definedName.Ranges;
var range = ranges.FirstOrDefault();
if (range != null)
var val = _nameDict[lookup].RefersToRange.Value;
if (val is double) result = val;
if ((val is string) && (val.Length > 0))
{
var cell = range.FirstCell();
if (cell != null)
{
var cellValue = cell.Value;
result = ParseAnyDouble(val);
if (cellValue.IsNumber)
if(result == null)
{
Match m = Regex.Match(val, "([0-9\\.\\,]+)([a-zA-Z]*)");
if (m.Success)
{
result = cellValue.GetNumber();
}
else if (cellValue.IsText)
{
string textVal = cellValue.GetText();
if (!string.IsNullOrEmpty(textVal))
{
result = ParseAnyDouble(textVal);
if (result == null)
{
Match m = Regex.Match(textVal, "([0-9\\.\\,]+)([a-zA-Z]*)");
if (m.Success)
{
result = ParseAnyDouble(m.Groups[1].Value);
}
}
}
}
result = ParseAnyDouble(m.Groups[1].Value);
}
}
}
if ((result == null) && (val != null))
{
double tmpDouble2 = val[1, 1];
result = tmpDouble2;
}
}
}
catch (Exception)
@ -175,26 +159,17 @@ namespace ENI2.Excel
internal void Colorize(string lookup, int color)
{
if (_nameDict.ContainsKey(lookup))
if(_nameDict.ContainsKey(lookup))
{
var definedName = _nameDict[lookup];
var ranges = definedName.Ranges;
var range = ranges.FirstOrDefault();
if (range != null)
{
Colorize(range, color);
}
var range = _nameDict[lookup].RefersToRange;
Colorize(range, color);
}
}
internal void Colorize(IXLRange range, int color)
internal void Colorize(Range range, int color)
{
// Convert int color to Color object
Color backgroundColor = Color.FromArgb(color);
range.Style.Fill.BackgroundColor = XLColor.FromColor(backgroundColor);
// Set worksheet tab color
range.Worksheet.SetTabColor(XLColor.FromColor(backgroundColor));
range.Interior.Color = color;
range.Worksheet.Tab.Color = color;
}
#endregion
@ -203,7 +178,9 @@ namespace ENI2.Excel
public void Save(string path)
{
_workBook.SaveAs(path);
this._workBook.SaveAs(path, XlFileFormat.xlOpenXMLWorkbook, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
this._workBook.Saved = true;
}
#endregion
@ -214,21 +191,29 @@ namespace ENI2.Excel
{
try
{
if (_workBook != null)
if (this._workBook != null)
{
_log.Debug("Disposing Workbook");
_workBook.Dispose();
_workBook = null;
this._workBook.Close(0);
_log.Debug("Close Worksheet");
Marshal.ReleaseComObject(this._workBook);
}
if (_workBookStream != null)
if (this._excelWorkbooks != null)
{
_workBookStream.Dispose();
_workBookStream = null;
this._excelWorkbooks.Close();
_log.Debug("Close Workbooks");
Marshal.ReleaseComObject(this._excelWorkbooks);
}
if (this._excelApp != null)
{
_log.Debug("Quit Excel");
this._excelApp.Quit();
Marshal.ReleaseComObject(this._excelApp);
}
}
catch (Exception ex)
catch(Exception ex)
{
_log.ErrorFormat("Exception disposing ExcelBase: {0}", ex.Message);
_log.ErrorFormat("Exception disposing ExcelReader: {0}", ex.Message);
}
}

View File

@ -4,7 +4,8 @@
using System;
using System.IO;
using ClosedXML.Excel;
using System.Drawing;
using Microsoft.Office.Interop.Excel;
namespace ENI2.Excel
{
@ -16,142 +17,173 @@ namespace ENI2.Excel
/// </summary>
public static class ExcelComparer
{
private static readonly XLColor diffColor = XLColor.FromArgb(150, 150, 255); // blue
private static readonly int diffColor = ColorTranslator.ToOle(Color.FromArgb(150, 150, 255)); // blue
private static bool GetSheetRange(IXLWorksheet sheet, out int lastUsedRow, out int lastUsedColumn)
private static bool GetSheetRange(Worksheet sheet, out int lastUsedRow, out int lastUsedColumn)
{
try
{
var usedRange = sheet.RangeUsed();
if (usedRange != null)
{
lastUsedRow = usedRange.RowCount();
lastUsedColumn = usedRange.ColumnCount();
return true;
}
else
{
lastUsedColumn = 0;
lastUsedRow = 0;
return false;
}
// sheet.Columns.ClearFormats();
// sheet.Rows.ClearFormats();
Range usedRange = sheet.UsedRange;
lastUsedRow = usedRange.Rows.Count;
lastUsedColumn = usedRange.Columns.Count;
/*
Range last = sheet.Cells.SpecialCells(XlCellType.xlCellTypeLastCell, Type.Missing);
Range range = sheet.get_Range("A1", last);
lastUsedRow = last.Row;
lastUsedColumn = last.Column;
*/
return true;
}
catch (Exception)
catch(Exception)
{
lastUsedColumn = 0;
lastUsedRow = 0;
return false;
}
}
}
private static string GetExcelColumnName(int columnNumber)
{
string columnName = "";
while (columnNumber > 0)
{
int modulo = (columnNumber - 1) % 26;
columnName = Convert.ToChar('A' + modulo) + columnName;
columnNumber = (columnNumber - modulo) / 26;
}
return columnName;
}
public static string Compare(string sourcePath, string targetPath, string comparisonFileName, out string errorMessage)
{
{
errorMessage = "";
int counter = 0;
try
{
File.Copy(targetPath, comparisonFileName, true);
File.Copy(targetPath, comparisonFileName);
ExcelReader source = new ExcelReader(sourcePath, true, false);
ExcelReader comparison = new ExcelReader(comparisonFileName, false, false);
using (var sourceStream = new FileStream(sourcePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var sourceWorkbook = new XLWorkbook(sourceStream))
using (var comparisonWorkbook = new XLWorkbook(comparisonFileName))
/* erste Variante Vergleich über Namen der Zellen
// loop through named cells
foreach (string name in comparison.NameDict.Keys)
{
// Es werden Zellen der "used range" miteinander verglichen
foreach (var sourceSheet in sourceWorkbook.Worksheets)
if (!source.NameDict.ContainsKey(name)) continue;
string sourceText = source.ReadText(name);
string targetText = comparison.ReadText(name);
if (sourceText == null)
{
IXLWorksheet targetSheet = null;
foreach (var sheet in comparisonWorkbook.Worksheets)
if (targetText != null)
{
if (sourceSheet.Name.Equals(sheet.Name))
{
targetSheet = sheet;
break;
}
comparison.Colorize(name, diffColor);
counter++;
}
if (targetSheet == null) continue;
System.Diagnostics.Trace.WriteLine(string.Format("Processing sheet {0}", targetSheet.Name));
if (GetSheetRange(sourceSheet, out int sourceRows, out int sourceCols) && GetSheetRange(targetSheet, out int targetRows, out int targetCols))
}
else if (targetText == null)
{
if (sourceText != null)
{
int maxRows = Math.Max(sourceRows, targetRows);
int maxCols = Math.Max(sourceCols, targetCols);
bool sheetHasDiffs = false;
for (int rowidx = 1; rowidx <= maxRows; rowidx++)
{
for (int colidx = 1; colidx <= maxCols; colidx++)
{
string sourceText = null;
string targetText = null;
// Get source cell value
if (rowidx <= sourceRows && colidx <= sourceCols)
{
var sourceCell = sourceSheet.Cell(rowidx, colidx);
if (!sourceCell.IsEmpty())
{
sourceText = sourceCell.GetString();
}
}
// Get target cell value
if (rowidx <= targetRows && colidx <= targetCols)
{
var targetCell = targetSheet.Cell(rowidx, colidx);
if (!targetCell.IsEmpty())
{
targetText = targetCell.GetString();
}
}
if (sourceText == null)
{
if (targetText != null)
{
var cellToHighlight = targetSheet.Cell(rowidx, colidx);
cellToHighlight.Style.Fill.BackgroundColor = diffColor;
counter++;
sheetHasDiffs = true;
}
}
else if (targetText == null)
{
if (sourceText != null)
{
var cellToHighlight = targetSheet.Cell(rowidx, colidx);
cellToHighlight.Style.Fill.BackgroundColor = diffColor;
counter++;
sheetHasDiffs = true;
}
}
else if ((sourceText != null) && (targetText != null))
{
if (!sourceText.Equals(targetText))
{
var cellToHighlight = targetSheet.Cell(rowidx, colidx);
cellToHighlight.Style.Fill.BackgroundColor = diffColor;
counter++;
sheetHasDiffs = true;
}
}
}
}
if (sheetHasDiffs)
{
targetSheet.SetTabColor(diffColor);
}
comparison.Colorize(name, diffColor);
counter++;
}
else
}
else if ((sourceText != null) && (targetText != null))
{
if (!sourceText.Equals(targetText))
{
errorMessage = "failed to get sheet ranges";
// turn cell blue
comparison.Colorize(name, diffColor);
counter++;
}
}
}
*/
// Zweite Version durch alle Sheets werden Zellen der "used range" miteinander verglichen
foreach(Worksheet sourceSheet in source.Worksheets)
{
Worksheet targetSheet = null;
foreach(Worksheet sheet in comparison.Worksheets)
{
if (sourceSheet.Name.Equals(sheet.Name))
{
targetSheet = sheet;
break;
}
}
comparisonWorkbook.SaveAs(comparisonFileName);
if (targetSheet == null) continue;
System.Diagnostics.Trace.WriteLine(string.Format("Processing sheet {0}", targetSheet.Name));
if(GetSheetRange(sourceSheet, out int sourceRows, out int sourceCols) && GetSheetRange(targetSheet, out int targetRows, out int targetCols))
{
// read source into 2 dim array
string rangeString = string.Format("A1:{0}{1}", GetExcelColumnName(Math.Max(sourceCols, targetCols)), Math.Max(sourceRows, targetRows));
object[,] sourceArray = sourceSheet.get_Range(rangeString).Value;
// read target into 2 dim array
object[,] targetArray = targetSheet.get_Range(rangeString).Value;
for (int rowidx = 1; rowidx <= Math.Max(sourceRows, targetRows); rowidx++)
{
for( int colidx = 1; colidx <= Math.Max(sourceCols, targetCols); colidx++)
{
string sourceText = null;
if(sourceArray[rowidx,colidx] != null) sourceText = sourceArray[rowidx,colidx].ToString();
string targetText = null;
if(targetArray[rowidx,colidx] != null) targetText = targetArray[rowidx, colidx].ToString();
if (sourceText == null)
{
if (targetText != null)
{
string targetRangeName = string.Format("{0}{1}", GetExcelColumnName(colidx), rowidx);
comparison.Colorize(targetSheet.Range[targetRangeName], diffColor);
counter++;
}
}
else if (targetText == null)
{
if (sourceText != null)
{
string targetRangeName = string.Format("{0}{1}", GetExcelColumnName(colidx), rowidx);
comparison.Colorize(targetSheet.Range[targetRangeName], diffColor);
counter++;
}
}
else if ((sourceText != null) && (targetText != null))
{
if (!sourceText.Equals(targetText))
{
string targetRangeName = string.Format("{0}{1}", GetExcelColumnName(colidx), rowidx);
// turn cell blue
comparison.Colorize(targetSheet.Range[targetRangeName], diffColor);
counter++;
}
}
}
}
}
else
{
errorMessage = "failed to get sheet ranges";
}
}
comparison.Save(comparisonFileName);
source.Dispose();
comparison.Dispose();
errorMessage = string.Format("{0} differences found", counter);
}
catch (Exception ex)
@ -161,5 +193,6 @@ namespace ENI2.Excel
return comparisonFileName;
}
}
}

View File

@ -1,333 +0,0 @@
using bsmd.database;
using ClosedXML.Excel;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
namespace ENI2.Excel
{
internal static class ExcelLocalImportHelper
{
#region Last 10 Port Facilities Called Import from Excel
public static int ImportLast10PortFacilities(SEC sec)
{
int cnt = 0;
OpenFileDialog ofd = new OpenFileDialog
{
Filter = "Excel Files|*.xls;*.xlsx"
};
if (ofd.ShowDialog() ?? false)
{
try
{
using (var stream = new FileStream(ofd.FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var workbook = new XLWorkbook(stream))
{
var worksheet = workbook.Worksheet(1);
var rows = worksheet.RangeUsed().RowsUsed();
int columnCount = worksheet.RangeUsed().ColumnCount();
// Check minimum columns upfront
if (columnCount < 8)
{
throw new InvalidDataException("Sheet must have at least 8 Columns of data");
}
List<LastTenPortFacilitiesCalled> importL10C = new List<LastTenPortFacilitiesCalled>();
foreach (var row in rows)
{
if (cnt >= 10) break; // Maximum 10 rows
// Skip empty rows
if (row.Cell(1).IsEmpty() && row.Cell(2).IsEmpty()) continue;
LastTenPortFacilitiesCalled l10c = new LastTenPortFacilitiesCalled();
try
{
// Column 1: Port Name
if (!row.Cell(1).IsEmpty())
l10c.PortFacilityPortName = row.Cell(1).GetString();
// Column 3: Country
if (!row.Cell(3).IsEmpty())
l10c.PortFacilityPortCountry = row.Cell(3).GetString();
// Column 4: Locode
if (!row.Cell(4).IsEmpty())
l10c.PortFacilityPortLoCode = row.Cell(4).GetString();
// Column 5: Arrival Date
if (!row.Cell(5).IsEmpty())
{
l10c.PortFacilityDateOfArrival = row.Cell(5).GetDateTime();
}
// Column 6: Departure Date
if (!row.Cell(6).IsEmpty())
{
l10c.PortFacilityDateOfDeparture = row.Cell(6).GetDateTime();
}
// Column 7: Security Level (byte)
if (!row.Cell(7).IsEmpty())
{
l10c.PortFacilityShipSecurityLevel = row.Cell(7).GetValue<byte>();
}
// Column 8: GISIS Code
if (!row.Cell(8).IsEmpty())
{
int gisis = row.Cell(8).GetValue<int>();
l10c.PortFacilityGISISCode = gisis.ToString().PadLeft(4, '0');
}
// Column 9: Security Matters (optional, can be beyond minimum columns)
if (columnCount >= 9 && !row.Cell(9).IsEmpty())
{
l10c.PortFacilitySecurityMattersToReport = row.Cell(9).GetString();
if (l10c.PortFacilitySecurityMattersToReport?.Equals("nil", StringComparison.OrdinalIgnoreCase) == true)
l10c.PortFacilitySecurityMattersToReport = null;
}
// Column 10: GISIS Code Locode (optional, can be beyond minimum columns)
if (columnCount >= 10 && !row.Cell(10).IsEmpty())
{
l10c.PortFacilityGISISCodeLocode = row.Cell(10).GetString();
}
l10c.SEC = sec;
l10c.IsDirty = true;
l10c.Identifier = LastTenPortFacilitiesCalled.GetNewIdentifier(sec.LastTenPortFacilitesCalled);
sec.LastTenPortFacilitesCalled.Add(l10c);
importL10C.Add(l10c);
cnt++;
}
catch (Exception ex)
{
throw new InvalidDataException($"Error processing row {row.RowNumber()}: {ex.Message}", ex);
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error reading Excel: " + ex.Message, Properties.Resources.textCaptionError,
MessageBoxButton.OK, MessageBoxImage.Error);
}
}
return cnt;
}
#endregion
#region Last 30 days Import from Excel
public static int ImportLast30Days(MDH mdh)
{
int cnt = 0;
OpenFileDialog ofd = new OpenFileDialog
{
Filter = "Excel Files|*.xls;*.xlsx"
};
if (ofd.ShowDialog() ?? false)
{
try
{
using (var stream = new FileStream(ofd.FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var workbook = new XLWorkbook(stream))
{
var worksheet = workbook.Worksheet(1);
var rows = worksheet.RangeUsed().RowsUsed();
int columnCount = worksheet.RangeUsed().ColumnCount();
List<PortOfCallLast30Days> importPoC30 = new List<PortOfCallLast30Days>();
foreach (var row in rows)
{
if (row.RowNumber() > worksheet.RangeUsed().RowCount()) break;
if (columnCount < 3)
{
throw new InvalidDataException("Sheet must have at least 3 Columns of data");
}
PortOfCallLast30Days poc30 = new PortOfCallLast30Days();
if (row.Cell(1).IsEmpty() && row.Cell(2).IsEmpty()) continue;
// Safer locode extraction
if (!row.Cell(1).IsEmpty())
{
try
{
poc30.PortOfCallLast30DaysLocode = row.Cell(1).GetString();
}
catch (Exception ex)
{
throw new InvalidDataException($"Invalid locode in row {row.RowNumber()}: {ex.Message}");
}
}
// Safer date extraction
if (!row.Cell(2).IsEmpty())
{
try
{
poc30.PortOfCallLast30DaysDateOfDeparture = row.Cell(2).GetDateTime();
}
catch (Exception ex)
{
throw new InvalidDataException($"Invalid date in row {row.RowNumber()}: {ex.Message}");
}
}
// Safer boolean extraction
string boolString = "";
if (!row.Cell(3).IsEmpty())
{
boolString = row.Cell(3).GetString()?.Trim() ?? "";
}
poc30.PortOfCallLast30DaysCrewMembersJoined = (
boolString.Equals("y", StringComparison.OrdinalIgnoreCase) ||
boolString.Equals("yes", StringComparison.OrdinalIgnoreCase) ||
boolString.Equals("j", StringComparison.OrdinalIgnoreCase));
// FIX: Check column count before accessing column 4
if (columnCount >= 4)
{
string allNewCrew = row.Cell(4).IsEmpty() ? null : row.Cell(4).GetString()?.Trim();
if (!allNewCrew.IsNullOrEmpty())
{
string[] crewNames = allNewCrew.Split(',', ';');
foreach (string crewName in crewNames)
{
string trimmedName = crewName.Trim();
if (trimmedName.IsNullOrEmpty()) continue;
PortOfCallLast30DaysCrewJoinedShip poc30Crew = new PortOfCallLast30DaysCrewJoinedShip
{
PortOfCallLast30DaysCrewJoinedShipName = trimmedName,
PortOfCallLast30Days = poc30
};
poc30.CrewJoinedShip.Add(poc30Crew);
}
}
}
poc30.MDH = mdh;
mdh.PortOfCallLast30Days.Add(poc30);
importPoC30.Add(poc30);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error reading Excel: " + ex.Message, Properties.Resources.textCaptionError,
MessageBoxButton.OK, MessageBoxImage.Error);
}
}
return cnt;
}
#endregion
#region Waste from Excel
public static int ImportWaste(WAS was)
{
int cnt = 0;
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Excel Files|*.xls;*.xlsx";
if (ofd.ShowDialog() ?? false)
{
try
{
using (var stream = new FileStream(ofd.FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var workbook = new XLWorkbook(stream))
{
var worksheet = workbook.Worksheet(1); // Get first worksheet
var rows = worksheet.RangeUsed().RowsUsed().Skip(3); // Skip first three rows
List<Waste> importWasteList = new List<Waste>();
object o = null;
// Diese Funktion kann das "alte" Sheet Format nicht mehr einlesen!
foreach (var row in rows)
{
if (cnt >= 35) break; // Maximum 35 rows
if (worksheet.RangeUsed().ColumnCount() < 9)
{
throw new InvalidDataException("Sheet must have 9 Columns of data");
}
if (!row.Cell(2).IsEmpty()) o = row.Cell(2).Value; else o = null;
if ((o != null) && Int32.TryParse(o.ToString(), out int wasteType))
{
Waste waste = was.GetWasteForType(wasteType);
if (waste == null)
{
waste = new Waste();
waste.WasteType = wasteType;
waste.WAS = was;
waste.IsDirty = true;
waste.Identifier = Waste.GetNewIdentifier(was.Waste);
was.Waste.Add(waste);
}
else
{
waste.IsDirty = true;
}
if (!row.Cell(5).IsEmpty()) waste.WasteDescription = row.Cell(5).GetString();
if (waste.WasteDescription.IsNullOrEmpty())
waste.WasteDescription = "-";
if (!row.Cell(6).IsEmpty())
waste.WasteDisposalAmount_MTQ = row.Cell(6).GetDouble();
if (!row.Cell(7).IsEmpty())
waste.WasteCapacity_MTQ = row.Cell(7).GetDouble();
if (!row.Cell(8).IsEmpty()) waste.WasteAmountRetained_MTQ = row.Cell(8).GetDouble();
if (!row.Cell(9).IsEmpty())
waste.WasteDisposalPort = row.Cell(9).GetString().ToUpper();
if (!row.Cell(10).IsEmpty())
waste.WasteAmountGeneratedTillNextPort_MTQ = row.Cell(10).GetDouble();
importWasteList.Add(waste);
cnt++;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error reading Excel: " + ex.Message, Properties.Resources.textCaptionError, MessageBoxButton.OK, MessageBoxImage.Error);
}
}
return cnt;
}
#endregion
}
}

View File

@ -9,12 +9,13 @@
using bsmd.database;
using ENI2.Locode;
using ClosedXML.Excel;
using Microsoft.Office.Interop.Excel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Runtime.InteropServices;
namespace ENI2.Excel
{
@ -30,9 +31,9 @@ namespace ENI2.Excel
internal Dictionary<string, string> ImportValues { get; } = new Dictionary<string, string>();
public ExcelReader(string filePath, bool createNameFields = true)
public ExcelReader(string filePath, bool openReadonly = true, bool createNameFields = true)
{
this.OpenWorkbookReadOnly(filePath);
this._workBook = _excelWorkbooks.Open(filePath, 0, openReadonly, 5, "", "", false, XlPlatform.xlWindows, "", false, false, 0, false, false, false);
if (createNameFields)
this.InitNameFields();
@ -68,20 +69,16 @@ namespace ENI2.Excel
{
try
{
var definedName = _nameDict[lookup];
var range = definedName.Ranges.FirstOrDefault();
if (range != null)
{
var cell = range.FirstCell();
if (cell != null && !cell.Value.IsBlank)
{
result = cell.Value.ToString().Trim();
}
}
var val = _nameDict[lookup].RefersToRange.Value;
var val2 = _nameDict[lookup].RefersToRange.Value2;
if (val != null)
result = val.ToString().Trim();
else if (val2 != null)
result = val2.ToString().Trim();
}
catch (Exception ex)
catch (COMException ex)
{
_log.WarnFormat("Exception reading field {0}: {1}", lookup, ex.Message);
_log.WarnFormat("COMException reading field {0}: {1}", lookup, ex.ErrorCode);
}
}
if (result != null)
@ -131,7 +128,7 @@ namespace ENI2.Excel
if (portName.IsNullOrEmpty())
{
_log.WarnFormat("unknown Locode {0}", val);
val = null;
val = "";
}
}
return val;
@ -286,7 +283,7 @@ namespace ENI2.Excel
}
}
return val;
}
}
internal byte? ReadHullConfiguration(string lookup)
{
@ -444,61 +441,47 @@ namespace ENI2.Excel
if (_nameDict.ContainsKey(lookup))
{
var definedName = _nameDict[lookup];
var range = definedName.Ranges.FirstOrDefault();
if (range != null)
var val = _nameDict[lookup].RefersToRange.Value;
if (val is DateTime)
{
var cell = range.FirstCell();
if (cell != null && !cell.Value.IsBlank)
date = val;
}
else if (val is double)
{
try
{
var cellValue = cell.Value;
if (cellValue.IsDateTime)
{
date = cellValue.GetDateTime();
}
else if (cellValue.IsNumber)
{
double numValue = 0;
try
{
numValue = cellValue.GetNumber();
date = DateTime.FromOADate(numValue);
}
catch (ArgumentException) { /* .. */ }
if (date == null)
{
CultureInfo provider = CultureInfo.InvariantCulture;
string dateString = numValue.ToString();
const string format = "yyyyMMdd";
if (DateTime.TryParseExact(dateString, format, provider, DateTimeStyles.None, out DateTime tmpDate))
date = tmpDate;
}
}
else if (cellValue.IsText)
{
string textValue = cellValue.GetText();
if (DateTime.TryParse(textValue, out DateTime tmpDate))
date = tmpDate;
if (date == null)
{
string[] formats = { "d/M/yyyy", "dd/M/yyyy", "d/MM/yyyy", "dd/MM/yyyy", "d/MMM/yyyy", "dd/MMM/yyyy", "yyyy-MM-dd", "yyyy-mm-d", "dd-MM-yyyy" };
if (DateTime.TryParseExact(textValue, formats, NumberFormatInfo.InvariantInfo, DateTimeStyles.None, out DateTime tmpDate2))
date = tmpDate2;
}
if (date == null)
{
CultureInfo en = CultureInfo.CreateSpecificCulture("en-US");
string[] formats = { "d/M/yyyy", "dd/M/yyyy", "d/MM/yyyy", "dd/MM/yyyy", "d/MMM/yyyy", "dd/MMM/yyyy", "yyyy-MM-dd", "yyyy-mm-d", "dd-MM-yyyy" };
if (DateTime.TryParseExact(textValue, formats, en, DateTimeStyles.None, out DateTime tmpDate3))
date = tmpDate3;
}
}
date = DateTime.FromOADate(val);
}
catch (ArgumentException) { /* .. */ }
if (date == null)
{
CultureInfo provider = CultureInfo.InvariantCulture;
string dateString = val.ToString();
const string format = "yyyyMMdd";
if (DateTime.TryParseExact(dateString, format, provider, DateTimeStyles.None, out DateTime tmpDate))
date = tmpDate;
}
}
if (date == null)
{
if (DateTime.TryParse(val, out DateTime tmpDate))
date = tmpDate;
}
if (date == null)
{
string[] formats = { "d/M/yyyy", "dd/M/yyyy", "d/MM/yyyy", "dd/MM/yyyy", "d/MMM/yyyy", "dd/MMM/yyyy", "yyyy-MM-dd", "yyyy-mm-d", "dd-MM-yyyy" };
if (DateTime.TryParseExact(val, formats, NumberFormatInfo.InvariantInfo, DateTimeStyles.None, out DateTime tmpDate))
date = tmpDate;
}
if (date == null)
{
CultureInfo en = CultureInfo.CreateSpecificCulture("en-US");
string[] formats = { "d/M/yyyy", "dd/M/yyyy", "d/MM/yyyy", "dd/MM/yyyy", "d/MMM/yyyy", "dd/MMM/yyyy", "yyyy-MM-dd", "yyyy-mm-d", "dd-MM-yyyy" };
if (DateTime.TryParseExact(val, formats, en, DateTimeStyles.None, out DateTime tmpDate))
return tmpDate;
}
if (date != null)
@ -549,72 +532,61 @@ namespace ENI2.Excel
{
if (_nameDict.ContainsKey(lookup))
{
var definedName = _nameDict[lookup];
var range = definedName.Ranges.FirstOrDefault();
if (range != null)
var val = _nameDict[lookup].RefersToRange.Value;
if (val is DateTime)
{
var cell = range.FirstCell();
if (cell != null && !cell.Value.IsBlank)
result = val;
}
if (val is double)
{
try
{
var cellValue = cell.Value;
result = DateTime.FromOADate(val);
}
catch (ArgumentException) { }
if (cellValue.IsDateTime)
if (result == null)
{
CultureInfo provider = CultureInfo.InvariantCulture;
string dateString = val.ToString();
if (!dateString.Contains(":"))
{
result = cellValue.GetDateTime();
const string format = "HHmm";
if (DateTime.TryParseExact(dateString, format, provider, DateTimeStyles.None, out DateTime tmpDate))
result = tmpDate;
}
else if (cellValue.IsTimeSpan)
{
TimeSpan timespan = cellValue.GetTimeSpan();
result = new DateTime(timespan.Ticks);
}
else if (cellValue.IsNumber)
{
double numValue = 0;
try
{
numValue = cellValue.GetNumber();
result = DateTime.FromOADate(numValue);
}
catch (ArgumentException) { }
}
}
if (result == null)
{
CultureInfo provider = CultureInfo.InvariantCulture;
string dateString = numValue.ToString();
if (!dateString.Contains(":"))
{
const string format = "HHmm";
if (DateTime.TryParseExact(dateString, format, provider, DateTimeStyles.None, out DateTime tmpDate))
result = tmpDate;
}
}
}
else if (cellValue.IsText)
{
string textValue = cellValue.GetText();
if (val is string @string)
{
if (@string.EndsWith("lt", StringComparison.OrdinalIgnoreCase))
val = @string.Substring(0, @string.Length - 2).Trim();
else
val = @string.Trim();
}
if (textValue.EndsWith("lt", StringComparison.OrdinalIgnoreCase))
textValue = textValue.Substring(0, textValue.Length - 2).Trim();
else
textValue = textValue.Trim();
if (result == null)
{
if (DateTime.TryParseExact(val, "HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault, out DateTime date))
result = date;
}
if (DateTime.TryParseExact(textValue, "HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault, out DateTime date))
result = date;
if (result == null)
{
if (DateTime.TryParseExact(val, "HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault, out DateTime date))
result = date;
}
if (result == null)
{
if (DateTime.TryParseExact(textValue, "HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault, out DateTime date2))
result = date2;
}
if (result == null && !textValue.Contains(":"))
{
CultureInfo provider = CultureInfo.InvariantCulture;
const string format = "HHmm";
if (DateTime.TryParseExact(textValue, format, provider, DateTimeStyles.None, out DateTime tmpDate))
result = tmpDate;
}
}
if ((result == null) && (val != null))
{
CultureInfo provider = CultureInfo.InvariantCulture;
string dateString = val.ToString();
if (!dateString.Contains(":"))
{
const string format = "HHmm";
if (DateTime.TryParseExact(dateString, format, provider, DateTimeStyles.None, out DateTime tmpDate))
result = tmpDate;
}
}
}
@ -655,7 +627,7 @@ namespace ENI2.Excel
{
try
{
var theWorkSheet = _workBook.Worksheets.Worksheet(sheetName);
Worksheet theWorkSheet = _workBook.Worksheets[sheetName];
return theWorkSheet != null;
}
catch (Exception)
@ -668,13 +640,12 @@ namespace ENI2.Excel
{
try
{
var workSheet = _workBook.Worksheets.Worksheet(sheetName);
var cell = workSheet.Range(range).FirstCell();
string result = cell.Value.ToString();
Worksheet workSheet = (Worksheet)_workBook.Worksheets[sheetName];
string result = workSheet.Range[range].Text.ToString();
if (!result.IsNullOrEmpty())
{
result = result.Trim().Clean();
if (maxLength.HasValue && result.Length > maxLength.Value)
if(maxLength.HasValue && result.Length > maxLength.Value)
{
result = result.Substring(0, maxLength.Value);
}
@ -692,9 +663,8 @@ namespace ENI2.Excel
{
try
{
var workSheet = _workBook.Worksheets.Worksheet(sheetName);
var cell = workSheet.Cell(row, col);
string result = cell.Value.ToString();
Worksheet workSheet = (Worksheet)_workBook.Worksheets[sheetName];
string result = workSheet.Range[row, col].Text.ToString();
if (!result.IsNullOrEmpty())
result = result.Trim().Clean();
return result;
@ -711,11 +681,10 @@ namespace ENI2.Excel
{
try
{
var workSheet = _workBook.Worksheets.Worksheet(sheetName);
var aRange = workSheet.Range(range);
Worksheet workSheet = (Worksheet)_workBook.Worksheets[sheetName];
Range aRange = workSheet.Range[range];
if (aRange != null)
{
// TODO: Implement dropdown reading logic for ClosedXML
}
}
catch (Exception e)
@ -744,27 +713,26 @@ namespace ENI2.Excel
try
{
double? result = null;
var workSheet = _workBook.Worksheets.Worksheet(sheetName);
var cell = workSheet.Range(range).FirstCell();
var cellValue = cell.Value;
if (cellValue.IsNumber)
Worksheet workSheet = (Worksheet)_workBook.Worksheets[sheetName];
var val = workSheet.Range[range].Value;
if (val is double) result = val;
if (val is string)
{
result = cellValue.GetNumber();
}
else if (cellValue.IsText)
{
string textValue = cellValue.GetText();
if (double.TryParse(textValue, NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite,
if (double.TryParse(val, NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite,
CultureInfo.InvariantCulture, out double tmpDouble))
result = tmpDouble;
if (result == null)
{
if (double.TryParse(textValue, out tmpDouble)) // current language style (==GER, mit , statt .)
if (double.TryParse(val, out tmpDouble)) // current language style (==GER, mit , statt .)
result = tmpDouble;
}
}
if ((result == null) && (val != null))
{
double tmpDouble2 = val[1, 1];
result = tmpDouble2;
}
return result;
}
catch (Exception e)
@ -779,7 +747,7 @@ namespace ENI2.Excel
string dateString = ReadCellAsText(sheetName, range);
if (dateString != null)
{
string[] formats = { "yyyy/MM/dd HH:mm", "yyyy/MM/dd", "dd.MM.yyyy", "dd-MM-yyyy", "d/M/yyyy", "dd/M/yyyy", "d/MM/yyyy", "dd/MM/yyyy", "d/MMM/yyyy", "dd/MMM/yyyy", "yyyy-MM-dd", "yyyy-MM-d", "dd.MM.yyyy HH:mm:ss", "dd.MM.yyyy HH:mm" };
string[] formats = { "yyyy/MM/dd HH:mm", "yyyy/MM/dd", "dd.MM.yyyy", "dd-MM-yyyy", "d/M/yyyy", "dd/M/yyyy", "d/MM/yyyy", "dd/MM/yyyy", "d/MMM/yyyy", "dd/MMM/yyyy", "yyyy-MM-dd", "yyyy-mm-d" };
if (DateTime.TryParseExact(dateString, formats, NumberFormatInfo.InvariantInfo, DateTimeStyles.None, out DateTime tmpDate))
return tmpDate;
CultureInfo en = CultureInfo.CreateSpecificCulture("en-US");
@ -791,6 +759,7 @@ namespace ENI2.Excel
return null;
}
#endregion Dakosy-specific functions
}
}
}

View File

@ -1,10 +1,12 @@
// Copyright (c) 2017- schick Informatik
// Description: Dumps Maersk data into a simple Excel file
//
using System;
using System;
using System.Collections.Generic;
using ClosedXML.Excel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
using bsmd.database;
namespace ENI2.Excel
@ -15,58 +17,68 @@ namespace ENI2.Excel
{
data.Sort();
using (var workbook = new XLWorkbook())
Application excelApp = new Application();
excelApp.DisplayAlerts = false;
excelApp.Visible = false;
Workbook wb = excelApp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Worksheet ws = wb.Worksheets[1];
// Überschriften erste Zeile
ws.Cells[1, 1] = "ETA";
ws.Cells[1, 2] = "ETD";
ws.Cells[1, 3] = "Rotation name";
ws.Cells[1, 4] = "Vessel code";
ws.Cells[1, 5] = "Vessel name";
ws.Cells[1, 6] = "IMO";
ws.Cells[1, 7] = "Arr voy";
ws.Cells[1, 8] = "Dep voy";
ws.Cells[1, 9] = "Terminal name";
ws.Cells[1, 10] = "Operator code";
ws.Cells[1, 11] = "Pro arr";
ws.Cells[1, 12] = "Pro dep";
ws.Cells[1, 13] = "ID";
ws.Cells[1, 14] = "Remark";
for (int i = 0; i < data.Count; i++)
{
var worksheet = workbook.Worksheets.Add("Sheet1");
MaerskData md = data[i];
// Headers in first row
worksheet.Cell(1, 1).Value = "ETA";
worksheet.Cell(1, 2).Value = "ETD";
worksheet.Cell(1, 3).Value = "Rotation name";
worksheet.Cell(1, 4).Value = "Vessel code";
worksheet.Cell(1, 5).Value = "Vessel name";
worksheet.Cell(1, 6).Value = "IMO";
worksheet.Cell(1, 7).Value = "Arr voy";
worksheet.Cell(1, 8).Value = "Dep voy";
worksheet.Cell(1, 9).Value = "Terminal name";
worksheet.Cell(1, 10).Value = "Operator code";
worksheet.Cell(1, 11).Value = "Pro arr";
worksheet.Cell(1, 12).Value = "Pro dep";
worksheet.Cell(1, 13).Value = "ID";
worksheet.Cell(1, 14).Value = "Remark";
ws.Cells[i + 2, 1].NumberFormat = "TT/hh:mm";
ws.Cells[i + 2, 1] = md.ColA;
ws.Cells[i + 2, 2].NumberFormat = "TT/hh:mm";
ws.Cells[i + 2, 2] = md.ColB;
ws.Cells[i + 2, 3] = md.ColC;
ws.Cells[i + 2, 4] = md.ColD;
ws.Cells[i + 2, 5] = md.ColE;
ws.Cells[i + 2, 6] = md.ColF;
ws.Cells[i + 2, 7] = md.ColG;
ws.Cells[i + 2, 8] = md.ColH;
ws.Cells[i + 2, 9] = md.ColI;
ws.Cells[i + 2, 10] = md.ColJ;
ws.Cells[i + 2, 11] = md.ColK;
ws.Cells[i + 2, 12] = md.ColL;
ws.Cells[i + 2, 13] = md.ColM ;
ws.Cells[i + 2, 14] = md.Remark;
for (int i = 0; i < data.Count; i++)
if((md.MessageCore != null) && (md.MessageCore.Cancelled ?? false))
{
MaerskData md = data[i];
int row = i + 2; // Data starts from row 2
worksheet.Cell(row, 1).Value = md.ColA;
worksheet.Cell(row, 1).Style.NumberFormat.Format = "dd/hh:mm";
worksheet.Cell(row, 2).Value = md.ColB;
worksheet.Cell(row, 2).Style.NumberFormat.Format = "dd/hh:mm";
worksheet.Cell(row, 3).Value = md.ColC;
worksheet.Cell(row, 4).Value = md.ColD;
worksheet.Cell(row, 5).Value = md.ColE;
worksheet.Cell(row, 6).Value = md.ColF;
worksheet.Cell(row, 7).Value = md.ColG;
worksheet.Cell(row, 8).Value = md.ColH;
worksheet.Cell(row, 9).Value = md.ColI;
worksheet.Cell(row, 10).Value = md.ColJ;
worksheet.Cell(row, 11).Value = md.ColK;
worksheet.Cell(row, 12).Value = md.ColL;
worksheet.Cell(row, 13).Value = md.ColM;
worksheet.Cell(row, 14).Value = md.Remark;
if ((md.MessageCore != null) && (md.MessageCore.Cancelled ?? false))
{
worksheet.Row(row).Style.Font.Strikethrough = true;
}
ws.Rows[i + 2].Font.Strikethrough = true;
}
workbook.SaveAs(filename);
}
wb.SaveAs(filename, XlFileFormat.xlOpenXMLWorkbook, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
wb.Saved = true;
wb.Close(0);
Marshal.ReleaseComObject(ws);
Marshal.ReleaseComObject(wb);
excelApp.Quit();
Marshal.ReleaseComObject(excelApp);
}
}
}
}

View File

@ -15,7 +15,6 @@ using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace ENI2.Excel
@ -1008,18 +1007,15 @@ namespace ENI2.Excel
STAT stat = statMessage.Elements[0] as STAT;
ScanMessage(stat, reader);
if (!messageCore.IsTransit) // let's not do this for transit messages
foreach (Message preMessage in messages)
{
foreach (Message preMessage in messages)
if (preMessage.MessageNotificationClass == Message.NotificationClass.PRE72H)
{
if (preMessage.MessageNotificationClass == Message.NotificationClass.PRE72H)
if (preMessage.Elements.Count > 0)
{
if (preMessage.Elements.Count > 0)
{
PRE72H pre72h = preMessage.Elements[0] as PRE72H;
pre72h.Tanker = stat.IsTanker;
ExcelReader.SaveMessage(preMessage);
}
PRE72H pre72h = preMessage.Elements[0] as PRE72H;
pre72h.Tanker = stat.IsTanker;
ExcelReader.SaveMessage(preMessage);
}
}
}
@ -1244,7 +1240,6 @@ namespace ENI2.Excel
if ((reader.Mode == ExcelReader.CountryMode.DE) && waste.IsDashWasteCode)
{
waste.WasteDescription = "-";
// NOP
}
else if (reader.Mode == ExcelReader.CountryMode.DK)
{
@ -1284,19 +1279,18 @@ namespace ENI2.Excel
if (waste.WasteType == 2309) waste.WasteType = 507;
if (waste.WasteType == 3000) waste.WasteType = 401;
waste.WasteDisposalAmount_MTQ = reader.ReadNumber(wasteAmount);
if (!waste.WasteDisposalAmount_MTQ.HasValue && reader.ReadText(wasteAmount).IsNullOrEmpty()) waste.WasteDisposalAmount_MTQ = 0;
waste.WasteCapacity_MTQ = reader.ReadNumber(wasteCapacity);
if (!waste.WasteCapacity_MTQ.HasValue && reader.ReadText(wasteCapacity).IsNullOrEmpty()) waste.WasteCapacity_MTQ = 0;
waste.WasteAmountRetained_MTQ = reader.ReadNumber(wasteRetained);
if (!waste.WasteAmountRetained_MTQ.HasValue && reader.ReadText(wasteRetained).IsNullOrEmpty()) waste.WasteAmountRetained_MTQ = 0;
waste.WasteDisposalAmount_MTQ = reader.ReadNumberDefaultZero(wasteAmount);
waste.WasteCapacity_MTQ = reader.ReadNumberDefaultZero(wasteCapacity);
waste.WasteAmountRetained_MTQ = reader.ReadNumberDefaultZero(wasteRetained);
waste.WasteDisposalPort = reader.ReadSSNLocode(wastePort); // aka RemainingWasteDisposalPort
if ((waste.WasteDisposalPort == null) && reader.ReadText(wastePort).IsNullOrEmpty()) waste.WasteDisposalPort = "ZZUKN";
if (waste.WasteDisposalPort.IsNullOrEmpty())
{
waste.WasteDisposalPort = "ZZUKN";
}
waste.WasteAmountGeneratedTillNextPort_MTQ = reader.ReadNumber(amountGen);
if (!waste.WasteAmountGeneratedTillNextPort_MTQ.HasValue && reader.ReadText(amountGen).IsNullOrEmpty()) waste.WasteAmountGeneratedTillNextPort_MTQ = 0;
waste.WasteAmountGeneratedTillNextPort_MTQ = reader.ReadNumberDefaultZero(amountGen);
if (!waste.WasteType.HasValue || (waste.WasteType > 999))
{
@ -1304,8 +1298,7 @@ namespace ENI2.Excel
}
}
was.AddMissingWaste(false);
was.AddMissingWaste();
return true;
}
@ -1375,7 +1368,7 @@ namespace ENI2.Excel
wr.WasteCode.Equals("204") || wr.WasteCode.Equals("510") || wr.WasteCode.Equals("511"))
wr.WasteDescription = "-";
}
wr.AmountWasteReceived_MTQ = reader.ReadNumber(wAmount); // ?? (double?)0; // Default ist 0, nicht nix ;-) // Update: wir wollen doch einen Fehler
wr.AmountWasteReceived_MTQ = reader.ReadNumber(wAmount) ?? (double?)0; // Default ist 0, nicht nix ;-)
}
// only add message when an identification number was given
@ -1425,10 +1418,10 @@ namespace ENI2.Excel
int i = 1;
foreach (LastTenPortFacilitiesCalled ltpfc in sec.LastTenPortFacilitesCalled)
{
if (!(mdh.GetSublistElementWithIdentifier((i).ToString()) is PortOfCallLast30Days poc30d))
if (!(mdh.GetSublistElementWithIdentifier((i + 1).ToString()) is PortOfCallLast30Days poc30d))
{
poc30d = new PortOfCallLast30Days();
poc30d.Identifier = (i).ToString();
poc30d.Identifier = (i + 1).ToString();
poc30d.MDH = mdh;
mdh.PortOfCallLast30Days.Add(poc30d);
}
@ -1442,66 +1435,64 @@ namespace ENI2.Excel
}
else // "normal mode", aus den Zellen lesen
{
string sheetTitle = "1. VOYAGE";
// 4.8.25: Changed this area to work like reading from a Dakosy Sheet (by values in rows, not cell names)
if (reader.HasWorksheetNamed(sheetTitle))
// POC last 30 days
for (int i = 0; i < mdh.NumberOfExcelRows; i++)
{
string portName = string.Format("MDH.PortOfCallLast30DaysPort_{0}", i + 1);
string portCountry = string.Format("MDH.PortOfCallLast30DaysCountry_{0}", i + 1);
string locode = string.Format("MDH.PortOfCallLast30DaysLocode_{0}", i + 1);
string crewJoined = string.Format("MDH.PortOfCallLast30DaysCrewMembersJoined_{0}", i + 1);
string crewName = string.Format("MDH.PortOfCallLast30DaysCrewJoinedShipName_{0}", i + 1);
string depDate = string.Format("MDH.PortOfCallLast30DaysDateOfDeparture_{0}", i + 1);
// POC last 30 days
for (int i = 0; i < mdh.NumberOfExcelRows; i++)
{
if (!(mdh.GetSublistElementWithIdentifier((i + 1).ToString()) is PortOfCallLast30Days poc30d))
{
poc30d = new PortOfCallLast30Days();
poc30d.Identifier = (i + 1).ToString();
poc30d.MDH = mdh;
mdh.PortOfCallLast30Days.Add(poc30d);
}
string pName = reader.ReadCellAsText(sheetTitle, string.Format("C{0}", 82 + i));
string pCountry = reader.ReadCellAsText(sheetTitle, string.Format("E{0}", 82 + i));
poc30d.PortOfCallLast30DaysDateOfDeparture = reader.ReadCellAsDateTime(sheetTitle, string.Format("G{0}", 82 + i));
poc30d.PortOfCallLast30DaysLocode = reader.ReadCellAsText(sheetTitle, string.Format("F{0}", 82 + i));
if (LocodeDB.PortNameFromLocode(poc30d.PortOfCallLast30DaysLocode).IsNullOrEmpty()) poc30d.PortOfCallLast30DaysLocode = "";
// Verbesserungsvorschlag Jul/21: CrewMembersJoined Häkchen abhängig von den Namen in der Spalte
bool? PortOfCallLast30DaysCrewMembersJoinedFlag = reader.ReadCellAsBool(sheetTitle, string.Format("H{0}", 82 + i));
string crewNameString = reader.ReadCellAsText(sheetTitle, string.Format("I{0}", 82 + i));
poc30d.PortOfCallLast30DaysCrewMembersJoined = !crewNameString.IsNullOrEmpty() && (crewNameString.Length > 1);
// if crew members joined is set explicitly to true and the name is empty, still set the field to true
if (!(poc30d.PortOfCallLast30DaysCrewMembersJoined ?? false) && (PortOfCallLast30DaysCrewMembersJoinedFlag ?? false))
poc30d.PortOfCallLast30DaysCrewMembersJoined = true;
if (!crewNameString.IsNullOrEmpty() && (poc30d.PortOfCallLast30DaysCrewMembersJoined ?? false))
{
// try different separators
string[] crew = crewNameString.Split(';');
if (crew.Length == 1)
crew = crewNameString.Split(',');
for (int j = 0; j < crew.Length; j++)
{
if (!(poc30d.GetSublistElementWithIdentifier((j + 1).ToString()) is PortOfCallLast30DaysCrewJoinedShip poc30dCrew))
{
poc30dCrew = new PortOfCallLast30DaysCrewJoinedShip();
poc30dCrew.Identifier = (j + 1).ToString();
poc30dCrew.PortOfCallLast30Days = poc30d;
poc30d.CrewJoinedShip.Add(poc30dCrew);
}
poc30dCrew.PortOfCallLast30DaysCrewJoinedShipName = crew[j];
}
}
// Leer/def. Zeilen entfernen
if (!poc30d.PortOfCallLast30DaysDateOfDeparture.HasValue && (poc30d.PortOfCallLast30DaysLocode.IsNullOrEmpty()))
mdh.PortOfCallLast30Days.Remove(poc30d);
if (!(mdh.GetSublistElementWithIdentifier((i + 1).ToString()) is PortOfCallLast30Days poc30d))
{
poc30d = new PortOfCallLast30Days();
poc30d.Identifier = (i + 1).ToString();
poc30d.MDH = mdh;
mdh.PortOfCallLast30Days.Add(poc30d);
}
string pName = reader.ReadText(portName);
string pCountry = reader.ReadText(portCountry);
poc30d.PortOfCallLast30DaysDateOfDeparture = reader.ReadDate(depDate);
poc30d.PortOfCallLast30DaysLocode = reader.ReadLoCode(locode);
// Verbesserungsvorschlag Jul/21: CrewMembersJoined Häkchen abhängig von den Namen in der Spalte
bool? PortOfCallLast30DaysCrewMembersJoinedFlag = reader.ReadBoolean(crewJoined);
string crewNameString = reader.ReadText(crewName);
poc30d.PortOfCallLast30DaysCrewMembersJoined = !crewNameString.IsNullOrEmpty();
// if crew members joined is set explicitly to true and the name is empty, still set the field to true
if (!(poc30d.PortOfCallLast30DaysCrewMembersJoined ?? false) && (PortOfCallLast30DaysCrewMembersJoinedFlag ?? false))
poc30d.PortOfCallLast30DaysCrewMembersJoined = true;
if (!crewNameString.IsNullOrEmpty() && (poc30d.PortOfCallLast30DaysCrewMembersJoined ?? false))
{
// try different separators
string[] crew = crewNameString.Split(';');
if (crew.Length == 1)
crew = crewNameString.Split(',');
for (int j = 0; j < crew.Length; j++)
{
if (!(poc30d.GetSublistElementWithIdentifier((j + 1).ToString()) is PortOfCallLast30DaysCrewJoinedShip poc30dCrew))
{
poc30dCrew = new PortOfCallLast30DaysCrewJoinedShip();
poc30dCrew.Identifier = (j + 1).ToString();
poc30dCrew.PortOfCallLast30Days = poc30d;
poc30d.CrewJoinedShip.Add(poc30dCrew);
}
poc30dCrew.PortOfCallLast30DaysCrewJoinedShipName = crew[j];
}
}
// Leer/def. Zeilen entfernen
if (!poc30d.PortOfCallLast30DaysDateOfDeparture.HasValue && (poc30d.PortOfCallLast30DaysLocode == null))
mdh.PortOfCallLast30Days.Remove(poc30d);
}
}
@ -1614,10 +1605,7 @@ namespace ENI2.Excel
}
SEC sec = secMessage.Elements[0] as SEC;
((ISublistContainer)sec).DeleteElements();
ScanMessage(sec, reader);
ScanMessage(sec, reader);
reader.ReadBoolean("SEC.AreMatterToReport"); // das berücksichtigen wir derzeit nicht in der DB (implizit)
@ -1667,84 +1655,97 @@ namespace ENI2.Excel
if (!sec.KielCanalPassagePlannedIncomming.HasValue && !sec.KielCanalPassagePlannedOutgoing.HasValue)
sec.KielCanalPassagePlanned = false;
// Last10PortFacilitesCalled
for (int i = 1; i <= 10; i++)
{
string portName = string.Format("SEC.PortFacilityPortName_{0}", i);
string portCountry = string.Format("SEC.PortFacilityPortCountry_{0}", i);
string portLocode = string.Format("SEC.PortFacilityPortLoCode_{0}", i);
string portDateOfArrival = string.Format("SEC.PortFacilityDateOfArrival_{0}", i);
string portDateOfDeparture = string.Format("SEC.PortFacilityDateOfDeparture_{0}", i);
string portShipSecLevel = string.Format("SEC.PortFacilityShipSecurityLevel_{0}", i);
string portGISISCode = string.Format("SEC.PortFacilityGISISCode_{0}", i);
string portSecMatters = string.Format("SEC.PortFacilitySecurityMattersToReport_{0}", i);
string sheetTitle = "1. VOYAGE";
// 4.8.25: Changed this area to work like reading from a Dakosy Sheet (by values in rows, not cell names)
if (reader.HasWorksheetNamed(sheetTitle))
{
// Last10PortFacilitesCalled
for (int i = 0; i < 10; i++)
{
if (!(sec.GetPortFacilityWithIdentifier((i + 1).ToString()) is LastTenPortFacilitiesCalled l10fc))
{
l10fc = new LastTenPortFacilitiesCalled();
l10fc.Identifier = (i + 1).ToString();
l10fc.SEC = sec;
sec.LastTenPortFacilitesCalled.Add(l10fc);
}
l10fc.PortFacilityPortName = reader.ReadCellAsText(sheetTitle, string.Format("C{0}", 54 + i), 99);
l10fc.PortFacilityPortCountry = reader.ReadCellAsText(sheetTitle, string.Format("E{0}", 54 + i), 99);
l10fc.PortFacilityPortLoCode = reader.ReadCellAsText(sheetTitle, string.Format("F{0}", 54 + i), 5);
if (LocodeDB.PortNameFromLocode(l10fc.PortFacilityPortLoCode).IsNullOrEmpty()) l10fc.PortFacilityPortLoCode = "";
l10fc.PortFacilityDateOfArrival = reader.ReadCellAsDateTime(sheetTitle, string.Format("G{0}", 54 + i));
l10fc.PortFacilityDateOfDeparture = reader.ReadCellAsDateTime(sheetTitle, string.Format("H{0}", 54 + i));
string sLevel = reader.ReadCellAsText(sheetTitle, string.Format("I{0}", 54 + i));
if (!sLevel.IsNullOrEmpty())
{
if (sLevel.Contains('1')) l10fc.PortFacilityShipSecurityLevel = 1;
if (sLevel.Contains('2')) l10fc.PortFacilityShipSecurityLevel = 2;
if (sLevel.Contains('3')) l10fc.PortFacilityShipSecurityLevel = 3;
}
string s = reader.ReadCellAsText(sheetTitle, string.Format("J{0}", 54 + i));
// All invalid codes become "0000", Oct/25
l10fc.PortFacilityGISISCode = (s != null) && Regex.IsMatch(s.Trim(), @"^\d{1,4}$") ? s.Trim().PadLeft(4, '0') : "0000";
l10fc.PortFacilitySecurityMattersToReport = reader.ReadCellAsText(sheetTitle, string.Format("K{0}", 54 + i), 255);
// keinen "leeren" Hafen anlegen, wenn der Eintrag leer war (trifft anscheinend bei Neubauten zu, siehe E-Mail Christin vom 20./22.6.17
if (l10fc.PortFacilityPortName.IsNullOrEmpty() && l10fc.PortFacilityPortLoCode.IsNullOrEmpty() && l10fc.PortFacilityPortCountry.IsNullOrEmpty())
sec.LastTenPortFacilitesCalled.Remove(l10fc);
if (!(sec.GetPortFacilityWithIdentifier(i.ToString()) is LastTenPortFacilitiesCalled l10fc))
{
l10fc = new LastTenPortFacilitiesCalled();
l10fc.Identifier = i.ToString();
l10fc.SEC = sec;
sec.LastTenPortFacilitesCalled.Add(l10fc);
}
// Ship2ShipActivities
for (int i = 0; i < 10; i++)
{
l10fc.PortFacilityPortName = reader.ReadText(portName);
l10fc.PortFacilityPortCountry = reader.ReadText(portCountry);
l10fc.PortFacilityPortLoCode = reader.ReadLoCode(portLocode);
l10fc.PortFacilityDateOfArrival = reader.ReadDate(portDateOfArrival);
l10fc.PortFacilityDateOfDeparture = reader.ReadDate(portDateOfDeparture);
if (!(sec.GetShipToShipWithIdentifier((i + 1).ToString()) is ShipToShipActivitiesDuringLastTenPortFacilitiesCalled s2sActivity))
{
s2sActivity = new ShipToShipActivitiesDuringLastTenPortFacilitiesCalled();
s2sActivity.Identifier = (i + 1).ToString();
s2sActivity.SEC = sec;
sec.ShipToShipActivitiesDuringLastTenPortFacilitiesCalled.Add(s2sActivity);
}
s2sActivity.ShipToShipActivityLocationName = reader.ReadCellAsText(sheetTitle, string.Format("C{0}", 68 + i), 255);
if (s2sActivity.ShipToShipActivityLocationName.IsNullOrEmpty())
{
sec.ShipToShipActivitiesDuringLastTenPortFacilitiesCalled.Remove(s2sActivity);
continue;
}
s2sActivity.ShipToShipActivityLocationLoCode = reader.ReadCellAsText(sheetTitle, string.Format("E{0}", 68 + i), 5);
if (LocodeDB.PortNameFromLocode(s2sActivity.ShipToShipActivityLocationLoCode).IsNullOrEmpty()) s2sActivity.ShipToShipActivityLocationLoCode = "";
s2sActivity.ShipToShipActivityLocationCoordinatesLatitude = (int?) reader.ReadCellAsDecimal(sheetTitle, string.Format("F{0}", 68 + i));
// keine "0" (d.h. fehlerhafte Koordinaten) ins ANSW übergeben falls im Sheet nichts ist aber der Reader das aus irgendeinem Grund liest
if (s2sActivity.ShipToShipActivityLocationCoordinatesLatitude == 0)
s2sActivity.ShipToShipActivityLocationCoordinatesLatitude = null;
s2sActivity.ShipToShipActivityLocationCoordinatesLongitude = (int?)reader.ReadCellAsDecimal(sheetTitle, string.Format("G{0}", 68 + i));
if (s2sActivity.ShipToShipActivityLocationCoordinatesLongitude == 0)
s2sActivity.ShipToShipActivityLocationCoordinatesLongitude = null;
s2sActivity.ShipToShipActivityDateFrom = reader.ReadCellAsDateTime(sheetTitle, string.Format("H{0}", 68 + i));
s2sActivity.ShipToShipActivityDateTo = reader.ReadCellAsDateTime(sheetTitle, string.Format("I{0}", 68 + i));
s2sActivity.ShipToShipActivityTypeCode = (int?)reader.ReadCellAsDecimal(sheetTitle, string.Format("J{0}", 68 + i));
s2sActivity.ShipToShipActivitySecurityMattersToReport = reader.ReadCellAsText(sheetTitle, string.Format("K{0}", 68 + i), 255);
string sLevel = reader.ReadText(portShipSecLevel);
if (!sLevel.IsNullOrEmpty())
{
if (sLevel.Contains('1')) l10fc.PortFacilityShipSecurityLevel = 1;
if (sLevel.Contains('2')) l10fc.PortFacilityShipSecurityLevel = 2;
if (sLevel.Contains('3')) l10fc.PortFacilityShipSecurityLevel = 3;
}
l10fc.PortFacilityGISISCode = reader.ReadTextNoWhitespace(portGISISCode);
if (l10fc.PortFacilityGISISCode.IsNullOrEmpty() || l10fc.PortFacilityGISISCode == "0")
l10fc.PortFacilityGISISCode = "0000";
if (l10fc.PortFacilityGISISCode?.Length < 4)
{
while (l10fc.PortFacilityGISISCode.Length < 4) l10fc.PortFacilityGISISCode = "0" + l10fc.PortFacilityGISISCode;
}
l10fc.PortFacilitySecurityMattersToReport = reader.ReadText(portSecMatters);
// keinen "leeren" Hafen anlegen, wenn der Eintrag leer war (trifft anscheinend bei Neubauten zu, siehe E-Mail Christin vom 20./22.6.17
if (l10fc.PortFacilityPortName.IsNullOrEmpty() && l10fc.PortFacilityPortLoCode.IsNullOrEmpty() && l10fc.PortFacilityPortCountry.IsNullOrEmpty())
sec.LastTenPortFacilitesCalled.Remove(l10fc);
}
// Ship2ShipActivities
for (int i = 1; i <= 10; i++)
{
string s2sName = string.Format("SEC.ShipToShipActivityLocationName_{0}", i);
string s2sLocode = string.Format("SEC.ShipToShipActivityLocationLoCode_{0}", i);
string s2sLatitude = string.Format("SEC.ShipToShipActivityLocationCoordinatesLatitude_{0}", i);
string s2sLongitude = string.Format("SEC.ShipToShipActivityLocationCoordinatesLongitude_{0}", i);
string s2sFromDate = string.Format("SEC.ShipToShipActivityDateFrom_{0}", i);
string s2sToDate = string.Format("SEC.ShipToShipActivityDateTo_{0}", i);
string s2sSec = string.Format("SEC.ShipToShipActivitySecurityMattersToReport_{0}", i);
string s2sActivityString = string.Format("SEC.ShipToShipActivityType_{0}", i);
if (!(sec.GetShipToShipWithIdentifier(i.ToString()) is ShipToShipActivitiesDuringLastTenPortFacilitiesCalled s2sActivity))
{
s2sActivity = new ShipToShipActivitiesDuringLastTenPortFacilitiesCalled();
s2sActivity.Identifier = i.ToString();
s2sActivity.SEC = sec;
sec.ShipToShipActivitiesDuringLastTenPortFacilitiesCalled.Add(s2sActivity);
}
s2sActivity.ShipToShipActivityLocationName = reader.ReadText(s2sName);
if (s2sActivity.ShipToShipActivityLocationName.IsNullOrEmpty())
{
sec.ShipToShipActivitiesDuringLastTenPortFacilitiesCalled.Remove(s2sActivity);
continue;
}
s2sActivity.ShipToShipActivityLocationLoCode = reader.ReadLoCode(s2sLocode);
s2sActivity.ShipToShipActivityLocationCoordinatesLatitude = (int?)reader.ReadNumber(s2sLatitude);
// keine "0" (d.h. fehlerhafte Koordinaten) ins ANSW übergeben falls im Sheet nichts ist aber der Reader das aus irgendeinem Grund liest
if (s2sActivity.ShipToShipActivityLocationCoordinatesLatitude == 0)
s2sActivity.ShipToShipActivityLocationCoordinatesLatitude = null;
s2sActivity.ShipToShipActivityLocationCoordinatesLongitude = (int?)reader.ReadNumber(s2sLongitude);
if (s2sActivity.ShipToShipActivityLocationCoordinatesLongitude == 0)
s2sActivity.ShipToShipActivityLocationCoordinatesLongitude = null;
s2sActivity.ShipToShipActivityDateFrom = reader.ReadDate(s2sFromDate);
s2sActivity.ShipToShipActivityDateTo = reader.ReadDate(s2sToDate);
s2sActivity.ShipToShipActivityTypeCode = (int?)reader.ReadNumber(s2sActivityString);
reader.ReadShip2ShipActivityType(s2sActivityString); // 24.8.21 nicht Code dem Klartext zuordnen, nur das Feld kolorieren
s2sActivity.ShipToShipActivitySecurityMattersToReport = reader.ReadText(s2sSec);
}
return true;

View File

@ -1,8 +1,8 @@
// Copyright (c) 2017- schick Informatik
// Description: Writing excel files
// Description:
//
using ClosedXML.Excel;
using Microsoft.Office.Interop.Excel;
using System;
using System.Collections.Generic;
using System.Data;
@ -26,9 +26,10 @@ namespace ENI2.Excel
if (isRefSheet) filename = @"Excel\Reference_Sheet_DE.xlsx";
string refFilePath = System.IO.Path.Combine(Environment.CurrentDirectory, filename);
this.OpenWorkbookReadOnly(refFilePath);
this._workBook = _excelWorkbooks.Open(refFilePath, 0, true, 5, "", "", false, XlPlatform.xlWindows, "", false, false, 0, false, false, false);
this.InitNameFields();
}
#endregion
@ -43,7 +44,7 @@ namespace ENI2.Excel
{
try
{
switch (message.MessageNotificationClass)
switch(message.MessageNotificationClass)
{
case Message.NotificationClass.AGNT:
if (message.Elements[0] is AGNT agnt) this.WriteMessage(agnt);
@ -83,10 +84,10 @@ namespace ENI2.Excel
break;
case Message.NotificationClass.HAZA:
this.WriteHAZ(message, true);
break;
break;
case Message.NotificationClass.HAZD:
this.WriteHAZ(message, false);
break;
break;
case Message.NotificationClass.INFO:
if (message.Elements[0] is INFO info)
{
@ -191,6 +192,11 @@ namespace ENI2.Excel
}
public void WriteMaerskList(List<MaerskData> maerskList)
{
}
#endregion
#region private excel field writing
@ -236,7 +242,7 @@ namespace ENI2.Excel
else if (property.PropertyType == typeof(Boolean?))
{
object boolVal = property.GetValue(dbEntity);
if (boolVal != null)
if(boolVal != null)
success = this.WriteBoolean(lookupNameAttribute.LookupName, boolVal);
}
else
@ -368,21 +374,18 @@ namespace ENI2.Excel
#endregion
// [Rest of the methods remain exactly the same as they only call the base class methods]
// I'll include a few key ones to show the pattern, but the rest are identical...
#region CREW
private void WriteCREW(Message crewMessage, bool isArrival, bool isRefSheet)
{
if (crewMessage.Elements.Count > 0)
{
WriteBoolean(string.Format("CREW{0}.NotificationSchengen", isArrival ? "" : "D"), ((CREW)crewMessage.Elements[0]).NotificationSchengen);
WriteBoolean(string.Format("CREW{0}.NotificationPAX", isArrival ? "" : "D"), ((CREW)crewMessage.Elements[0]).NotificationPAX);
}
}
for (int i = 0; i < Math.Min(crewMessage.NumberOfExcelRows, crewMessage.Elements.Count); i++)
for(int i = 0; i<Math.Min(crewMessage.NumberOfExcelRows, crewMessage.Elements.Count); i++)
{
string crewLastName = string.Format("CREW{1}.CrewMemberLastName_{0}", i + 1, isArrival ? "" : "D");
string crewFirstName = string.Format("CREW{1}.CrewMemberFirstName_{0}", i + 1, isArrival ? "" : "D");
@ -410,7 +413,7 @@ namespace ENI2.Excel
WriteText(crewNationality, crew.CrewMemberNationality);
WriteText(crewDuty, crew.CrewMemberDuty);
WriteText(crewPlaceOfBirth, crew.CrewMemberPlaceOfBirth);
if (crew.CrewMemberDateOfBirth.HasValue)
if(crew.CrewMemberDateOfBirth.HasValue)
WriteDate(crewDateOfBirth, crew.CrewMemberDateOfBirth.Value);
WriteText(crewIdentDocType, crew.CrewMemberIdentityDocumentTypeDisplay);
WriteText(crewIdentDocId, crew.CrewMemberIdentityDocumentId);
@ -421,16 +424,16 @@ namespace ENI2.Excel
}
else
{
if (!crew.CrewMemberIdentityDocumentIssuingState.IsNullOrEmpty() && !crew.CrewMemberIdentityDocumentIssuingState.Equals("XX"))
if(!crew.CrewMemberIdentityDocumentIssuingState.IsNullOrEmpty() && !crew.CrewMemberIdentityDocumentIssuingState.Equals("XX"))
WriteText(crewIssuingState, crew.CrewMemberIdentityDocumentIssuingState);
}
if (isRefSheet)
if(isRefSheet)
{
WriteDate(crewExpiry, crew.CrewMemberIdentityDocumentExpiryDate);
}
else
{
if (crew.CrewMemberIdentityDocumentExpiryDate != new DateTime(2100, 12, 31))
if(crew.CrewMemberIdentityDocumentExpiryDate != new DateTime(2100, 12, 31))
WriteDate(crewExpiry, crew.CrewMemberIdentityDocumentExpiryDate);
}
@ -790,12 +793,12 @@ namespace ENI2.Excel
private void WritePAS(Message pasMessage, bool isArrival, bool isRefSheet)
{
if(pasMessage.Elements.Count > 0)
{
WriteBoolean(string.Format("PAS{0}.NotificationSchengen", isArrival ? "" : "D"), ((PAS)pasMessage.Elements[0]).NotificationSchengen);
WriteBoolean(string.Format("PAS{0}.NotificationPAX", isArrival ? "" : "D"), ((PAS)pasMessage.Elements[0]).NotificationPAX);
}
}
for(int i = 0; i < Math.Min(pasMessage.NumberOfExcelRows, pasMessage.Elements.Count); i++)
{
@ -1063,7 +1066,7 @@ namespace ENI2.Excel
string tLen = string.Format("TOWD.TowageOnDepartureLengthOverall_MTR_{0}", i + 1);
string tBeam = string.Format("TOWD.TowageOnDepartureBeam_MTR_{0}", i + 1);
string tOp = string.Format("TOWD.TowageOnDepartureOperatorCompanyName_{0}", i + 1);
// string tPoc = string.Format("TOWD.TowageOnDeparturePurposeOfCall_{0}", i + 1);
string tPoc = string.Format("TOWD.TowageOnDeparturePurposeOfCall_{0}", i + 1);
TOWD towd = towdMessage.Elements[i] as TOWD;
@ -1273,7 +1276,7 @@ namespace ENI2.Excel
private void WriteGenderCode(string label, byte? gender)
{
if (gender.HasValue)
if(gender.HasValue)
{
if (gender == 0) WriteText(label, "not known");
if (gender == 1) WriteText(label, "m");
@ -1300,24 +1303,15 @@ namespace ENI2.Excel
private bool WriteBoolean(string lookupName, object v)
{
bool result = _nameDict.ContainsKey(lookupName);
bool? b = (bool?)v;
bool? b = (bool?) v;
try
{
if (result && b.HasValue)
{
var definedName = _nameDict[lookupName];
var range = definedName.Ranges.FirstOrDefault();
if (range != null)
{
var cell = range.FirstCell();
if (cell != null)
{
cell.Value = b.Value ? "Y" : "N";
}
}
_nameDict[lookupName].RefersToRange.Value = b.Value ? "Y" : "N";
}
}
catch (Exception)
catch(Exception)
{
System.Diagnostics.Trace.WriteLine(string.Format("Error writing {0} to excel, field missing", lookupName));
}
@ -1332,19 +1326,10 @@ namespace ENI2.Excel
{
if (result)
{
var definedName = _nameDict[lookupName];
var range = definedName.Ranges.FirstOrDefault();
if (range != null)
{
var cell = range.FirstCell();
if (cell != null)
{
cell.Value = ClosedXML.Excel.XLCellValue.FromObject(v);
}
}
_nameDict[lookupName].RefersToRange.Value = v;
}
}
catch (Exception)
catch(Exception)
{
System.Diagnostics.Trace.WriteLine(string.Format("Error writing {0} to excel, field missing", lookupName));
}
@ -1358,16 +1343,7 @@ namespace ENI2.Excel
if (result)
{
var definedName = _nameDict[lookupName];
var range = definedName.Ranges.FirstOrDefault();
if (range != null)
{
var cell = range.FirstCell();
if (cell != null)
{
cell.Value = ClosedXML.Excel.XLCellValue.FromObject(v);
}
}
_nameDict[lookupName].RefersToRange.Value = v;
}
return result;
@ -1379,19 +1355,11 @@ namespace ENI2.Excel
if (result)
{
if (v != null)
if(v != null)
{
var definedName = _nameDict[lookupName];
var range = definedName.Ranges.FirstOrDefault();
if (range != null)
{
var cell = range.FirstCell();
if (cell != null)
{
cell.Value = ClosedXML.Excel.XLCellValue.FromObject(((DateTime)v).ToLocalTime());
}
}
_nameDict[lookupName].RefersToRange.Value = ((DateTime) v).ToLocalTime().ToOADate();
}
}
return result;
@ -1405,17 +1373,9 @@ namespace ENI2.Excel
{
if (v != null)
{
var definedName = _nameDict[lookupName];
var range = definedName.Ranges.FirstOrDefault();
if (range != null)
{
var cell = range.FirstCell();
if (cell != null)
{
cell.Value = ((DateTime)v).ToLocalTime().ToString("HH:mm");
}
}
_nameDict[lookupName].RefersToRange.Value = ((DateTime)v).ToLocalTime().ToShortTimeString();
}
}
return result;

View File

@ -95,7 +95,6 @@
<MenuItem x:Name="menuItemUserAdministration" Header="{x:Static p:Resources.textUserAdministration}" Click="radioButton_Click" Visibility="Hidden"/>
<MenuItem x:Name="menuItemMaersk" Header="{x:Static p:Resources.textPOLists}" Click="radioButton_Click" Visibility="Hidden" />
<MenuItem x:Name="menuItemValueMappings" Header="{x:Static p:Resources.textExcelValueMappings}" Click="radioButton_Click" Visibility="Hidden" />
<MenuItem x:Name="menuItemEasyPeasy" Header="{x:Static p:Resources.textEasyPeasy}" Click="radioButton_Click" Visibility="Hidden" />
<MenuItem x:Name="labelStatusId" />
<MenuItem Header="Help" HorizontalAlignment="Right">
<MenuItem Header="Change Password" Click="buttonChangePassword_Click">

View File

@ -39,7 +39,6 @@ namespace ENI2
private ServerStatusControl statusControl;
private readonly SucheControl sucheControl;
private CompareExcelDialog compareExcelDialog;
private EasyPeasyControl easyPeasyControl;
private bool dbConnected;
private readonly ScaleTransform _transform = new ScaleTransform(1.0, 1.0);
@ -325,14 +324,6 @@ namespace ENI2
}
this.rootContainer.Children.Add(this.vmControl);
}
else if(sender == this.menuItemEasyPeasy)
{
if(this.easyPeasyControl == null)
{
this.easyPeasyControl = new EasyPeasyControl();
}
this.rootContainer.Children.Add(this.easyPeasyControl);
}
}
private void buttonCompareSheets_Click(object sender, RoutedEventArgs ev)
@ -386,8 +377,6 @@ namespace ENI2
Properties.Settings.Default.MainWindowPlacement = this.GetPlacement();
Properties.Settings.Default.Save();
Microsoft.Win32.SystemEvents.SessionEnded -= SystemEvents_SessionEnded;
if (easyPeasyControl != null)
easyPeasyControl.SaveState();
}
private void Window_SourceInitialized(object sender, EventArgs e)
@ -701,7 +690,6 @@ namespace ENI2
ReportingParty.CurrentReportingParty = this.userEntity;
this.menuItemMaersk.Visibility = Visibility.Visible;
this.menuItemValueMappings.Visibility = Visibility.Visible;
this.menuItemEasyPeasy.Visibility = Visibility.Visible;
if (this.userEntity.IsAdmin)
{
this.menuItemUserAdministration.Visibility = Visibility.Visible;
@ -765,6 +753,5 @@ namespace ENI2
#endregion
}
}

View File

@ -750,16 +750,6 @@ namespace ENI2.Properties {
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap pencil {
get {
object obj = ResourceManager.GetObject("pencil", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
@ -2021,7 +2011,7 @@ namespace ENI2.Properties {
}
/// <summary>
/// Looks up a localized string similar to Columns &quot;o&quot; of IBC Code (value 15.19).
/// Looks up a localized string similar to Columns &quot;o&quot; of OBC Code (value 15.19).
/// </summary>
public static string textColumsOfIBC {
get {
@ -2173,20 +2163,6 @@ namespace ENI2.Properties {
}
}
/// <summary>
/// Looks up a localized string similar to The existing value for the waste disposal service provider will be overwritten.
///
///Current entry: {0}
///New entry: {1}
///
///Proceed?.
/// </summary>
public static string textConfirmWSDPOverwrite {
get {
return ResourceManager.GetString("textConfirmWSDPOverwrite", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Construction characteristics.
/// </summary>
@ -2277,15 +2253,6 @@ namespace ENI2.Properties {
}
}
/// <summary>
/// Looks up a localized string similar to Copy from CREWA.
/// </summary>
public static string textCopyFromCREWA {
get {
return ResourceManager.GetString("textCopyFromCREWA", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Copy from last 10 port facilities called.
/// </summary>
@ -2871,15 +2838,6 @@ namespace ENI2.Properties {
}
}
/// <summary>
/// Looks up a localized string similar to Easy Peasy 🍋.
/// </summary>
public static string textEasyPeasy {
get {
return ResourceManager.GetString("textEasyPeasy", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to _Edit.
/// </summary>
@ -2970,15 +2928,6 @@ namespace ENI2.Properties {
}
}
/// <summary>
/// Looks up a localized string similar to ENI-Status.
/// </summary>
public static string textENIStatus {
get {
return ResourceManager.GetString("textENIStatus", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to entries.
/// </summary>
@ -4356,15 +4305,6 @@ namespace ENI2.Properties {
}
}
/// <summary>
/// Looks up a localized string similar to NSW-Status.
/// </summary>
public static string textNSWStatus {
get {
return ResourceManager.GetString("textNSWStatus", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Number of deaths.
/// </summary>
@ -5320,16 +5260,7 @@ namespace ENI2.Properties {
}
/// <summary>
/// Looks up a localized string similar to Select crew member.
/// </summary>
public static string textSelectCrewMember {
get {
return ResourceManager.GetString("textSelectCrewMember", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Select message classes.
/// Looks up a localized string similar to Select classes to import.
/// </summary>
public static string textSelectImportClasses {
get {
@ -5346,15 +5277,6 @@ namespace ENI2.Properties {
}
}
/// <summary>
/// Looks up a localized string similar to Send all.
/// </summary>
public static string textSendAll {
get {
return ResourceManager.GetString("textSendAll", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Send date.
/// </summary>
@ -5436,15 +5358,6 @@ namespace ENI2.Properties {
}
}
/// <summary>
/// Looks up a localized string similar to SERV-Template.
/// </summary>
public static string textSERVTemplate {
get {
return ResourceManager.GetString("textSERVTemplate", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Ship-to-ship activity.
/// </summary>
@ -6390,15 +6303,6 @@ namespace ENI2.Properties {
}
}
/// <summary>
/// Looks up a localized string similar to Waste disposal service provider.
/// </summary>
public static string textWasteDisposalServiceProvider {
get {
return ResourceManager.GetString("textWasteDisposalServiceProvider", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Waste disposal service providers.
/// </summary>

View File

@ -1757,7 +1757,7 @@
<value>Select all</value>
</data>
<data name="textSelectImportClasses" xml:space="preserve">
<value>Select message classes</value>
<value>Select classes to import</value>
</data>
<data name="textSelectNone" xml:space="preserve">
<value>Select none</value>
@ -2233,39 +2233,4 @@
<data name="textSECSimplification" xml:space="preserve">
<value>SEC simplification available</value>
</data>
<data name="textCopyFromCREWA" xml:space="preserve">
<value>Copy from CREWA</value>
</data>
<data name="textSelectCrewMember" xml:space="preserve">
<value>Select crew member</value>
</data>
<data name="textSERVTemplate" xml:space="preserve">
<value>SERV-Template</value>
</data>
<data name="pencil" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\pencil.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
<data name="textWasteDisposalServiceProvider" xml:space="preserve">
<value>Waste disposal service provider</value>
</data>
<data name="textSendAll" xml:space="preserve">
<value>Send all</value>
</data>
<data name="textENIStatus" xml:space="preserve">
<value>ENI-Status</value>
</data>
<data name="textNSWStatus" xml:space="preserve">
<value>NSW-Status</value>
</data>
<data name="textConfirmWSDPOverwrite" xml:space="preserve">
<value>The existing value for the waste disposal service provider will be overwritten.
Current entry: {0}
New entry: {1}
Proceed?</value>
</data>
<data name="textEasyPeasy" xml:space="preserve">
<value>Easy Peasy 🍋</value>
</data>
</root>

View File

@ -12,7 +12,7 @@ namespace ENI2.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.14.0.0")]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.5.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

View File

@ -117,7 +117,7 @@ namespace ENI2.LockingServiceReference {
return this.CORRUPTFilesField;
}
set {
if ((object.ReferenceEquals(this.CORRUPTFilesField, value) != true)) {
if ((ReferenceEquals(this.CORRUPTFilesField, value) != true)) {
this.CORRUPTFilesField = value;
this.RaisePropertyChanged("CORRUPTFiles");
}
@ -143,7 +143,7 @@ namespace ENI2.LockingServiceReference {
return this.IMPFilesField;
}
set {
if ((object.ReferenceEquals(this.IMPFilesField, value) != true)) {
if ((ReferenceEquals(this.IMPFilesField, value) != true)) {
this.IMPFilesField = value;
this.RaisePropertyChanged("IMPFiles");
}
@ -156,7 +156,7 @@ namespace ENI2.LockingServiceReference {
return this.READYFilesField;
}
set {
if ((object.ReferenceEquals(this.READYFilesField, value) != true)) {
if ((ReferenceEquals(this.READYFilesField, value) != true)) {
this.READYFilesField = value;
this.RaisePropertyChanged("READYFiles");
}

View File

@ -3,9 +3,9 @@
//
using bsmd.database;
using ClosedXML.Excel;
using ENI2.EditControls;
using ENI2.Util;
using ExcelDataReader;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
@ -126,67 +126,72 @@ namespace ENI2.SheetDisplayControls
};
if (ofd.ShowDialog() ?? false)
{
FileStream stream;
try
{
using (var stream = new FileStream(ofd.FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var workbook = new XLWorkbook(stream))
{
var worksheet = workbook.Worksheet(1); // Get first worksheet
var rows = worksheet.RangeUsed().RowsUsed().Skip(1); // Skip header row if present
List<CREWD> importCrew = new List<CREWD>();
foreach (var row in rows)
{
if (row.RowNumber() > worksheet.RangeUsed().RowCount()) break;
// Check if we have at least 13 columns
if (worksheet.RangeUsed().ColumnCount() < 13)
{
throw new InvalidDataException("Sheet must have 13 columns of data");
}
CREWD crew = new CREWD();
crew.IsDeparture = true;
// Check if first two cells are empty
if (row.Cell(1).IsEmpty() && row.Cell(2).IsEmpty()) continue;
if (!row.Cell(1).IsEmpty()) crew.CrewMemberLastName = row.Cell(1).GetString().Clean();
if (crew.CrewMemberLastName?.Equals("Family Name") == true || string.IsNullOrWhiteSpace(crew.CrewMemberLastName)) continue;
if (!row.Cell(2).IsEmpty()) crew.CrewMemberFirstName = row.Cell(2).GetString().Clean();
if (!row.Cell(3).IsEmpty()) crew.CrewMemberGender = GlobalStructures.ParseGender(row.Cell(3).GetString());
if (!row.Cell(4).IsEmpty()) crew.CrewMemberDuty = row.Cell(4).GetString().Clean();
if (!row.Cell(5).IsEmpty()) crew.CrewMemberNationality = row.Cell(5).GetString().Substring(0, 2).ToUpper();
if (!row.Cell(6).IsEmpty()) crew.CrewMemberPlaceOfBirth = row.Cell(6).GetString().Clean();
if (!row.Cell(7).IsEmpty()) crew.CrewMemberCountryOfBirth = row.Cell(7).GetString().Substring(0, 2).ToUpper();
if (!row.Cell(8).IsEmpty()) crew.CrewMemberDateOfBirth = row.Cell(8).GetDateTime();
if (!row.Cell(9).IsEmpty()) crew.CrewMemberIdentityDocumentType = GlobalStructures.ReadIdentityDocumentType(row.Cell(9).GetString());
if (!row.Cell(10).IsEmpty()) crew.CrewMemberIdentityDocumentId = row.Cell(10).GetString().Clean();
if (!row.Cell(11).IsEmpty()) crew.CrewMemberIdentityDocumentIssuingState = row.Cell(11).GetString().Substring(0, 2).ToUpper();
if (!row.Cell(12).IsEmpty()) crew.CrewMemberIdentityDocumentExpiryDate = row.Cell(12).GetDateTime();
if (!row.Cell(13).IsEmpty()) crew.CrewMemberVisaNumber = row.Cell(13).GetString().Clean();
crew.MessageHeader = this._crewdMessage;
crew.IsDirty = true;
crew.Identifier = CREWD.GetNewIdentifier(this._crewdMessage.Elements);
this._crewdMessage.Elements.Add(crew);
importCrew.Add(crew);
}
if (importCrew.Count > 0)
{
this.dataGridCrewListDeparture.Items.Refresh();
this.SublistElementChanged(Message.NotificationClass.CREWD);
MessageBox.Show(String.Format(Properties.Resources.textCrewImported, importCrew.Count), Properties.Resources.textCaptionInformation, MessageBoxButton.OK, MessageBoxImage.Information);
}
}
stream = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read);
}
catch (Exception ex)
{
MessageBox.Show("Error reading Excel: " + ex.Message, Properties.Resources.textCaptionError, MessageBoxButton.OK, MessageBoxImage.Error);
MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
using (IExcelDataReader reader = ExcelReaderFactory.CreateReader(stream))
{
List<CREWD> importCrew = new List<CREWD>();
try
{
do
{
while (reader.Read())
{
if (reader.FieldCount < 13)
{
throw new InvalidDataException("Sheet must have 13 columns of data");
}
CREWD crew = new CREWD();
crew.IsDeparture = true;
if (reader.IsDBNull(0) && reader.IsDBNull(1)) continue;
if (!reader.IsDBNull(0)) crew.CrewMemberLastName = reader.GetString(0);
if (crew.CrewMemberLastName.Equals("Family Name") || (crew.CrewMemberLastName.Trim().Length == 0)) continue;
if (!reader.IsDBNull(1)) crew.CrewMemberFirstName = reader.GetString(1);
if (!reader.IsDBNull(2)) crew.CrewMemberGender = GlobalStructures.ParseGender(reader.GetString(2));
if (!reader.IsDBNull(3)) crew.CrewMemberDuty = reader.GetString(3).Clean();
if (!reader.IsDBNull(4)) crew.CrewMemberNationality = reader.GetString(4).Substring(0, 2).ToUpper();
if (!reader.IsDBNull(5)) crew.CrewMemberPlaceOfBirth = reader.GetString(5);
if (!reader.IsDBNull(6)) crew.CrewMemberCountryOfBirth = reader.GetString(6).Substring(0, 2).ToUpper();
if (!reader.IsDBNull(7)) crew.CrewMemberDateOfBirth = reader.GetDateTime(7);
if (!reader.IsDBNull(8)) crew.CrewMemberIdentityDocumentType = GlobalStructures.ReadIdentityDocumentType(reader.GetString(8));
if (!reader.IsDBNull(9)) crew.CrewMemberIdentityDocumentId = reader.ReadAsString(9);
if (!reader.IsDBNull(10)) crew.CrewMemberIdentityDocumentIssuingState = reader.GetString(10).Substring(0, 2).ToUpper();
if (!reader.IsDBNull(11)) crew.CrewMemberIdentityDocumentExpiryDate = reader.GetDateTime(11);
if (!reader.IsDBNull(12)) crew.CrewMemberVisaNumber = reader.ReadAsString(12);
crew.MessageHeader = this._crewdMessage;
crew.IsDirty = true;
crew.Identifier = CREWD.GetNewIdentifier(this._crewdMessage.Elements);
this._crewdMessage.Elements.Add(crew);
importCrew.Add(crew);
}
} while (reader.NextResult());
}
catch (Exception ex)
{
MessageBox.Show("Error reading Excel: " + ex.Message, Properties.Resources.textCaptionError, MessageBoxButton.OK, MessageBoxImage.Error);
}
if (importCrew.Count > 0)
{
this.dataGridCrewListDeparture.Items.Refresh();
this.SublistElementChanged(Message.NotificationClass.CREWD);
MessageBox.Show(String.Format(Properties.Resources.textCrewImported, importCrew.Count), Properties.Resources.textCaptionInformation, MessageBoxButton.OK, MessageBoxImage.Information);
}
}
stream.Close();
}
}

View File

@ -30,7 +30,6 @@
<Label HorizontalContentAlignment="Right" Grid.Row="0" Grid.Column="0" Content="{x:Static p:Resources.textNameMaster}" Name="label_nameMaster" Margin="0,0,10,0"/>
<TextBox Grid.Row="0" Grid.Column="1" Name="textBox_NameMaster" MaxLength="100" Margin="2" Text="{Binding NameOfMaster, Converter={util:TrimStringConverter}}" VerticalContentAlignment="Center" />
<Button Grid.Row="0" Grid.Column="2" Content="{x:Static p:Resources.textCopyFromCREWA}" Margin="2" Width="120" HorizontalAlignment="Left" x:Name="buttonCopyFromCrewA" Click="buttonCopyFromCrewA_Click" />
<Label Name="labelCrewNotificationSchengen" Content="{x:Static p:Resources.textNotificationSchengen}" Grid.Row="1" Grid.Column="0" HorizontalAlignment="Right"/>
<CheckBox Name="checkBoxCrewNotificationSchengen" Grid.Row="1" Grid.Column="1" IsThreeState="False" VerticalAlignment="Center" Margin="10,0,0,0" Click="checkBoxCrewNotificationSchengen_Click"/>
<Label Name="labelCrewNotificationPAX" Content="{x:Static p:Resources.textNotificationPAX}" Grid.Row="2" Grid.Column="0" HorizontalAlignment="Right" />

View File

@ -3,9 +3,9 @@
//
using bsmd.database;
using ClosedXML.Excel;
using ENI2.EditControls;
using ENI2.Util;
using ExcelDataReader;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
@ -166,91 +166,73 @@ namespace ENI2.SheetDisplayControls
};
if (ofd.ShowDialog() ?? false)
{
FileStream stream;
try
{
using (var stream = new FileStream(ofd.FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var workbook = new XLWorkbook(stream))
{
var worksheet = workbook.Worksheet(1); // Get first worksheet
var rows = worksheet.RangeUsed().RowsUsed().Skip(1); // Skip header row if present
List<CREW> importCrew = new List<CREW>();
foreach (var row in rows)
{
if (row.RowNumber() > worksheet.RangeUsed().RowCount()) break;
// Check if we have at least 13 columns
if (worksheet.RangeUsed().ColumnCount() < 13)
{
throw new InvalidDataException("Sheet must have 13 columns of data");
}
CREW crew = new CREW();
// Check if first two cells are empty
if (row.Cell(1).IsEmpty() && row.Cell(2).IsEmpty()) continue;
if (!row.Cell(1).IsEmpty()) crew.CrewMemberLastName = row.Cell(1).GetString().Clean();
if (crew.CrewMemberLastName?.Equals("Family Name") == true || string.IsNullOrWhiteSpace(crew.CrewMemberLastName)) continue;
if (!row.Cell(2).IsEmpty()) crew.CrewMemberFirstName = row.Cell(2).GetString().Clean();
if (!row.Cell(3).IsEmpty()) crew.CrewMemberGender = GlobalStructures.ParseGender(row.Cell(3).GetString());
if (!row.Cell(4).IsEmpty()) crew.CrewMemberDuty = row.Cell(4).GetString().Clean();
if (!row.Cell(5).IsEmpty()) crew.CrewMemberNationality = row.Cell(5).GetString().Substring(0, 2).ToUpper();
if (!row.Cell(6).IsEmpty()) crew.CrewMemberPlaceOfBirth = row.Cell(6).GetString().Clean();
if (!row.Cell(7).IsEmpty()) crew.CrewMemberCountryOfBirth = row.Cell(7).GetString().Substring(0, 2).ToUpper();
if (!row.Cell(8).IsEmpty()) crew.CrewMemberDateOfBirth = row.Cell(8).GetDateTime();
if (!row.Cell(9).IsEmpty()) crew.CrewMemberIdentityDocumentType = GlobalStructures.ReadIdentityDocumentType(row.Cell(9).GetString());
if (!row.Cell(10).IsEmpty()) crew.CrewMemberIdentityDocumentId = row.Cell(10).GetString().Clean();
if (!row.Cell(11).IsEmpty()) crew.CrewMemberIdentityDocumentIssuingState = row.Cell(11).GetString().Substring(0, 2).ToUpper();
if (!row.Cell(12).IsEmpty()) crew.CrewMemberIdentityDocumentExpiryDate = row.Cell(12).GetDateTime();
if (!row.Cell(13).IsEmpty()) crew.CrewMemberVisaNumber = row.Cell(13).GetString().Clean();
crew.MessageHeader = this._crewaMessage;
crew.IsDirty = true;
crew.Identifier = CREW.GetNewIdentifier(this._crewaMessage.Elements);
this._crewaMessage.Elements.Add(crew);
importCrew.Add(crew);
}
if (importCrew.Count > 0)
{
this.dataGridCrewList.Items.Refresh();
this.SublistElementChanged(Message.NotificationClass.CREWA);
MessageBox.Show(String.Format(Properties.Resources.textCrewImported, importCrew.Count), Properties.Resources.textCaptionInformation, MessageBoxButton.OK, MessageBoxImage.Information);
}
}
stream = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read);
}
catch (Exception ex)
{
MessageBox.Show("Error reading Excel: " + ex.Message, Properties.Resources.textCaptionError, MessageBoxButton.OK, MessageBoxImage.Error);
MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
using (IExcelDataReader reader = ExcelReaderFactory.CreateReader(stream))
{
List<CREW> importCrew = new List<CREW>();
try
{
do
{
while (reader.Read())
{
if (reader.FieldCount < 13)
{
throw new InvalidDataException("Sheet must have 13 columns of data");
}
CREW crew = new CREW();
if (reader.IsDBNull(0) && reader.IsDBNull(1)) continue;
if (!reader.IsDBNull(0)) crew.CrewMemberLastName = reader.GetString(0).Clean();
if (crew.CrewMemberLastName.Equals("Family Name") || (crew.CrewMemberLastName.Trim().Length == 0)) continue;
if (!reader.IsDBNull(1)) crew.CrewMemberFirstName = reader.GetString(1).Clean();
if (!reader.IsDBNull(2)) crew.CrewMemberGender = GlobalStructures.ParseGender(reader.GetString(2));
if (!reader.IsDBNull(3)) crew.CrewMemberDuty = reader.GetString(3).Clean();
if (!reader.IsDBNull(4)) crew.CrewMemberNationality = reader.GetString(4).Substring(0, 2).ToUpper();
if (!reader.IsDBNull(5)) crew.CrewMemberPlaceOfBirth = reader.GetString(5).Clean();
if (!reader.IsDBNull(6)) crew.CrewMemberCountryOfBirth = reader.GetString(6).Substring(0, 2).ToUpper();
if (!reader.IsDBNull(7)) crew.CrewMemberDateOfBirth = reader.GetDateTime(7);
if (!reader.IsDBNull(8)) crew.CrewMemberIdentityDocumentType = GlobalStructures.ReadIdentityDocumentType(reader.GetString(8));
if (!reader.IsDBNull(9)) crew.CrewMemberIdentityDocumentId = reader.ReadAsString(9).Clean();
if (!reader.IsDBNull(10)) crew.CrewMemberIdentityDocumentIssuingState = reader.GetString(10).Substring(0, 2).ToUpper();
if (!reader.IsDBNull(11)) crew.CrewMemberIdentityDocumentExpiryDate = reader.GetDateTime(11);
if (!reader.IsDBNull(12)) crew.CrewMemberVisaNumber = reader.ReadAsString(12).Clean();
crew.MessageHeader = this._crewaMessage;
crew.IsDirty = true;
crew.Identifier = CREW.GetNewIdentifier(this._crewaMessage.Elements);
this._crewaMessage.Elements.Add(crew);
importCrew.Add(crew);
}
} while (reader.NextResult());
}
catch (Exception ex)
{
MessageBox.Show("Error reading Excel: " + ex.Message, Properties.Resources.textCaptionError, MessageBoxButton.OK, MessageBoxImage.Error);
}
if (importCrew.Count > 0)
{
this.dataGridCrewList.Items.Refresh();
this.SublistElementChanged(Message.NotificationClass.CREWA);
MessageBox.Show(String.Format(Properties.Resources.textCrewImported, importCrew.Count), Properties.Resources.textCaptionInformation, MessageBoxButton.OK, MessageBoxImage.Information);
}
}
stream.Close();
}
}
private void buttonCopyFromCrewA_Click(object sender, RoutedEventArgs e)
{
CREW crewA = null;
if (this._crewaMessage.Elements.Count > 0)
{
crewA = this._crewaMessage.Elements[0] as CREW;
}
SelectCrewMemberDialog scmd = new SelectCrewMemberDialog();
scmd.CREW = crewA;
scmd.AddVisible = false;
if (scmd.ShowDialog() ?? false)
{
this.textBox_NameMaster.Text = $"{crewA.CrewMemberFirstName} {crewA.CrewMemberLastName}";
this.SublistElementChanged(Message.NotificationClass.NAME);
var binding = textBox_NameMaster.GetBindingExpression(TextBox.TextProperty);
binding?.UpdateSource();
}
}
#endregion
#region crew grid arrival
@ -396,10 +378,8 @@ namespace ENI2.SheetDisplayControls
}
}
#endregion
}
}

View File

@ -3,10 +3,10 @@
//
using bsmd.database;
using ClosedXML.Excel;
using ENI2.EditControls;
using ENI2.Locode;
using ENI2.Util;
using ExcelDataReader;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
@ -144,72 +144,78 @@ namespace ENI2.SheetDisplayControls
};
if (ofd.ShowDialog() ?? false)
{
FileStream stream;
try
{
using (var stream = new FileStream(ofd.FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var workbook = new XLWorkbook(stream))
{
var worksheet = workbook.Worksheet(1); // Get first worksheet
var rows = worksheet.RangeUsed().RowsUsed().Skip(1); // Skip header row if present
List<PASD> importPassenger = new List<PASD>();
foreach (var row in rows)
{
if (row.RowNumber() > worksheet.RangeUsed().RowCount()) break;
if (worksheet.RangeUsed().ColumnCount() < 17)
{
throw new InvalidDataException("Sheet must have 17 columns of data");
}
PASD pas = new PASD();
if (row.Cell(1).IsEmpty() && row.Cell(2).IsEmpty()) continue;
if (!row.Cell(1).IsEmpty()) pas.PassengerLastName = row.Cell(1).GetString().Clean();
if (pas.PassengerLastName?.Equals("Family Name") == true || string.IsNullOrWhiteSpace(pas.PassengerLastName)) continue;
if (!row.Cell(2).IsEmpty()) pas.PassengerFirstName = row.Cell(2).GetString().Clean();
if (!row.Cell(3).IsEmpty()) pas.PassengerGender = GlobalStructures.ParseGender(row.Cell(3).GetString());
if (!row.Cell(4).IsEmpty()) pas.PassengerPortOfEmbarkation = row.Cell(4).GetString().Clean();
if (LocodeDB.PortNameFromLocode(pas.PassengerPortOfEmbarkation) == null)
pas.PassengerPortOfEmbarkation = null;
if (!row.Cell(5).IsEmpty()) pas.PassengerPortOfDisembarkation = row.Cell(5).GetString().Clean();
if (LocodeDB.PortNameFromLocode(pas.PassengerPortOfDisembarkation) == null)
pas.PassengerPortOfDisembarkation = null;
if (!row.Cell(6).IsEmpty()) pas.PassengerInTransit = GlobalStructures.ReadBoolean(row.Cell(6).GetString());
if (!row.Cell(7).IsEmpty()) pas.PassengerNationality = row.Cell(7).GetString().Substring(0, 2).ToUpper();
if (!row.Cell(8).IsEmpty()) pas.PassengerPlaceOfBirth = row.Cell(8).GetString().Clean();
if (!row.Cell(9).IsEmpty()) pas.PassengerCountryOfBirth = row.Cell(9).GetString().Substring(0, 2).ToUpper();
if (!row.Cell(10).IsEmpty()) pas.PassengerDateOfBirth = row.Cell(10).GetDateTime();
if (!row.Cell(11).IsEmpty()) pas.PassengerIdentityDocumentType = GlobalStructures.ReadIdentityDocumentType(row.Cell(11).GetString());
if (!row.Cell(12).IsEmpty()) pas.PassengerIdentityDocumentId = row.Cell(12).GetString().Clean();
if (!row.Cell(13).IsEmpty()) pas.PassengerIdentityDocumentIssuingState = row.Cell(13).GetString().Substring(0, 2).ToUpper();
if (!row.Cell(14).IsEmpty()) pas.PassengerIdentityDocumentExpiryDate = row.Cell(14).GetDateTime();
if (!row.Cell(15).IsEmpty()) pas.PassengerVisaNumber = row.Cell(15).GetString().Clean();
if (!row.Cell(16).IsEmpty()) pas.EmergencyCare = row.Cell(16).GetString().Clean();
if (!row.Cell(17).IsEmpty()) pas.EmergencyContactNumber = row.Cell(17).GetString().Clean();
pas.MessageHeader = this._pasdMessage;
pas.IsDirty = true;
pas.Identifier = PASD.GetNewIdentifier(this._pasdMessage.Elements);
this._pasdMessage.Elements.Add(pas);
importPassenger.Add(pas);
}
if (importPassenger.Count > 0)
{
this.dataGridPassengerListDeparture.Items.Refresh();
this.SublistElementChanged(Message.NotificationClass.PASD);
MessageBox.Show(String.Format(Properties.Resources.textPassengerImported, importPassenger.Count), Properties.Resources.textCaptionInformation, MessageBoxButton.OK, MessageBoxImage.Information);
}
}
stream = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read);
}
catch (Exception ex)
{
MessageBox.Show("Error reading Excel: " + ex.Message, Properties.Resources.textCaptionError, MessageBoxButton.OK, MessageBoxImage.Error);
MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
List<PASD> importPassenger = new List<PASD>();
try
{
do
{
while (reader.Read())
{
if (((IExcelDataReader)reader).FieldCount < 17)
{
throw new InvalidDataException("Sheet must have 17 columns of data");
}
PASD pas = new PASD();
if (reader.IsDBNull(0) && reader.IsDBNull(1)) continue;
if (!reader.IsDBNull(0)) pas.PassengerLastName = reader.GetValue(0).ToString();
if (pas.PassengerLastName.Equals("Family Name") || (pas.PassengerLastName.Trim().Length == 0)) continue;
if (!reader.IsDBNull(1)) pas.PassengerFirstName = reader.GetValue(1).ToString();
if (!reader.IsDBNull(2)) pas.PassengerGender = GlobalStructures.ParseGender(reader.GetString(2));
if (!reader.IsDBNull(3)) pas.PassengerPortOfEmbarkation = reader.GetString(3);
if (LocodeDB.PortNameFromLocode(pas.PassengerPortOfEmbarkation) == null)
pas.PassengerPortOfEmbarkation = null;
if (!reader.IsDBNull(4)) pas.PassengerPortOfDisembarkation = reader.GetString(4);
if (LocodeDB.PortNameFromLocode(pas.PassengerPortOfDisembarkation) == null)
pas.PassengerPortOfDisembarkation = null;
if (!reader.IsDBNull(5)) pas.PassengerInTransit = GlobalStructures.ReadBoolean(reader.GetString(5));
if (!reader.IsDBNull(6)) pas.PassengerNationality = reader.GetString(6).Substring(0, 2).ToUpper();
if (!reader.IsDBNull(7)) pas.PassengerPlaceOfBirth = reader.GetString(7);
if (!reader.IsDBNull(8)) pas.PassengerCountryOfBirth = reader.GetString(8).Substring(0, 2).ToUpper();
if (!reader.IsDBNull(9)) pas.PassengerDateOfBirth = reader.GetDateTime(9);
if (!reader.IsDBNull(10)) pas.PassengerIdentityDocumentType = GlobalStructures.ReadIdentityDocumentType(reader.GetString(10));
if (!reader.IsDBNull(11)) pas.PassengerIdentityDocumentId = reader.ReadAsString( 11);
if (!reader.IsDBNull(12)) pas.PassengerIdentityDocumentIssuingState = reader.GetString(12).Substring(0, 2).ToUpper();
if (!reader.IsDBNull(13)) pas.PassengerIdentityDocumentExpiryDate = reader.GetDateTime(13);
if (!reader.IsDBNull(14)) pas.PassengerVisaNumber = reader.ReadAsString(14);
if (!reader.IsDBNull(15)) pas.EmergencyCare = reader.GetString(15);
if (!reader.IsDBNull(16)) pas.EmergencyContactNumber = reader.ReadAsString(16);
pas.MessageHeader = this._pasMessage;
pas.IsDirty = true;
pas.Identifier = PASD.GetNewIdentifier(this._pasdMessage.Elements);
this._pasdMessage.Elements.Add(pas);
importPassenger.Add(pas);
}
} while (reader.NextResult());
}
catch (Exception ex)
{
MessageBox.Show("Error reading Excel: " + ex.Message, Properties.Resources.textCaptionError, MessageBoxButton.OK, MessageBoxImage.Error);
}
if (importPassenger.Count > 0)
{
this.dataGridPassengerListDeparture.Items.Refresh();
this.SublistElementChanged(Message.NotificationClass.PASD);
MessageBox.Show(String.Format(Properties.Resources.textPassengerImported, importPassenger.Count), Properties.Resources.textCaptionInformation, MessageBoxButton.OK, MessageBoxImage.Information);
}
}
stream.Close();
}
}

View File

@ -4,10 +4,10 @@
//
using bsmd.database;
using ClosedXML.Excel;
using ENI2.EditControls;
using ENI2.Locode;
using ENI2.Util;
using ExcelDataReader;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
@ -126,72 +126,78 @@ namespace ENI2.SheetDisplayControls
};
if (ofd.ShowDialog() ?? false)
{
FileStream stream;
try
{
using (var stream = new FileStream(ofd.FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var workbook = new XLWorkbook(stream))
{
var worksheet = workbook.Worksheet(1); // Get first worksheet
var rows = worksheet.RangeUsed().RowsUsed().Skip(1); // Skip header row if present
List<PAS> importPassenger = new List<PAS>();
foreach (var row in rows)
{
if (row.RowNumber() > worksheet.RangeUsed().RowCount()) break;
if (worksheet.RangeUsed().ColumnCount() < 17)
{
throw new InvalidDataException("Sheet must have 17 columns of data");
}
PAS pas = new PAS();
if (row.Cell(1).IsEmpty() && row.Cell(2).IsEmpty()) continue;
if (!row.Cell(1).IsEmpty()) pas.PassengerLastName = row.Cell(1).GetString().Clean();
if (pas.PassengerLastName?.Equals("Family Name") == true || string.IsNullOrWhiteSpace(pas.PassengerLastName)) continue;
if (!row.Cell(2).IsEmpty()) pas.PassengerFirstName = row.Cell(2).GetString().Clean();
if (!row.Cell(3).IsEmpty()) pas.PassengerGender = GlobalStructures.ParseGender(row.Cell(3).GetString());
if (!row.Cell(4).IsEmpty()) pas.PassengerPortOfEmbarkation = row.Cell(4).GetString().Clean();
if (LocodeDB.PortNameFromLocode(pas.PassengerPortOfEmbarkation) == null)
pas.PassengerPortOfEmbarkation = null;
if (!row.Cell(5).IsEmpty()) pas.PassengerPortOfDisembarkation = row.Cell(5).GetString().Clean();
if (LocodeDB.PortNameFromLocode(pas.PassengerPortOfDisembarkation) == null)
pas.PassengerPortOfDisembarkation = null;
if (!row.Cell(6).IsEmpty()) pas.PassengerInTransit = GlobalStructures.ReadBoolean(row.Cell(6).GetString());
if (!row.Cell(7).IsEmpty()) pas.PassengerNationality = row.Cell(7).GetString().Substring(0, 2).ToUpper();
if (!row.Cell(8).IsEmpty()) pas.PassengerPlaceOfBirth = row.Cell(8).GetString().Clean();
if (!row.Cell(9).IsEmpty()) pas.PassengerCountryOfBirth = row.Cell(9).GetString().Substring(0, 2).ToUpper().Clean();
if (!row.Cell(10).IsEmpty()) pas.PassengerDateOfBirth = row.Cell(10).GetDateTime();
if (!row.Cell(11).IsEmpty()) pas.PassengerIdentityDocumentType = GlobalStructures.ReadIdentityDocumentType(row.Cell(11).GetString());
if (!row.Cell(12).IsEmpty()) pas.PassengerIdentityDocumentId = row.Cell(12).GetString().Clean();
if (!row.Cell(13).IsEmpty()) pas.PassengerIdentityDocumentIssuingState = row.Cell(13).GetString().Substring(0, 2).ToUpper();
if (!row.Cell(14).IsEmpty()) pas.PassengerIdentityDocumentExpiryDate = row.Cell(14).GetDateTime();
if (!row.Cell(15).IsEmpty()) pas.PassengerVisaNumber = row.Cell(15).GetString().Clean();
if (!row.Cell(16).IsEmpty()) pas.EmergencyCare = row.Cell(16).GetString().Clean();
if (!row.Cell(17).IsEmpty()) pas.EmergencyContactNumber = row.Cell(17).GetString().Clean();
pas.MessageHeader = this._pasMessage;
pas.IsDirty = true;
pas.Identifier = PAS.GetNewIdentifier(this._pasMessage.Elements);
this._pasMessage.Elements.Add(pas);
importPassenger.Add(pas);
}
if (importPassenger.Count > 0)
{
this.dataGridPassengerList.Items.Refresh();
this.SublistElementChanged(Message.NotificationClass.PASA);
MessageBox.Show(String.Format(Properties.Resources.textPassengerImported, importPassenger.Count), Properties.Resources.textCaptionInformation, MessageBoxButton.OK, MessageBoxImage.Information);
}
}
stream = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read);
}
catch (Exception ex)
{
MessageBox.Show("Error reading Excel: " + ex.Message, Properties.Resources.textCaptionError, MessageBoxButton.OK, MessageBoxImage.Error);
MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
List<PAS> importPassenger = new List<PAS>();
try
{
do
{
while (reader.Read())
{
if (((IExcelDataReader)reader).FieldCount < 17)
{
throw new InvalidDataException("Sheet must have 17 columns of data");
}
PAS pas = new PAS();
if (reader.IsDBNull(0) && reader.IsDBNull(1)) continue;
if (!reader.IsDBNull(0)) pas.PassengerLastName = reader.GetValue(0).ToString().Clean();
if (pas.PassengerLastName.Equals("Family Name") || (pas.PassengerLastName.Trim().Length == 0)) continue;
if (!reader.IsDBNull(1)) pas.PassengerFirstName = reader.GetValue(1).ToString().Clean();
if (!reader.IsDBNull(2)) pas.PassengerGender = GlobalStructures.ParseGender(reader.GetString(2));
if (!reader.IsDBNull(3)) pas.PassengerPortOfEmbarkation = reader.GetString(3).Clean();
if (LocodeDB.PortNameFromLocode(pas.PassengerPortOfEmbarkation) == null)
pas.PassengerPortOfEmbarkation = null;
if (!reader.IsDBNull(4)) pas.PassengerPortOfDisembarkation = reader.GetString(4).Clean();
if (LocodeDB.PortNameFromLocode(pas.PassengerPortOfDisembarkation) == null)
pas.PassengerPortOfDisembarkation = null;
if (!reader.IsDBNull(5)) pas.PassengerInTransit = GlobalStructures.ReadBoolean(reader.GetString(5));
if (!reader.IsDBNull(6)) pas.PassengerNationality = reader.GetString(6).Substring(0, 2).ToUpper();
if (!reader.IsDBNull(7)) pas.PassengerPlaceOfBirth = reader.GetString(7).Clean();
if (!reader.IsDBNull(8)) pas.PassengerCountryOfBirth = reader.GetString(8).Substring(0, 2).ToUpper().Clean();
if (!reader.IsDBNull(9)) pas.PassengerDateOfBirth = reader.GetDateTime(9);
if (!reader.IsDBNull(10)) pas.PassengerIdentityDocumentType = GlobalStructures.ReadIdentityDocumentType(reader.GetString(10));
if (!reader.IsDBNull(11)) pas.PassengerIdentityDocumentId = reader.ReadAsString(11).Clean();
if (!reader.IsDBNull(12)) pas.PassengerIdentityDocumentIssuingState = reader.GetString(12).Substring(0, 2).ToUpper();
if (!reader.IsDBNull(13)) pas.PassengerIdentityDocumentExpiryDate = reader.GetDateTime(13);
if (!reader.IsDBNull(14)) pas.PassengerVisaNumber = reader.ReadAsString(14).Clean();
if (!reader.IsDBNull(15)) pas.EmergencyCare = reader.GetString(15).Clean();
if (!reader.IsDBNull(16)) pas.EmergencyContactNumber = reader.ReadAsString(16).Clean();
pas.MessageHeader = this._pasMessage;
pas.IsDirty = true;
pas.Identifier = PAS.GetNewIdentifier(this._pasMessage.Elements);
this._pasMessage.Elements.Add(pas);
importPassenger.Add(pas);
}
} while (reader.NextResult());
}
catch (Exception ex)
{
MessageBox.Show("Error reading Excel: " + ex.Message, Properties.Resources.textCaptionError, MessageBoxButton.OK, MessageBoxImage.Error);
}
if (importPassenger.Count > 0)
{
this.dataGridPassengerList.Items.Refresh();
this.SublistElementChanged(Message.NotificationClass.PASA);
MessageBox.Show(String.Format(Properties.Resources.textPassengerImported, importPassenger.Count), Properties.Resources.textCaptionInformation, MessageBoxButton.OK, MessageBoxImage.Information);
}
}
stream.Close();
}
}

View File

@ -88,14 +88,13 @@
<TabItem Header="{x:Static p:Resources.textTab22}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="190"/>
<ColumnDefinition Width="120"/>
<ColumnDefinition Width=".3*" />
<ColumnDefinition Width=".3*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="36" />
<RowDefinition Height="28" />
<RowDefinition Height="1" />
<RowDefinition Height="28" />
<RowDefinition Height="28" />
<RowDefinition Height="28" />
@ -126,18 +125,20 @@
<Label HorizontalContentAlignment="Right" Grid.Row="10" Grid.Column="0" Content="{x:Static p:Resources.textEMail}" Name="label_AgentEMail" Margin="0,0,10,0" />
<Label HorizontalContentAlignment="Right" Grid.Row="11" Grid.Column="0" Content="{x:Static p:Resources.textLastName}" Name="label_AgentLastName" Margin="0,0,10,0"/>
<Label HorizontalContentAlignment="Right" Grid.Row="12" Grid.Column="0" Content="{x:Static p:Resources.textFirstName}" Name="label_AgentFirstName" Margin="0,0,10,0"/>
<Label HorizontalContentAlignment="Right" Grid.Row="13" Grid.Column="0" Content="{x:Static p:Resources.textWasteDisposalServiceProvider}" Name="label_WasteDisposalServiceProvider" Margin="0,0,10,0"/>
<ComboBox Grid.Row="1" Grid.Column="1" Name="comboBox_AgentTemplate" Margin="2" SelectedValuePath="Id" DisplayMemberPath="AgentTitle" SelectionChanged="comboBox_AgentTemplate_SelectionChanged" />
<Grid Grid.Column="0" Grid.Row="2" HorizontalAlignment="Right">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="26" />
</Grid.ColumnDefinitions>
<Button Name="buttonSetTemplate" Margin="2" Click="buttonSetTemplate_Click" BorderThickness="0" Background="Transparent" ToolTip="Apply template" HorizontalContentAlignment="Right" IsEnabled="False">
<StackPanel Orientation="Horizontal">
<Image Source="../Resources/check.png" Margin="0,0,0,0" Height="20" Width="20" />
</StackPanel>
</Button>
</Grid>
<Grid Grid.Row="1" Grid.Column="2" Name="gridTemplateControls" Visibility="Visible">
<Grid Grid.Row="2" Grid.Column="1" Name="gridTemplateControls" Visibility="Visible">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="26" />
<ColumnDefinition Width="*"/>
<!-- Name -->
<ColumnDefinition Width="26"/>
@ -147,23 +148,18 @@
<ColumnDefinition Width="52"/>
<!-- Undo button -->
</Grid.ColumnDefinitions>
<Button Name="buttonSetTemplate" Grid.Column="0" Margin="2" Click="buttonSetTemplate_Click" BorderThickness="0" Background="Transparent" ToolTip="Apply template" HorizontalContentAlignment="Right" IsEnabled="False">
<StackPanel Orientation="Horizontal">
<Image Source="../Resources/check.png" Margin="0,0,0,0" Height="20" Width="20" />
</StackPanel>
</Button>
<TextBox Grid.Column="1" Margin="2" Name="textBoxTemplateTitle" VerticalContentAlignment="Center"/>
<Button Name="buttonSaveTemplate" Grid.Column="2" Grid.Row="0" Margin="2" Click="buttonSaveTemplate_Click" BorderThickness="0" Background="Transparent" ToolTip="Save template">
<TextBox Grid.Column="0" Margin="2" Name="textBoxTemplateTitle" VerticalContentAlignment="Center"/>
<Button Name="buttonSaveTemplate" Grid.Column="1" Grid.Row="0" Margin="2" Click="buttonSaveTemplate_Click" BorderThickness="0" Background="Transparent" ToolTip="Save template">
<StackPanel Orientation="Horizontal">
<Image Source="../Resources/floppy_disk_blue.png" Margin="0,0,0,0" Height="20" Width="20" />
</StackPanel>
</Button>
<Button Name="buttonDeleteTemplate" Grid.Column="3" Grid.Row="0" Margin="2" Click="buttonDeleteTemplate_Click" BorderThickness="0" Background="Transparent" ToolTip="Delete template" IsEnabled="False">
<Button Name="buttonDeleteTemplate" Grid.Column="2" Grid.Row="0" Margin="2" Click="buttonDeleteTemplate_Click" BorderThickness="0" Background="Transparent" ToolTip="Delete template" IsEnabled="False">
<StackPanel Orientation="Horizontal">
<Image Source="../Resources/delete.png" Margin="0,0,0,0" Height="20" Width="20" />
</StackPanel>
</Button>
<Button Name="buttonUndoTemplate" Grid.Column="4" Grid.Row="0" Margin="22,2,2,2" Click="buttonUndoTemplate_Click" BorderThickness="0" Background="Transparent" ToolTip="Undo last overwrite" IsEnabled="False">
<Button Name="buttonUndoTemplate" Grid.Column="3" Grid.Row="0" Margin="22,2,2,2" Click="buttonUndoTemplate_Click" BorderThickness="0" Background="Transparent" ToolTip="Undo last overwrite" IsEnabled="False">
<StackPanel Orientation="Horizontal">
<Image Source="../Resources/undo.png" Margin="0,0,0,0" Height="20" Width="20" />
</StackPanel>
@ -180,44 +176,11 @@
<TextBox Grid.Row="10" Grid.Column="1" Name="textBox_AgentEMail" MaxLength="99" Margin="2" Text="{Binding AgentEMail, Converter={util:TrimStringConverter}}" VerticalContentAlignment="Center"/>
<TextBox Grid.Row="11" Grid.Column="1" Name="textBox_AgentLastName" MaxLength="99" Margin="2" Text="{Binding AgentLastName, Converter={util:TrimStringConverter}}" VerticalContentAlignment="Center"/>
<TextBox Grid.Row="12" Grid.Column="1" Name="textBox_AgentFirstName" MaxLength="99" Margin="2" Text="{Binding AgentFirstName, Converter={util:TrimStringConverter}}" VerticalContentAlignment="Center"/>
<TextBox Grid.Row="13" Grid.Column="1" Name="textBox_WasteDisposalServiceProvider" MaxLength="99" Margin="2" Text="{Binding WasteDisposalServiceProviderText, Converter={util:TrimStringConverter}}" VerticalContentAlignment="Center"/>
<TextBlock FontSize="18" VerticalAlignment="Bottom" Text="{x:Static p:Resources.text24Invoice}" Grid.Column="0" Grid.Row="14" Grid.ColumnSpan="3"/>
<Label HorizontalContentAlignment="Right" Grid.Row="15" Grid.Column="0" Content="{x:Static p:Resources.textSERVTemplate}" Name="label_MaerskSeaGo" VerticalContentAlignment="Center" Margin="0,0,10,0"/>
<ComboBox Grid.Row="15" Grid.Column="1" x:Name="comboBoxGroup" DisplayMemberPath="ServiceName" Margin="2" SelectionChanged="comboBoxGroup_SelectionChanged" ContextMenu="{DynamicResource ClearContextMenu}" />
<Grid Grid.Row="15" Grid.Column="2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="26" />
<ColumnDefinition Width="26" />
<ColumnDefinition Width="26" />
<ColumnDefinition Width="26" />
<ColumnDefinition Width="26" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Button Name="buttonSetSERVTemplate" Margin="2" Click="buttonSetSERVTemplate_Click" BorderThickness="0" Background="Transparent" Grid.Column="0"
ToolTip="Apply template" HorizontalContentAlignment="Right" IsEnabled="False">
<StackPanel Orientation="Horizontal">
<Image Source="../Resources/check.png" Margin="0,0,0,0" Height="20" Width="20" />
</StackPanel>
</Button>
<Button Name="buttonEditSERVTemplate" Grid.Column="2" Grid.Row="0" Margin="2" Click="buttonEditSERVTemplate_Click" BorderThickness="0" Background="Transparent" ToolTip="Edit template">
<StackPanel Orientation="Horizontal">
<Image Source="../Resources/pencil.png" Margin="0,0,0,0" Height="20" Width="20" />
</StackPanel>
</Button>
<Button Name="buttonNewSERVTemplate" Grid.Column="3" Grid.Row="0" Margin="2" Click="buttonNewSERVTemplate_Click" BorderThickness="0" Background="Transparent" ToolTip="New template">
<StackPanel Orientation="Horizontal">
<Image Source="../Resources/document_plain_new.png" Margin="0,0,0,0" Height="20" Width="20" />
</StackPanel>
</Button>
<Button Name="buttonDeleteSERVTemplate" Grid.Column="4" Grid.Row="0" Margin="2" Click="buttonDeleteSERVTemplate_Click" BorderThickness="0" Background="Transparent" ToolTip="Delete template" IsEnabled="False">
<StackPanel Orientation="Horizontal">
<Image Source="../Resources/delete.png" Margin="0,0,0,0" Height="20" Width="20" />
</StackPanel>
</Button>
</Grid>
<GroupBox Name="servGroupBox" Header="{x:Static p:Resources.textServ}" Grid.Row="16" Grid.Column="0" Grid.ColumnSpan="3">
<TextBlock FontSize="18" VerticalAlignment="Bottom" Text="{x:Static p:Resources.text24Invoice}" Grid.Column="0" Grid.Row="13" Grid.ColumnSpan="3"/>
<Label HorizontalContentAlignment="Right" Grid.Row="14" Grid.Column="0" Content="{x:Static p:Resources.textMaerskSeago}" Name="label_MaerskSeaGo" VerticalContentAlignment="Center" Margin="0,0,10,0"/>
<ComboBox Grid.Row="14" Grid.Column="1" x:Name="comboBoxGroup" Margin="2" ItemsSource="{StaticResource arrList}" DisplayMemberPath="Key" SelectedValuePath="Value" SelectionChanged="comboBoxGroup_SelectionChanged" ContextMenu="{DynamicResource ClearContextMenu}" />
<GroupBox Name="servGroupBox" Header="{x:Static p:Resources.textServ}" Grid.Row="15" Grid.Column="0" Grid.ColumnSpan="3">
<enictrl:ENIDataGrid x:Name="dataGridSERV" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch"
AutoGenerateColumns="False" Margin="0,5,0,0">
<DataGrid.Columns>
@ -317,7 +280,7 @@
<RowDefinition Height="28" />
<RowDefinition Height="28" />
<RowDefinition Height="56" />
<RowDefinition Height="28" />
<RowDefinition Height="56" />
<RowDefinition Height="530" />
<RowDefinition Height="28" />
@ -343,7 +306,7 @@
</DatePicker.BlackoutDates>
</DatePicker>
<TextBox Grid.Row="5" Grid.Column="1" Grid.ColumnSpan="2" Grid.RowSpan="1" Name="textBoxWasteDisposalServiceProviders" Text="{Binding WasteDisposalServiceProviderText, Converter={util:TrimStringConverter}}" Margin="2" />
<!-- Label Grid.Row="6" Grid.Column="0" HorizontalContentAlignment="Right" Content="{x:Static p:Resources.textAgentTemplate}" Margin="0,0,10,0" / -->
<Label Grid.Row="6" Grid.Column="0" HorizontalContentAlignment="Right" Content="{x:Static p:Resources.textAgentTemplate}" Margin="0,0,10,0" />
<Grid Grid.Row="6" Grid.Column="1" Grid.ColumnSpan="2" x:Name="gridWasteControls">
<Grid.ColumnDefinitions>
<ColumnDefinition Width=".25*" />
@ -352,13 +315,39 @@
<ColumnDefinition Width=".25*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<!-- RowDefinition Height="28" / -->
<RowDefinition Height="28" />
<RowDefinition Height="28" />
</Grid.RowDefinitions>
<ComboBox Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2" Name="comboBox_WSDPTemplate" Margin="2" SelectedValuePath="Id" DisplayMemberPath="Remark" SelectionChanged="comboBox_WSDPTemplate_SelectionChanged" />
<Grid Grid.Row="0" Grid.Column="2" Grid.ColumnSpan="2" Name="gridWasteTemplateControls" Visibility="Visible">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<!-- Name -->
<ColumnDefinition Width="26"/>
<!-- Save button -->
<ColumnDefinition Width="26"/>
<!-- Delete button -->
<ColumnDefinition Width="52"/>
<!-- Undo button -->
</Grid.ColumnDefinitions>
<TextBox Grid.Column="0" Margin="2" Name="textBoxWasteTemplateTitle" VerticalContentAlignment="Center"/>
<Button Name="buttonSaveWasteTemplate" Grid.Column="1" Grid.Row="0" Margin="2" Click="buttonSaveWasteTemplate_Click" BorderThickness="0" Background="Transparent" ToolTip="Save template">
<StackPanel Orientation="Horizontal">
<Image Source="../Resources/floppy_disk_blue.png" Margin="0,0,0,0" Height="20" Width="20" />
</StackPanel>
</Button>
<Button Name="buttonDeleteWasteTemplate" Grid.Column="2" Grid.Row="0" Margin="2" Click="buttonDeleteWasteTemplate_Click" BorderThickness="0" Background="Transparent" ToolTip="Delete template" IsEnabled="False">
<StackPanel Orientation="Horizontal">
<Image Source="../Resources/delete.png" Margin="0,0,0,0" Height="20" Width="20" />
</StackPanel>
</Button>
<Button Name="buttonUndoWasteTemplate" Grid.Column="3" Grid.Row="0" Margin="22,2,2,2" Click="buttonUndoWasteTemplate_Click" BorderThickness="0" Background="Transparent" ToolTip="Undo last overwrite" IsEnabled="False">
<StackPanel Orientation="Horizontal">
<Image Source="../Resources/undo.png" Margin="0,0,0,0" Height="20" Width="20" />
</StackPanel>
</Button>
</Grid>
<Button Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="1" Name="buttonAddMissingEntries" Content="{x:Static p:Resources.textAddMissingEntries}" Margin="2" Click="buttonAddMissingEntries_Click"/>
<Button Grid.Row="1" Grid.Column="1" Grid.ColumnSpan="1" Name="buttonImportFromExcel" Content="{x:Static p:Resources.textImportFromExcel}" Margin="2" Click="buttonImportFromExcel_Click" />
</Grid>

View File

@ -3,12 +3,11 @@
//
using bsmd.database;
using ClosedXML.Excel;
using ENI2.EditControls;
using ENI2.Excel;
using ExcelDataReader;
using Microsoft.Win32;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
@ -35,6 +34,7 @@ namespace ENI2.SheetDisplayControls
private SEC _sec;
private WAS _was;
private Message _stoMessage;
private Message _crewMessage;
private Dictionary<string, string> portAreas = null;
@ -42,10 +42,7 @@ namespace ENI2.SheetDisplayControls
private AGNT_Template _currentTemplate;
private AGNT_Template _undoTemplate;
private static List<SERV_Template> _servTemplates = null;
private SERV_Template _currentSERVTemplate;
private static List<WasteDisposalServiceProvider_Template> _wsdpTemplates = null;
private static List<WasteDisposalServiceProvider_Template> _wsdpTemplates = null;
private WasteDisposalServiceProvider_Template _currentWSDPTemplate;
private string _undoWSDPTemplate;
@ -83,17 +80,17 @@ namespace ENI2.SheetDisplayControls
{
base.Initialize();
foreach (Message aMessage in this.Messages)
{
{
if (aMessage.MessageNotificationClass == Message.NotificationClass.LADG) { this._ladgMessage = aMessage; this.ControlMessages.Add(aMessage); }
if (aMessage.MessageNotificationClass == Message.NotificationClass.SERV) { this._servMessage = aMessage; this.ControlMessages.Add(aMessage); }
if (aMessage.MessageNotificationClass == Message.NotificationClass.NOA_NOD) { this._noa_nod = aMessage.Elements[0] as NOA_NOD; this.ControlMessages.Add(aMessage); }
if (aMessage.MessageNotificationClass == Message.NotificationClass.SEC) { this._sec = aMessage.Elements[0] as SEC; this.ControlMessages.Add(aMessage); }
if (aMessage.MessageNotificationClass == Message.NotificationClass.SEC) { this._sec = aMessage.Elements[0] as SEC; this.ControlMessages.Add(aMessage); }
if (aMessage.MessageNotificationClass == Message.NotificationClass.INFO) { this._info = aMessage.Elements[0] as INFO; this.ControlMessages.Add(aMessage); }
if (aMessage.MessageNotificationClass == Message.NotificationClass.PRE72H) { this._pre72H = aMessage.Elements[0] as PRE72H; this.ControlMessages.Add(aMessage); }
if (aMessage.MessageNotificationClass == Message.NotificationClass.AGNT) { this._agnt = aMessage.Elements[0] as AGNT; this.ControlMessages.Add(aMessage); }
if (aMessage.MessageNotificationClass == Message.NotificationClass.WAS) { this._was = aMessage.Elements[0] as WAS; this.ControlMessages.Add(aMessage); }
if (aMessage.MessageNotificationClass == Message.NotificationClass.STO) { this._stoMessage = aMessage; this.ControlMessages.Add(aMessage); }
// if (aMessage.MessageNotificationClass == Message.NotificationClass.CREWA) { this._crewMessage = aMessage; this.ControlMessages.Add(aMessage); }
if (aMessage.MessageNotificationClass == Message.NotificationClass.CREWA) { this._crewMessage = aMessage; this.ControlMessages.Add(aMessage); }
}
// 2.1
@ -107,7 +104,7 @@ namespace ENI2.SheetDisplayControls
this.dataGridCallPurposes.AddingNewItem += DataGridCallPurposes_AddingNewItem;
this.dataGridCallPurposes.CreateRequested += DataGridCallPurposes_CreateRequested;
this.dataGridCallPurposes.DeleteRequested += DataGridCallPurposes_DeleteRequested;
portAreas = LocalizedLookup.getPortAreasForLocode(this.Core.PoC);
this.comboBoxPortArea.ItemsSource = portAreas;
this.comboBoxPortArea.DataContext = this._info;
@ -128,7 +125,6 @@ namespace ENI2.SheetDisplayControls
this.textBox_AgentPhone.DataContext = this._agnt;
this.textBox_AgentPostalCode.DataContext = this._agnt;
this.textBox_AgentStreetAndNumber.DataContext = this._agnt;
this.textBox_WasteDisposalServiceProvider.DataContext = this._was;
if (_agntTemplates == null)
{
_agntTemplates = await DBManagerAsync.GetAGNTTemplatesAsync(); // inital full load
@ -206,23 +202,6 @@ namespace ENI2.SheetDisplayControls
// this.dataGridEffects.Initialize();
// this.dataGridEffects.ItemsSource = _crewMessage.Elements;
#region init SERV templates
if (_servTemplates == null)
{
_servTemplates = await DBManagerAsync.GetSERVTemplatesAsync(); // initial load
_servTemplates.Sort();
Trace.WriteLine($"{_servTemplates.Count} SERV templates loaded");
}
this.comboBoxGroup.ItemsSource = _servTemplates;
this.buttonDeleteSERVTemplate.Visibility = DBManager.Instance.GetReportingPartyDict()[App.UserId.Value].IsEditor ? Visibility.Visible : Visibility.Hidden;
this.buttonEditSERVTemplate.Visibility = DBManager.Instance.GetReportingPartyDict()[App.UserId.Value].IsEditor ? Visibility.Visible : Visibility.Hidden;
this.buttonNewSERVTemplate.Visibility = DBManager.Instance.GetReportingPartyDict()[App.UserId.Value].IsEditor ? Visibility.Visible : Visibility.Hidden;
#endregion
}
public override int SelectedTabIndex
@ -266,7 +245,6 @@ namespace ENI2.SheetDisplayControls
this.RegisterTextboxChange(this.textBox_AgentPostalCode, Message.NotificationClass.AGNT);
this.RegisterTextboxChange(this.textBox_AgentStreetAndNumber, Message.NotificationClass.AGNT);
this.RegisterTextboxChange(this.textBox_AgentCountry, Message.NotificationClass.AGNT);
this.RegisterTextboxChange(this.textBox_WasteDisposalServiceProvider, Message.NotificationClass.WAS);
this.buttonSaveTemplate.IsEnabled = DBManager.Instance.GetReportingPartyDict()[App.UserId.Value].IsEditor;
this.buttonDeleteTemplate.IsEnabled = DBManager.Instance.GetReportingPartyDict()[App.UserId.Value].IsEditor;
@ -286,7 +264,7 @@ namespace ENI2.SheetDisplayControls
this.RegisterLocodeChange(this.locodeCtrlNextWastePort, Message.NotificationClass.WAS);
this.RegisterTextboxChange(this.textBoxWasteDisposalServiceProviders, Message.NotificationClass.WAS);
this.RegisterDatePickerChange(this.datePickerDateLastDisposal, Message.NotificationClass.WAS);
}
private void CheckBoxValidExemption_Checked(object sender, RoutedEventArgs e)
@ -340,14 +318,6 @@ namespace ENI2.SheetDisplayControls
{
if (this._currentTemplate == null) return;
// confirm overwrite of waste disposal service provider
if (this.textBox_WasteDisposalServiceProvider.Text.Length > 0)
{
string message = string.Format(Properties.Resources.textConfirmWSDPOverwrite, this.textBox_WasteDisposalServiceProvider.Text, this._currentTemplate.WasteDisposalServiceProviderName);
if (MessageBox.Show(message, Properties.Resources.textConfirmation, MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No)
== MessageBoxResult.No) { return; }
}
this._undoTemplate = createFromCurrentText(null, null);
this.textBox_AgentCity.Text = this._currentTemplate.AgentCity;
@ -359,7 +329,7 @@ namespace ENI2.SheetDisplayControls
this.textBox_AgentEMail.Text = this._currentTemplate.AgentEMail;
this.textBox_AgentEMail.GetBindingExpression(TextBox.TextProperty).UpdateSource();
this.textBox_AgentFax.Text = this._currentTemplate.AgentFax;
this.textBox_AgentFax.GetBindingExpression(TextBox.TextProperty).UpdateSource();
this.textBox_AgentEMail.GetBindingExpression(TextBox.TextProperty).UpdateSource();
this.textBox_AgentFirstName.Text = this._currentTemplate.AgentFirstName;
this.textBox_AgentFirstName.GetBindingExpression(TextBox.TextProperty).UpdateSource();
this.textBox_AgentLastName.Text = this._currentTemplate.AgentLastName;
@ -370,11 +340,6 @@ namespace ENI2.SheetDisplayControls
this.textBox_AgentPostalCode.GetBindingExpression(TextBox.TextProperty).UpdateSource();
this.textBox_AgentStreetAndNumber.Text = this._currentTemplate.AgentStreetAndNumber;
this.textBox_AgentStreetAndNumber.GetBindingExpression(TextBox.TextProperty).UpdateSource();
if ((this._currentTemplate.WasteDisposalServiceProviderName ?? "").Trim() != (this.textBox_WasteDisposalServiceProvider.Text ?? "").Trim())
{
this.textBox_WasteDisposalServiceProvider.Text = this._currentTemplate.WasteDisposalServiceProviderName;
this.textBox_WasteDisposalServiceProvider.GetBindingExpression(TextBox.TextProperty).UpdateSource();
}
this.buttonUndoTemplate.IsEnabled = true;
this.buttonSetTemplate.IsEnabled = false;
@ -462,8 +427,6 @@ namespace ENI2.SheetDisplayControls
this.textBox_AgentPostalCode.GetBindingExpression(TextBox.TextProperty).UpdateSource();
this.textBox_AgentStreetAndNumber.Text = this._undoTemplate.AgentStreetAndNumber;
this.textBox_AgentStreetAndNumber.GetBindingExpression(TextBox.TextProperty).UpdateSource();
this.textBox_WasteDisposalServiceProvider.Text = this._undoTemplate.WasteDisposalServiceProviderName;
this.textBox_WasteDisposalServiceProvider.GetBindingExpression(TextBox.TextProperty).UpdateSource();
this.buttonUndoTemplate.IsEnabled = false; // can't undo after undo
}
@ -485,7 +448,6 @@ namespace ENI2.SheetDisplayControls
at.AgentPhone = this.textBox_AgentPhone.Text;
at.AgentPostalCode = this.textBox_AgentPostalCode.Text;
at.AgentStreetAndNumber = textBox_AgentStreetAndNumber.Text;
at.WasteDisposalServiceProviderName = textBox_WasteDisposalServiceProvider.Text;
return at;
}
@ -515,14 +477,136 @@ namespace ENI2.SheetDisplayControls
private void buttonImportFromExcel_Click(object sender, RoutedEventArgs e)
{
int importWasteListCnt = ExcelLocalImportHelper.ImportWaste(_was);
if (importWasteListCnt > 0)
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Excel Files|*.xls;*.xlsx";
if (ofd.ShowDialog() ?? false)
{
this.dataGridWaste.Items.Refresh();
this.SublistElementChanged(Message.NotificationClass.WAS);
MessageBox.Show(String.Format(Properties.Resources.textWasteImported, importWasteListCnt), Properties.Resources.textCaptionInformation, MessageBoxButton.OK, MessageBoxImage.Information);
}
FileStream stream;
try
{
stream = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
List<Waste> importWasteList = new List<Waste>();
try
{
do
{
// skip first three rows
reader.Read();
reader.Read();
reader.Read();
int cnt = 0;
object o = null;
// Diese Funktion kann das "alte" Sheet Format nicht mehr einlesen!
while (reader.Read() && (cnt < 35))
{
if (reader.FieldCount < 9)
{
throw new InvalidDataException("Sheet must have 9 Columns of data");
}
if (!reader.IsDBNull(1)) o = reader.GetValue(1); else o = null;
if ((o != null) && Int32.TryParse(o.ToString(), out int wasteType))
{
Waste waste = _was.GetWasteForType(wasteType);
if (waste == null)
{
waste = new Waste();
waste.WasteType = wasteType;
waste.WAS = this._was;
waste.IsDirty = true;
waste.Identifier = Waste.GetNewIdentifier(this._was.Waste);
this._was.Waste.Add(waste);
}
else
{
waste.IsDirty = true;
}
if (!reader.IsDBNull(4)) waste.WasteDescription = reader.GetString(4);
if (waste.WasteDescription.IsNullOrEmpty())
waste.WasteDescription = "-";
if (!reader.IsDBNull(5)) o = reader.GetValue(5); else o = null;
if (o != null) waste.WasteDisposalAmount_MTQ = Convert.ToDouble(o);
if (!reader.IsDBNull(6)) o = reader.GetValue(6); else o = null;
if (o != null) waste.WasteCapacity_MTQ = Convert.ToDouble(o);
if (!reader.IsDBNull(7)) o = reader.GetValue(7); else o = null;
if (o != null) waste.WasteAmountRetained_MTQ = Convert.ToDouble(o);
if (!reader.IsDBNull(8)) waste.WasteDisposalPort = reader.GetString(8).ToUpper();
if (!reader.IsDBNull(9)) o = reader.GetValue(9); else o = null;
if (o != null) waste.WasteAmountGeneratedTillNextPort_MTQ = Convert.ToDouble(o);
importWasteList.Add(waste);
cnt++;
}
}
} while (reader.NextResult());
}
catch (Exception ex)
{
MessageBox.Show("Error reading Excel: " + ex.Message, Properties.Resources.textCaptionError, MessageBoxButton.OK, MessageBoxImage.Error);
}
if (importWasteList.Count > 0)
{
this.dataGridWaste.Items.Refresh();
this.SublistElementChanged(Message.NotificationClass.WAS);
MessageBox.Show(String.Format(Properties.Resources.textWasteImported, importWasteList.Count), Properties.Resources.textCaptionInformation, MessageBoxButton.OK, MessageBoxImage.Information);
}
}
stream.Close();
}
}
private void comboBoxGroup_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// clear all
this.Core.SetFlag(false, MessageCore.CoreFlags.MAERSK_BHV);
this.Core.SetFlag(false, MessageCore.CoreFlags.SEAGO_BHV);
this.Core.SetFlag(false, MessageCore.CoreFlags.SEAGO_WHV);
this.Core.SetFlag(false, MessageCore.CoreFlags.HOEGH);
this.Core.SetFlag(false, MessageCore.CoreFlags.ELBE_BULK);
this.Core.SetFlag(false, MessageCore.CoreFlags.FCT_JUNGE);
if (this.comboBoxGroup.SelectedItem == null)
{
this.comboBoxGroup.SelectedIndex = 0;
DBManager.Instance.Save(this.Core);
}
else
{
DictionaryEntry selectedItem = (DictionaryEntry)this.comboBoxGroup.SelectedItem;
if (Int32.TryParse((string)selectedItem.Value, out int selectedValue))
{
if (selectedValue == (int)MessageCore.CoreFlags.MAERSK_BHV) CheckServiceEntryMaerskBHV();
if (selectedValue == (int)MessageCore.CoreFlags.SEAGO_BHV) CheckServiceEntrySeaGoBHV();
if (selectedValue == (int)MessageCore.CoreFlags.HOEGH) CheckServiceEntryHoegh();
if (selectedValue == (int)MessageCore.CoreFlags.ELBE_BULK) CheckServiceEntryElbeBulk();
if (selectedValue == (int)MessageCore.CoreFlags.FCT_JUNGE) CheckServiceEntryFctJunge();
this.Core.SetFlag(true, (MessageCore.CoreFlags)selectedValue);
DBManager.Instance.Save(this.Core);
}
}
}
#endregion
@ -642,7 +726,7 @@ namespace ENI2.SheetDisplayControls
this.dataGridSERV.Items.Refresh();
this.SublistElementChanged(Message.NotificationClass.SERV);
}
}
}
#endregion
@ -650,7 +734,7 @@ namespace ENI2.SheetDisplayControls
private async Task InitTemplates()
{
_wsdpTemplates = await DBManagerAsync.GetWasteDisposalServiceProviderTemplatesAsync();
_wsdpTemplates = await DBManagerAsync.GetWastDisposalServiceProviderTemplatesAsync();
_wsdpTemplates.Sort();
this.comboBox_WSDPTemplate.ItemsSource = null;
this.comboBox_WSDPTemplate.ItemsSource = _wsdpTemplates;
@ -1064,99 +1148,6 @@ namespace ENI2.SheetDisplayControls
}
#endregion
#region SERV template button event handler
private void comboBoxGroup_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (this.comboBoxGroup.SelectedItem is SERV_Template st)
{
this.buttonDeleteSERVTemplate.IsEnabled = true;
this.buttonSetSERVTemplate.IsEnabled = true;
this._currentSERVTemplate = st;
}
}
private void buttonSetSERVTemplate_Click(object sender, RoutedEventArgs e)
{
if (this.comboBoxGroup.SelectedItem is SERV_Template st)
{
bool found = false;
foreach (SERV serv in _servMessage.Elements.Cast<SERV>())
{
if (serv.ServiceName.Equals(st.ServiceName))
{
found = true; break;
}
}
if (!found)
{
SERV newServ = new SERV();
newServ.ServiceName = st.ServiceName;
newServ.ServiceBeneficiary = st.ServiceBeneficiary;
newServ.ServiceInvoiceRecipient = st.ServiceInvoiceRecipient;
newServ.MessageHeader = this._servMessage;
newServ.Identifier = SERV.GetNewIdentifier(_servMessage.Elements);
this._servMessage.Elements.Add(newServ);
this.dataGridSERV.Items.Refresh();
this.SublistElementChanged(Message.NotificationClass.SERV);
}
}
}
private void buttonEditSERVTemplate_Click(object sender, RoutedEventArgs e)
{
if (this.comboBoxGroup.SelectedItem is SERV_Template st)
{
EditSERVDialog editSERVDialog = new EditSERVDialog();
editSERVDialog.AddVisible = false;
editSERVDialog.SERV_Template = st;
if (editSERVDialog.ShowDialog() ?? false)
{
_ = DBManagerAsync.SaveAsync(st);
this.comboBoxGroup.ItemsSource = null;
_servTemplates.Sort();
this.comboBoxGroup.ItemsSource = _servTemplates;
}
}
}
private void buttonNewSERVTemplate_Click(object sender, RoutedEventArgs e)
{
SERV_Template newTemplate = new SERV_Template();
EditSERVDialog esd = new EditSERVDialog();
esd.AddVisible = false;
esd.SERV_Template = newTemplate;
if (esd.ShowDialog() ?? false)
{
_ = DBManagerAsync.SaveAsync(esd.SERV_Template);
this.comboBoxGroup.ItemsSource = null;
_servTemplates.Add(newTemplate);
_servTemplates.Sort();
this.comboBoxGroup.ItemsSource = _servTemplates;
}
}
private void buttonDeleteSERVTemplate_Click(object sender, RoutedEventArgs e)
{
if (_currentSERVTemplate != null)
{
if (MessageBox.Show("Delete this template?", "Confirmation", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No) == MessageBoxResult.Yes)
{
this.comboBoxGroup.SelectedItem = null;
this.comboBoxGroup.ItemsSource = null;
_ = DBManagerAsync.DeleteAsync(_currentTemplate);
_servTemplates.Remove(_currentSERVTemplate);
this.buttonDeleteSERVTemplate.IsEnabled = false;
this.comboBoxGroup.ItemsSource = _servTemplates;
this.buttonSetSERVTemplate.IsEnabled = false;
}
}
}
#endregion
}
}

View File

@ -105,7 +105,7 @@ namespace ENI2.SheetDisplayControls
private void PreDepartureControl_Loaded(object sender, RoutedEventArgs e)
{
// 4.1
this.RegisterDoubleUpDownChange(this.doubleUpDownDraught, Message.NotificationClass.TIEFD);
this.RegisterDoubleUpDownChange(this.doubleUpDownDraught, Message.NotificationClass.TIEFA);
// 4.2
this.RegisterIntegerUpDownChange(this.integerUpDownCrewMemberOnBoard, Message.NotificationClass.POBD);

View File

@ -2,16 +2,17 @@
// Description: Display control of formsheet Tab 1. Voyage
//
using bsmd.database;
using ClosedXML.Excel;
using ENI2.EditControls;
using ENI2.Util;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using bsmd.database;
using ENI2.EditControls;
using System.Windows.Controls;
using System;
using ENI2.Util;
using System.Collections.Generic;
using ExcelDataReader;
using Microsoft.Win32;
using System.IO;
namespace ENI2.SheetDisplayControls
@ -300,14 +301,83 @@ namespace ENI2.SheetDisplayControls
private void buttonImportExcelLast10PortFacilities_Click(object sender, RoutedEventArgs e)
{
int importedCount = Excel.ExcelLocalImportHelper.ImportLast10PortFacilities(this._sec);
if (importedCount > 0)
OpenFileDialog ofd = new OpenFileDialog
{
this.dataGridLast10PortFacilities.Items.Refresh();
this.SublistElementChanged(Message.NotificationClass.SEC);
MessageBox.Show(String.Format(Properties.Resources.textL10PImported, importedCount),
Properties.Resources.textCaptionInformation, MessageBoxButton.OK, MessageBoxImage.Information);
Filter = "Excel Files|*.xls;*.xlsx"
};
if (ofd.ShowDialog() ?? false)
{
FileStream stream;
try
{
stream = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
List<LastTenPortFacilitiesCalled> importL10C = new List<LastTenPortFacilitiesCalled>();
try
{
do
{
int cnt = 0;
while (reader.Read() && (cnt < 10))
{
if (((IExcelDataReader)reader).FieldCount < 8)
{
throw new InvalidDataException("Sheet must have 8 Columns of data");
}
LastTenPortFacilitiesCalled l10c = new LastTenPortFacilitiesCalled();
if (reader.IsDBNull(0) && reader.IsDBNull(1)) continue;
if (!reader.IsDBNull(0)) l10c.PortFacilityPortName = reader.GetString(0);
if (!reader.IsDBNull(2)) l10c.PortFacilityPortCountry = reader.GetString(2);
if (!reader.IsDBNull(3)) l10c.PortFacilityPortLoCode = reader.GetString(3);
object o = null;
if (!reader.IsDBNull(4)) o = reader.GetValue(4);
if (o != null) l10c.PortFacilityDateOfArrival = Convert.ToDateTime(o);
if (!reader.IsDBNull(5)) o = reader.GetValue(5);
if (o != null) l10c.PortFacilityDateOfDeparture = Convert.ToDateTime(o);
// if (!reader.IsDBNull(4)) l10c.PortFacilityDateOfArrival = reader.GetDateTime(4);
// if (!reader.IsDBNull(5)) l10c.PortFacilityDateOfDeparture = reader.GetDateTime(5);
if (!reader.IsDBNull(6)) o = reader.GetValue(6);
if (o != null) l10c.PortFacilityShipSecurityLevel = Convert.ToByte(o);
if (!reader.IsDBNull(7)) o = reader.GetValue(7);
int gisis = Convert.ToInt32(o);
if (!reader.IsDBNull(7)) l10c.PortFacilityGISISCode = gisis.ToString().PadLeft(4, '0');
if (!reader.IsDBNull(8)) l10c.PortFacilitySecurityMattersToReport = reader.GetString(8);
if (l10c.PortFacilitySecurityMattersToReport.Equals("nil", StringComparison.CurrentCultureIgnoreCase))
l10c.PortFacilitySecurityMattersToReport = null;
if (!reader.IsDBNull(9)) l10c.PortFacilityGISISCodeLocode = reader.GetString(9);
l10c.SEC = this._sec;
l10c.IsDirty = true;
l10c.Identifier = LastTenPortFacilitiesCalled.GetNewIdentifier(this._sec.LastTenPortFacilitesCalled);
this._sec.LastTenPortFacilitesCalled.Add(l10c);
importL10C.Add(l10c);
cnt++;
}
} while (reader.NextResult());
}
catch (Exception ex)
{
MessageBox.Show("Error reading Excel: " + ex.Message, Properties.Resources.textCaptionError, MessageBoxButton.OK, MessageBoxImage.Error);
}
if (importL10C.Count > 0)
{
this.dataGridLast10PortFacilities.Items.Refresh();
this.SublistElementChanged(Message.NotificationClass.SEC);
MessageBox.Show(String.Format(Properties.Resources.textL10PImported, importL10C.Count), Properties.Resources.textCaptionInformation, MessageBoxButton.OK, MessageBoxImage.Information);
}
}
stream.Close();
}
}
@ -377,16 +447,87 @@ namespace ENI2.SheetDisplayControls
private void buttonImportLast30DaysFromExcel_Click(object sender, RoutedEventArgs e)
{
int cnt = Excel.ExcelLocalImportHelper.ImportLast30Days(this._mdh);
if (cnt > 0)
OpenFileDialog ofd = new OpenFileDialog
{
this.dataGridPortOfCallLast30Days.Items.Refresh();
this.SublistElementChanged(Message.NotificationClass.MDH);
MessageBox.Show(String.Format(Properties.Resources.textPoC30Imported, cnt),
Properties.Resources.textCaptionInformation,
MessageBoxButton.OK, MessageBoxImage.Information);
}
Filter = "Excel Files|*.xls;*.xlsx"
};
if (ofd.ShowDialog() ?? false)
{
FileStream stream;
try
{
stream = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
List<PortOfCallLast30Days> importPoC30 = new List<PortOfCallLast30Days>();
try
{
do
{
while (reader.Read())
{
if (reader.FieldCount < 3)
{
throw new InvalidDataException("Sheet must have at least 3 Columns of data");
}
PortOfCallLast30Days poc30 = new PortOfCallLast30Days();
if (reader.IsDBNull(0) && reader.IsDBNull(1)) continue;
if (!reader.IsDBNull(0)) poc30.PortOfCallLast30DaysLocode = reader.GetString(0);
if (!reader.IsDBNull(1)) poc30.PortOfCallLast30DaysDateOfDeparture = reader.GetDateTime(1);
string boolString = "";
if (!reader.IsDBNull(2)) boolString = reader.GetString(2);
poc30.PortOfCallLast30DaysCrewMembersJoined = (boolString.Equals("y", StringComparison.OrdinalIgnoreCase) || (boolString.Equals("yes", StringComparison.OrdinalIgnoreCase)) ||
(boolString.Equals("j", StringComparison.OrdinalIgnoreCase)));
if (reader.FieldCount > 3)
{
string allNewCrew = reader.GetString(3)?.Trim();
if (!allNewCrew.IsNullOrEmpty())
{
string[] crewNames = allNewCrew.Split(',', ';');
for (int i = 0; i < crewNames.Length; i++)
{
string crewName = crewNames[i].Trim();
if (crewName.IsNullOrEmpty()) continue;
PortOfCallLast30DaysCrewJoinedShip poc30Crew = new PortOfCallLast30DaysCrewJoinedShip();
poc30Crew.PortOfCallLast30DaysCrewJoinedShipName = crewName;
poc30Crew.PortOfCallLast30Days = poc30;
poc30.CrewJoinedShip.Add(poc30Crew);
}
}
}
poc30.MDH = this._mdh;
this._mdh.PortOfCallLast30Days.Add(poc30);
importPoC30.Add(poc30);
}
} while (reader.NextResult());
}
catch (Exception ex)
{
MessageBox.Show("Error reading Excel: " + ex.Message, Properties.Resources.textCaptionError, MessageBoxButton.OK, MessageBoxImage.Error);
}
if (importPoC30.Count > 0)
{
this.dataGridPortOfCallLast30Days.Items.Refresh();
this.SublistElementChanged(Message.NotificationClass.MDH);
MessageBox.Show(String.Format(Properties.Resources.textPoC30Imported, importPoC30.Count), Properties.Resources.textCaptionInformation,
MessageBoxButton.OK, MessageBoxImage.Information);
}
}
stream.Close();
}
}
private void buttonImportPortOfItineraryFromSEC_Click(object sender, RoutedEventArgs e)

View File

@ -102,8 +102,7 @@ namespace ENI2
private void ContextMenu_ContextMenuOpening(object sender, ContextMenuEventArgs e)
{
MessageCore selectedCore = this.dataGrid.SelectedItem as MessageCore;
if(selectedCore != null)
cancelItem.Visibility = (this.AdminMode && (selectedCore.Cancelled ?? false)) ? Visibility.Visible : Visibility.Collapsed;
cancelItem.Visibility = (this.AdminMode && (selectedCore.Cancelled ?? false)) ? Visibility.Visible : Visibility.Collapsed;
}
private void CancelItem_Click(object sender, RoutedEventArgs e)

View File

@ -66,7 +66,7 @@
</Setter>
</Style>
<Style TargetType="{x:Type enictrl:ClosableTabItem}" BasedOn="{StaticResource {x:Type TabItem}}">
<Style TargetType="{x:Type enictrl:ClosableTabItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type enictrl:ClosableTabItem}">

View File

@ -1,63 +0,0 @@
// Copyright (c) 2017- schick Informatik
// Description: Helper class for customs data serialization
//
using bsmd.database.EasyPeasy;
using System;
using System.IO;
using System.Xml.Serialization;
namespace ENI2.Util
{
public static class EasyPeasyState
{
private static readonly string Root = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"EasyPeasy");
private static readonly string StatePath = Path.Combine(Root, "state.xml");
public static ProofRequest LoadOrCreate()
{
try
{
if (File.Exists(StatePath))
{
using (var fs = File.OpenRead(StatePath))
{
var ser = new XmlSerializer(typeof(ProofRequest));
return (ProofRequest)ser.Deserialize(fs);
}
}
}
catch { /* swallow & create new */ }
return CreateDefault();
}
public static void Save(ProofRequest data)
{
Directory.CreateDirectory(Root);
using (var fs = File.Create(StatePath))
{
var ser = new XmlSerializer(typeof(ProofRequest));
ser.Serialize(fs, data);
}
}
public static ProofRequest CreateDefault()
{
return new ProofRequest
{
ProofInformationT2LT2LF = new ProofInformationT2LT2LF
{
RequestedValidityOfTheProof = new RequestedValidityOfTheProof(),
GoodsShipmentForT2LT2LF = new GoodsShipmentForT2LT2LF
{
LocationOfGoods = new LocationOfGoods(),
TransportDocuments = new TransportDocuments()
}
}
};
}
}
}

View File

@ -3,7 +3,7 @@
//
using bsmd.database;
using ExcelDataReader;
using System;
namespace ENI2.Util
@ -11,6 +11,20 @@ namespace ENI2.Util
internal static class Extensions
{
public static string ReadAsString(this IExcelDataReader reader, int index)
{
if (index >= reader.FieldCount) return null;
Type fieldType = reader.GetFieldType(index);
if (fieldType == null) return null;
if (fieldType == typeof(string))
return reader.GetString(index).Clean();
if (fieldType == typeof(DateTime))
return reader.GetDateTime(index).ToString();
if (fieldType == typeof(int))
return reader.GetInt32(index).ToString();
if (fieldType == typeof(double))
return ((int)reader.GetDouble(index)).ToString();
return null;
}
}
}

View File

@ -1,34 +1,24 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="ClosedXML" version="0.105.0" targetFramework="net48" />
<package id="ClosedXML.Parser" version="2.0.0" targetFramework="net48" />
<package id="DocumentFormat.OpenXml" version="3.3.0" targetFramework="net481" />
<package id="DocumentFormat.OpenXml.Framework" version="3.3.0" targetFramework="net481" />
<package id="ExcelNumberFormat" version="1.1.0" targetFramework="net48" />
<package id="Extended.Wpf.Toolkit" version="5.0.0" targetFramework="net48" />
<package id="log4net" version="3.2.0" targetFramework="net48" />
<package id="Microsoft.Bcl.AsyncInterfaces" version="10.0.0" targetFramework="net481" />
<package id="Microsoft.Bcl.Cryptography" version="10.0.0" targetFramework="net481" />
<package id="Microsoft.Bcl.HashCode" version="6.0.0" targetFramework="net481" />
<package id="Microsoft.Extensions.DependencyInjection" version="10.0.0" targetFramework="net481" />
<package id="Microsoft.Extensions.DependencyInjection.Abstractions" version="10.0.0" targetFramework="net481" />
<package id="Microsoft.Extensions.Logging" version="10.0.0" targetFramework="net481" />
<package id="Microsoft.Extensions.Logging.Abstractions" version="10.0.0" targetFramework="net481" />
<package id="Microsoft.Extensions.Options" version="10.0.0" targetFramework="net481" />
<package id="Microsoft.Extensions.Primitives" version="10.0.0" targetFramework="net481" />
<package id="PDFsharp" version="6.2.3" targetFramework="net481" />
<package id="PDFsharp-MigraDoc" version="6.2.3" targetFramework="net481" />
<package id="RBush.Signed" version="4.0.0" targetFramework="net48" />
<package id="SixLabors.Fonts" version="1.0.0" targetFramework="net481" />
<package id="ExcelDataReader" version="3.7.0" targetFramework="net48" />
<package id="Extended.Wpf.Toolkit" version="4.7.25104.5739" targetFramework="net48" />
<package id="log4net" version="3.0.4" targetFramework="net48" />
<package id="Microsoft.Bcl.AsyncInterfaces" version="9.0.4" targetFramework="net48" />
<package id="Microsoft.Extensions.DependencyInjection" version="9.0.4" targetFramework="net48" />
<package id="Microsoft.Extensions.DependencyInjection.Abstractions" version="9.0.4" targetFramework="net48" />
<package id="Microsoft.Extensions.Logging" version="9.0.4" targetFramework="net48" />
<package id="Microsoft.Extensions.Logging.Abstractions" version="9.0.4" targetFramework="net48" />
<package id="Microsoft.Extensions.Options" version="9.0.4" targetFramework="net48" />
<package id="Microsoft.Extensions.Primitives" version="9.0.4" targetFramework="net48" />
<package id="Microsoft.Office.Interop.Excel" version="15.0.4795.1001" targetFramework="net48" />
<package id="PDFsharp-MigraDoc" version="6.1.1" targetFramework="net48" />
<package id="Stub.System.Data.SQLite.Core.NetFramework" version="1.0.119.0" targetFramework="net48" />
<package id="System.Buffers" version="4.6.1" targetFramework="net48" />
<package id="System.Data.SQLite.Core" version="1.0.119.0" targetFramework="net48" />
<package id="System.Diagnostics.DiagnosticSource" version="10.0.0" targetFramework="net481" />
<package id="System.Formats.Asn1" version="10.0.0" targetFramework="net481" />
<package id="System.Diagnostics.DiagnosticSource" version="9.0.4" targetFramework="net48" />
<package id="System.Memory" version="4.6.3" targetFramework="net48" />
<package id="System.Numerics.Vectors" version="4.6.1" targetFramework="net48" />
<package id="System.Runtime.CompilerServices.Unsafe" version="6.1.2" targetFramework="net48" />
<package id="System.Security.Cryptography.Pkcs" version="10.0.0" targetFramework="net481" />
<package id="System.Threading.Tasks.Extensions" version="4.6.3" targetFramework="net48" />
<package id="System.ValueTuple" version="4.6.1" targetFramework="net48" />
</packages>

View File

@ -1,25 +0,0 @@
PRINT N'Creating [dbo].[SERV_template]...';
GO
CREATE TABLE [dbo].[SERV_template] (
[Id] UNIQUEIDENTIFIER NOT NULL,
[ServiceName] NVARCHAR (100) NULL,
[ServiceBeneficiary] NVARCHAR (256) NULL,
[ServiceInvoiceRecipient] NVARCHAR (256) NULL,
[Created] DATETIME NULL DEFAULT CURRENT_TIMESTAMP,
[Changed] DATETIME NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
GO
CREATE TRIGGER SERV_template_Trigger_Change_Log
ON
dbo.SERV_template
FOR UPDATE
AS
SET NOCOUNT ON
IF NOT UPDATE([Changed])
UPDATE SERV_template SET [Changed] = GETDATE() WHERE Id IN (SELECT Id FROM [inserted])
GO

View File

@ -1,7 +1,7 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.25123.0
# Visual Studio Version 17
VisualStudioVersion = 17.14.36109.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SendNSWMessageService", "SendNSWMessageService\SendNSWMessageService.csproj", "{E6F8F110-77E7-4348-9875-CAD095BF8E24}"
EndProject
@ -15,6 +15,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "bsmd.hisnord", "bsmd.hisnor
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "bsmd.status", "bsmd.status\bsmd.status.csproj", "{1EA7D5CE-4051-45CB-BE70-F8DD3DE0416A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "bsmd.util", "bsmd.util\bsmd.util.csproj", "{5BA1BA6D-FB0E-4EC7-9AB2-47504E363C49}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -45,8 +47,15 @@ Global
{1EA7D5CE-4051-45CB-BE70-F8DD3DE0416A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1EA7D5CE-4051-45CB-BE70-F8DD3DE0416A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1EA7D5CE-4051-45CB-BE70-F8DD3DE0416A}.Release|Any CPU.Build.0 = Release|Any CPU
{5BA1BA6D-FB0E-4EC7-9AB2-47504E363C49}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5BA1BA6D-FB0E-4EC7-9AB2-47504E363C49}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5BA1BA6D-FB0E-4EC7-9AB2-47504E363C49}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5BA1BA6D-FB0E-4EC7-9AB2-47504E363C49}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {C4D8D5B4-6702-49E1-A952-AF5335BE5186}
EndGlobalSection
EndGlobal

View File

@ -10,6 +10,7 @@
<root>
<level value="DEBUG"/>
<appender-ref ref="LogFileAppender"/>
<appender-ref ref="LokiAppender" />
</root>
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="log-NSWMessageService.txt"/>
@ -22,6 +23,13 @@
<param name="ConversionPattern" value="%date [%thread] %-5level [%logger] - %message%newline"/>
</layout>
</appender>
<appender name="LokiAppender" type="bsmd.util.LokiAppender, bsmd.util">
<LokiUrl value="https://loki.puls200.dyn-dns.org/loki/api/v1/push" />
<ApplicationName value="NSW service" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="[%date{yyyy-MM-dd HH:mm:ss}] %-5level - %message%newline" />
</layout>
</appender>
</log4net>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8"/>

View File

@ -23,7 +23,9 @@ namespace SendNSWMessageService
Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
InitializeComponent();
System.Net.ServicePointManager.ServerCertificateValidationCallback += (_, ____, __, ___) =>
System.Net.ServicePointManager.ServerCertificateValidationCallback += (object _, System.Security.Cryptography.X509Certificates.X509Certificate ____,
System.Security.Cryptography.X509Certificates.X509Chain __,
System.Net.Security.SslPolicyErrors ___) =>
{
return true; // **** Immer OK weil wir nur mit einem dedizierten Endpoint reden..
};

View File

@ -40,8 +40,8 @@
<AssemblyOriginatorKeyFile>..\bsmdKey.snk</AssemblyOriginatorKeyFile>
</PropertyGroup>
<ItemGroup>
<Reference Include="log4net, Version=3.2.0.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<HintPath>..\packages\log4net.3.2.0\lib\net462\log4net.dll</HintPath>
<Reference Include="log4net, Version=3.1.0.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<HintPath>..\packages\log4net.3.1.0\lib\net462\log4net.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
@ -126,6 +126,10 @@
<Project>{1ea7d5ce-4051-45cb-be70-f8dd3de0416a}</Project>
<Name>bsmd.status</Name>
</ProjectReference>
<ProjectReference Include="..\bsmd.util\bsmd.util.csproj">
<Project>{5ba1ba6d-fb0e-4ec7-9ab2-47504e363c49}</Project>
<Name>bsmd.util</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="log4net" version="3.2.0" targetFramework="net48" />
<package id="log4net" version="3.1.0" targetFramework="net48" />
</packages>

View File

@ -36,23 +36,7 @@ namespace bsmd.ExcelReadService
this._excelApp.DisplayAlerts = false;
this._excelWorkbooks = _excelApp.Workbooks;
this._portcall = _excelWorkbooks.Open(
filePath,
UpdateLinks: 0,
ReadOnly: true,
Format: 5,
Password: "",
WriteResPassword: "",
IgnoreReadOnlyRecommended: true,
Origin: XlPlatform.xlWindows,
Delimiter: "",
Editable: false,
Notify: false,
Converter: 0,
AddToMru: false,
Local: false,
CorruptLoad: false);
this._portcall.ChangeFileAccess(XlFileAccess.xlReadOnly);
this._portcall = _excelWorkbooks.Open(filePath, 0, true, 5, "", "", false, XlPlatform.xlWindows, "", false, false, 0, false, false, false);
_nameDict = new Dictionary<string, Name>();
int bookCnt = 0;
foreach(Name name in _portcall.Names)

View File

@ -46,8 +46,8 @@
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="log4net, Version=3.2.0.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<HintPath>..\ENI2\packages\log4net.3.2.0\lib\net462\log4net.dll</HintPath>
<Reference Include="log4net, Version=3.0.4.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<HintPath>..\ENI2\packages\log4net.3.0.4\lib\net462\log4net.dll</HintPath>
</Reference>
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data.DataSetExtensions" />

View File

@ -0,0 +1,38 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<UseIISExpress>true</UseIISExpress>
<LastActiveSolutionConfig>Debug|Any CPU</LastActiveSolutionConfig>
<Use64BitIISExpress />
<IISExpressSSLPort />
<IISExpressAnonymousAuthentication />
<IISExpressWindowsAuthentication />
<IISExpressUseClassicPipelineMode />
<UseGlobalApplicationHostFile />
</PropertyGroup>
<ProjectExtensions>
<VisualStudio>
<FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}">
<WebProjectProperties>
<StartPageUrl>
</StartPageUrl>
<StartAction>CurrentPage</StartAction>
<AspNetDebugging>True</AspNetDebugging>
<SilverlightDebugging>False</SilverlightDebugging>
<NativeDebugging>False</NativeDebugging>
<SQLDebugging>False</SQLDebugging>
<ExternalProgram>
</ExternalProgram>
<StartExternalURL>
</StartExternalURL>
<StartCmdLineArguments>
</StartCmdLineArguments>
<StartWorkingDirectory>
</StartWorkingDirectory>
<EnableENC>True</EnableENC>
<AlwaysStartWebServerOnDebug>True</AlwaysStartWebServerOnDebug>
</WebProjectProperties>
</FlavorProperties>
</VisualStudio>
</ProjectExtensions>
</Project>

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="log4net" version="3.2.0" targetFramework="net48" />
<package id="log4net" version="3.0.4" targetFramework="net48" />
</packages>

View File

@ -1,72 +1,36 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net" />
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<section name="bsmd.Tool.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<section name="bsmd.Tool.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false"/>
</sectionGroup>
</configSections>
<log4net>
<root>
<level value="DEBUG" />
<appender-ref ref="LogFileAppender" />
<level value="DEBUG"/>
<appender-ref ref="LogFileAppender"/>
</root>
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="log.bsmd.Tool.txt" />
<param name="AppendToFile" value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<param name="File" value="log.bsmd.Tool.txt"/>
<param name="AppendToFile" value="true"/>
<rollingStyle value="Size"/>
<maxSizeRollBackups value="10"/>
<maximumFileSize value="10MB"/>
<staticLogFileName value="true"/>
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%date [%thread] %-5level [%logger] - %message%newline" />
<param name="ConversionPattern" value="%date [%thread] %-5level [%logger] - %message%newline"/>
</layout>
</appender>
</log4net>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8"/>
</startup>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="log4net" publicKeyToken="669e0ddf0bb1aa2a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.6.0" newVersion="4.0.6.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Memory" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.1.2" newVersion="4.0.1.2" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Numerics.Vectors" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.1.4.0" newVersion="4.1.4.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Buffers" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.3.0" newVersion="4.0.3.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<applicationSettings>
<bsmd.Tool.Properties.Settings>
<setting name="ConnectionString" serializeAs="String">
<value>replace me!</value>
</setting>
<setting name="EcholotOutputFolder" serializeAs="String">
<value />
</setting>
<setting name="EcholotMaxThreads" serializeAs="String">
<value>4</value>
</setting>
<setting name="HISNORD_Folder" serializeAs="String">
<value>C:\temp\hisnord</value>
</setting>
<setting name="DBH_Folder" serializeAs="String">
<value>C:\temp\dbh</value>
</setting>
</bsmd.Tool.Properties.Settings>
</applicationSettings>
<userSettings>
<bsmd.Tool.Properties.Settings>
<setting name="ConnectionString" serializeAs="String">
<value>replace me!</value>
</setting>
</bsmd.Tool.Properties.Settings>
</userSettings>
</configuration>

View File

@ -1,224 +0,0 @@
// Copyright (c) 2020- schick Informatik
// Description: The purpose of this tool is to evaluate files sent both through HIS-Nord and dbh
// to evaluate how many classes were sent at what time and by whom to the purpose of improved employee
// time planning
using ClosedXML.Excel;
using log4net;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace bsmd.Tool
{
internal static class Echolot
{
private static readonly ILog _log = LogManager.GetLogger(typeof(Echolot));
static readonly HashSet<string> ValidGroupingKeys = new HashSet<string>
{
"VISIT",
"TRANSIT",
"NOA_NOD",
"NOANOD",
"ATA",
"ATD",
"SEC",
"POBA",
"POBD",
"NAME",
"TIEFA",
"TIEFD",
"BKRA",
"BKRD",
"STAT",
"LADG",
"INFO",
"SERV",
"PRE72H",
"MDH",
"WAS",
"CREWA",
"PASA",
"BPOL",
"TOWA",
"TOWD",
"HAZA",
"HAZD",
"AGNT",
"STO",
"CREWD",
"PASD",
"WAS_RCPT"
};
static readonly HashSet<string> IgnoreGroupingKeys = new HashSet<string>
{
"VISIT",
"TRANSIT",
"ATA",
"ATD"
};
internal static void Evaluate(string outputFolder, int maxThreads)
{
DateTime executionTime = DateTime.Now;
#region first scan: dbh files
string inputFolder = Properties.Settings.Default.DBH_Folder;
var files = Directory.GetFiles(inputFolder, "*.xml");
var results = new ConcurrentBag<ResultRow>();
Parallel.ForEach(files, new ParallelOptions { MaxDegreeOfParallelism = maxThreads }, file =>
{
try
{
var doc = XDocument.Load(file);
// Look for a valid grouping key at the root level
var groupingElem = doc.Root.Elements()
.FirstOrDefault(x => ValidGroupingKeys.Contains(x.Name.LocalName) && !IgnoreGroupingKeys.Contains(x.Name.LocalName));
if (groupingElem == null)
{
_log.InfoFormat("skipping {0}", file);
return; // Skip file
}
var lastName = doc.Descendants("RPLastName").FirstOrDefault()?.Value?.Trim();
var firstName = doc.Descendants("RPFirstName").FirstOrDefault()?.Value?.Trim();
var timestampStr = doc.Descendants("Timestamp").FirstOrDefault()?.Value?.Trim();
DateTime timestamp = DateTime.Parse(timestampStr);
results.Add(new ResultRow
{
FirstName = firstName,
LastName = lastName,
Timestamp = timestamp,
WeekStart = GetWeekStart(timestamp, executionTime.DayOfWeek),
Provider = "DBH"
});
}
catch (Exception ex)
{
_log.Error(ex.ToString());
}
});
#endregion
#region second scan: his-nord files
var inputFolder2 = Properties.Settings.Default.HISNORD_Folder;
var files2 = Directory.GetFiles(inputFolder2, "*.xml");
Parallel.ForEach(files2, new ParallelOptions { MaxDegreeOfParallelism = maxThreads }, file =>
{
try
{
var doc = XDocument.Load(file);
var match = Regex.Match(file, @"-([A-Z0-9_]+)\.xml$", RegexOptions.None);
string key = "";
if (match.Success)
{
key = match.Groups[1].Value;
}
if((key.Length == 0) || IgnoreGroupingKeys.Contains(key))
{
_log.InfoFormat("skipping {0}", file);
return; // Skip file
}
var username = doc.Descendants("firstname").FirstOrDefault()?.Value?.Trim();
if(username == null)
{
_log.WarnFormat("Username not found in file {0}", file);
return;
}
var splitname = username.Split(' ');
var lastName = splitname[1].Trim();
var firstName = splitname[0].Trim();
DateTime timestamp = File.GetCreationTime(file);
results.Add(new ResultRow
{
FirstName = firstName,
LastName = lastName,
Timestamp = timestamp,
WeekStart = GetWeekStart(timestamp, executionTime.DayOfWeek),
Provider = "HIS-NORD"
});
}
catch (Exception ex)
{
_log.Error(ex.ToString());
}
});
#endregion
var grouped = results
.GroupBy(r => r.WeekStart)
.OrderBy(g => g.Key);
// Write Excel
string excelFile = Path.Combine(outputFolder, $"echolot_{executionTime:yyyyMMdd_HHmmss}.xlsx");
using (var workbook = new XLWorkbook())
{
foreach (var weekGroup in grouped)
{
var ws = workbook.Worksheets.Add(weekGroup.Key.ToString("yyyy-MM-dd"));
ws.Cell(1, 1).Value = "Firstname";
ws.Cell(1, 2).Value = "Lastname";
ws.Cell(1, 3).Value = "Count";
int row = 2;
var orderedGroups = weekGroup
.GroupBy(x => new { x.FirstName, x.LastName })
.OrderByDescending(g => g.Count()); // Use OrderBy for ascending
foreach (var nameGroup in orderedGroups)
{
ws.Cell(row, 1).Value = nameGroup.Key.FirstName;
ws.Cell(row, 2).Value = nameGroup.Key.LastName;
ws.Cell(row, 3).Value = nameGroup.Count();
row++;
}
}
workbook.SaveAs(excelFile);
}
}
static DateTime GetWeekStart(DateTime date, DayOfWeek weekStart)
{
int diff = (7 + (date.DayOfWeek - weekStart)) % 7;
return date.Date.AddDays(-1 * diff);
}
class ResultRow
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime Timestamp { get; set; }
public DateTime WeekStart { get; set; }
public string Provider { get; set; }
}
}
}

View File

@ -25,18 +25,6 @@ namespace bsmd.Tool
[Option("locodes", HelpText = "use this flag if you want to import locodes")]
public bool ImportLocodes { get; set; }
[Option("echolot", HelpText = "use this flag to run the echolot output file evaluation")]
public bool Echolot { get; set; }
[Option('i', "input_folder", HelpText = "Input folder")]
public string InputFolder { get; set; }
[Option('o', "output_folder", HelpText = "Output folder")]
public string OutputFolder { get; set; }
[Option("max_threads", HelpText = "Maximum amount of parallelism for folder parsing")]
public int? MaxThreads { get; set; }
[Option('s', "staledays", Default = 30, HelpText ="Delete files older than X days")]
public int StaleDays { get; set; }

View File

@ -1,5 +1,4 @@
using bsmd.database;
using CommandLine;
using CommandLine;
using log4net;
using System;
@ -41,24 +40,15 @@ namespace bsmd.Tool
LocodeSQliteImport.Import(o.LocodeDB, o.LocodeCSV);
}
}
if(o.Echolot)
{
string outputFolder = Properties.Settings.Default.EcholotOutputFolder;
if (!o.OutputFolder.IsNullOrEmpty())
outputFolder = o.OutputFolder;
int maxThreads = 2;
if (o.MaxThreads.HasValue) maxThreads = o.MaxThreads.Value;
Echolot.Evaluate(outputFolder, maxThreads);
}
});
}
catch (Exception ex)
{
log.Fatal(ex.ToString());
Console.WriteLine(ex.Message);
result = 1;
}
}
Console.Read();
return result;
}
}

View File

@ -12,7 +12,7 @@ namespace bsmd.Tool.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.14.0.0")]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.10.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
@ -23,48 +23,15 @@ namespace bsmd.Tool.Properties {
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Configuration.UserScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("replace me!")]
public string ConnectionString {
get {
return ((string)(this["ConnectionString"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("")]
public string EcholotOutputFolder {
get {
return ((string)(this["EcholotOutputFolder"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("4")]
public int EcholotMaxThreads {
get {
return ((int)(this["EcholotMaxThreads"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("C:\\temp\\hisnord")]
public string HISNORD_Folder {
get {
return ((string)(this["HISNORD_Folder"]));
}
}
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.DefaultSettingValueAttribute("C:\\temp\\dbh")]
public string DBH_Folder {
get {
return ((string)(this["DBH_Folder"]));
set {
this["ConnectionString"] = value;
}
}
}

View File

@ -2,20 +2,8 @@
<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)" GeneratedClassNamespace="bsmd.Tool.Properties" GeneratedClassName="Settings">
<Profiles />
<Settings>
<Setting Name="ConnectionString" Type="System.String" Scope="Application">
<Setting Name="ConnectionString" Type="System.String" Scope="User">
<Value Profile="(Default)">replace me!</Value>
</Setting>
<Setting Name="EcholotOutputFolder" Type="System.String" Scope="Application">
<Value Profile="(Default)" />
</Setting>
<Setting Name="EcholotMaxThreads" Type="System.Int32" Scope="Application">
<Value Profile="(Default)">4</Value>
</Setting>
<Setting Name="HISNORD_Folder" Type="System.String" Scope="Application">
<Value Profile="(Default)">C:\temp\hisnord</Value>
</Setting>
<Setting Name="DBH_Folder" Type="System.String" Scope="Application">
<Value Profile="(Default)">C:\temp\dbh</Value>
</Setting>
</Settings>
</SettingsFile>

View File

@ -44,62 +44,25 @@
<Reference Include="bsmd.database">
<HintPath>..\bsmd.database\bin\Debug\bsmd.database.dll</HintPath>
</Reference>
<Reference Include="ClosedXML, Version=0.105.0.0, Culture=neutral, PublicKeyToken=fd1eb21b62ae805b, processorArchitecture=MSIL">
<HintPath>..\packages\ClosedXML.0.105.0\lib\netstandard2.0\ClosedXML.dll</HintPath>
</Reference>
<Reference Include="ClosedXML.Parser, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1d5f7376574c51ec, processorArchitecture=MSIL">
<HintPath>..\packages\ClosedXML.Parser.2.0.0\lib\netstandard2.0\ClosedXML.Parser.dll</HintPath>
</Reference>
<Reference Include="CommandLine, Version=2.9.1.0, Culture=neutral, PublicKeyToken=5a870481e358d379, processorArchitecture=MSIL">
<HintPath>..\packages\CommandLineParser.2.9.1\lib\net461\CommandLine.dll</HintPath>
</Reference>
<Reference Include="DocumentFormat.OpenXml, Version=3.1.1.0, Culture=neutral, PublicKeyToken=8fb06cb64d019a17, processorArchitecture=MSIL">
<HintPath>..\packages\DocumentFormat.OpenXml.3.1.1\lib\net46\DocumentFormat.OpenXml.dll</HintPath>
</Reference>
<Reference Include="DocumentFormat.OpenXml.Framework, Version=3.1.1.0, Culture=neutral, PublicKeyToken=8fb06cb64d019a17, processorArchitecture=MSIL">
<HintPath>..\packages\DocumentFormat.OpenXml.Framework.3.1.1\lib\net46\DocumentFormat.OpenXml.Framework.dll</HintPath>
</Reference>
<Reference Include="ExcelNumberFormat, Version=1.1.0.0, Culture=neutral, PublicKeyToken=23c6f5d73be07eca, processorArchitecture=MSIL">
<HintPath>..\packages\ExcelNumberFormat.1.1.0\lib\net20\ExcelNumberFormat.dll</HintPath>
</Reference>
<Reference Include="log4net, Version=3.1.0.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<HintPath>..\packages\log4net.3.1.0\lib\net462\log4net.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Bcl.HashCode, Version=1.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Bcl.HashCode.1.1.1\lib\net461\Microsoft.Bcl.HashCode.dll</HintPath>
</Reference>
<Reference Include="RBush, Version=4.0.0.0, Culture=neutral, PublicKeyToken=c77e27b81f4d0187, processorArchitecture=MSIL">
<HintPath>..\packages\RBush.Signed.4.0.0\lib\net47\RBush.dll</HintPath>
</Reference>
<Reference Include="SixLabors.Fonts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=d998eea7b14cab13, processorArchitecture=MSIL">
<HintPath>..\packages\SixLabors.Fonts.1.0.0\lib\netstandard2.0\SixLabors.Fonts.dll</HintPath>
<Reference Include="log4net, Version=2.0.15.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<HintPath>..\packages\log4net.2.0.15\lib\net45\log4net.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Buffers, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Buffers.4.5.1\lib\net461\System.Buffers.dll</HintPath>
</Reference>
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
<Reference Include="System.Data.SQLite, Version=1.0.119.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139, processorArchitecture=MSIL">
<HintPath>..\packages\Stub.System.Data.SQLite.Core.NetFramework.1.0.119.0\lib\net46\System.Data.SQLite.dll</HintPath>
</Reference>
<Reference Include="System.Memory, Version=4.0.1.2, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
<HintPath>..\packages\System.Memory.4.5.5\lib\net461\System.Memory.dll</HintPath>
<Reference Include="System.Data.SQLite, Version=1.0.117.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139, processorArchitecture=MSIL">
<HintPath>..\packages\Stub.System.Data.SQLite.Core.NetFramework.1.0.117.0\lib\net46\System.Data.SQLite.dll</HintPath>
</Reference>
<Reference Include="System.Numerics" />
<Reference Include="System.Numerics.Vectors, Version=4.1.4.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Numerics.Vectors.4.5.0\lib\net46\System.Numerics.Vectors.dll</HintPath>
</Reference>
<Reference Include="System.Runtime.CompilerServices.Unsafe, Version=4.0.6.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Runtime.CompilerServices.Unsafe.4.7.0\lib\netstandard2.0\System.Runtime.CompilerServices.Unsafe.dll</HintPath>
</Reference>
<Reference Include="System.Web" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
<Reference Include="WindowsBase" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\bsmd.database\Properties\AssemblyProductInfo.cs">
@ -113,7 +76,6 @@
</Compile>
<Compile Include="CheckRules.cs" />
<Compile Include="CleanupFiles.cs" />
<Compile Include="Echolot.cs" />
<Compile Include="LocodeSQliteImport.cs" />
<Compile Include="Options.cs" />
<Compile Include="Program.cs" />
@ -127,7 +89,6 @@
<ItemGroup>
<None Include="App.config" />
<None Include="..\bsmdKey.snk" />
<None Include="bsmd.Tool.licenseheader" />
<None Include="packages.config" />
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
@ -135,12 +96,12 @@
</None>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="..\packages\Stub.System.Data.SQLite.Core.NetFramework.1.0.119.0\build\net46\Stub.System.Data.SQLite.Core.NetFramework.targets" Condition="Exists('..\packages\Stub.System.Data.SQLite.Core.NetFramework.1.0.119.0\build\net46\Stub.System.Data.SQLite.Core.NetFramework.targets')" />
<Import Project="..\packages\Stub.System.Data.SQLite.Core.NetFramework.1.0.117.0\build\net46\Stub.System.Data.SQLite.Core.NetFramework.targets" Condition="Exists('..\packages\Stub.System.Data.SQLite.Core.NetFramework.1.0.117.0\build\net46\Stub.System.Data.SQLite.Core.NetFramework.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\packages\Stub.System.Data.SQLite.Core.NetFramework.1.0.119.0\build\net46\Stub.System.Data.SQLite.Core.NetFramework.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Stub.System.Data.SQLite.Core.NetFramework.1.0.119.0\build\net46\Stub.System.Data.SQLite.Core.NetFramework.targets'))" />
<Error Condition="!Exists('..\packages\Stub.System.Data.SQLite.Core.NetFramework.1.0.117.0\build\net46\Stub.System.Data.SQLite.Core.NetFramework.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Stub.System.Data.SQLite.Core.NetFramework.1.0.117.0\build\net46\Stub.System.Data.SQLite.Core.NetFramework.targets'))" />
</Target>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.

View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<StartArguments>--echolot --output_folder="C:\temp"</StartArguments>
<StartArguments>--locodes --csv="C:\svn_lager\bsmd\nsw\Archiv\2022-2.UNLOCODE.all.csv" --db "C:\git_lager\git_bsmd\misc\db.sqlite"</StartArguments>
</PropertyGroup>
</Project>

View File

@ -1,14 +0,0 @@
extensions: designer.cs generated.cs
extensions: .cs .cpp .h
// Copyright (c) 2020- schick Informatik
// Description:
//
extensions: .aspx .ascx
<%--
Copyright (c) 2020- schick Informatik
--%>
extensions: .xml .config .xsd
<!--
Copyright (c) 2020- schick Informatik
-->

View File

@ -1,19 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="ClosedXML" version="0.105.0" targetFramework="net48" />
<package id="ClosedXML.Parser" version="2.0.0" targetFramework="net48" />
<package id="CommandLineParser" version="2.9.1" targetFramework="net48" />
<package id="DocumentFormat.OpenXml" version="3.1.1" targetFramework="net48" />
<package id="DocumentFormat.OpenXml.Framework" version="3.1.1" targetFramework="net48" />
<package id="ExcelNumberFormat" version="1.1.0" targetFramework="net48" />
<package id="log4net" version="3.1.0" targetFramework="net48" />
<package id="Microsoft.Bcl.HashCode" version="1.1.1" targetFramework="net48" />
<package id="RBush.Signed" version="4.0.0" targetFramework="net48" />
<package id="SixLabors.Fonts" version="1.0.0" targetFramework="net48" />
<package id="Stub.System.Data.SQLite.Core.NetFramework" version="1.0.119.0" targetFramework="net48" />
<package id="System.Buffers" version="4.5.1" targetFramework="net48" />
<package id="System.Data.SQLite.Core" version="1.0.119.0" targetFramework="net48" />
<package id="System.Memory" version="4.5.5" targetFramework="net48" />
<package id="System.Numerics.Vectors" version="4.5.0" targetFramework="net48" />
<package id="System.Runtime.CompilerServices.Unsafe" version="4.7.0" targetFramework="net48" />
<package id="log4net" version="2.0.15" targetFramework="net48" />
<package id="Stub.System.Data.SQLite.Core.NetFramework" version="1.0.117.0" targetFramework="net48" />
<package id="System.Data.SQLite.Core" version="1.0.117.0" targetFramework="net48" />
</packages>

View File

@ -40,8 +40,8 @@
<AssemblyOriginatorKeyFile>..\bsmdKey.snk</AssemblyOriginatorKeyFile>
</PropertyGroup>
<ItemGroup>
<Reference Include="log4net, Version=3.2.0.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<HintPath>..\packages\log4net.3.2.0\lib\net462\log4net.dll</HintPath>
<Reference Include="log4net, Version=3.1.0.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<HintPath>..\packages\log4net.3.1.0\lib\net462\log4net.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
@ -52,8 +52,8 @@
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
<Reference Include="WinSCPnet, Version=1.16.0.16364, Culture=neutral, PublicKeyToken=2271ec4a3c56d0bf, processorArchitecture=MSIL">
<HintPath>..\packages\WinSCP.6.5.3\lib\net40\WinSCPnet.dll</HintPath>
<Reference Include="WinSCPnet, Version=1.16.0.16311, Culture=neutral, PublicKeyToken=2271ec4a3c56d0bf, processorArchitecture=MSIL">
<HintPath>..\packages\WinSCP.6.5.1\lib\net40\WinSCPnet.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
@ -93,12 +93,12 @@
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="..\packages\WinSCP.6.5.3\build\WinSCP.targets" Condition="Exists('..\packages\WinSCP.6.5.3\build\WinSCP.targets')" />
<Import Project="..\packages\WinSCP.6.5.1\build\WinSCP.targets" Condition="Exists('..\packages\WinSCP.6.5.1\build\WinSCP.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\packages\WinSCP.6.5.3\build\WinSCP.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\WinSCP.6.5.3\build\WinSCP.targets'))" />
<Error Condition="!Exists('..\packages\WinSCP.6.5.1\build\WinSCP.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\WinSCP.6.5.1\build\WinSCP.targets'))" />
</Target>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.

View File

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="log4net" version="3.2.0" targetFramework="net48" />
<package id="WinSCP" version="6.5.3" targetFramework="net48" />
<package id="log4net" version="3.1.0" targetFramework="net48" />
<package id="WinSCP" version="6.5.1" targetFramework="net48" />
</packages>

View File

@ -5,6 +5,8 @@ using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Runtime.Serialization;
namespace bsmd.database
{
@ -54,9 +56,6 @@ namespace bsmd.database
[MaxLength(99)]
public string AgentEMail { get; set; }
[MaxLength(99)]
public string WasteDisposalServiceProviderName { get; set; }
#endregion
#region DatabaseEntity implementation
@ -87,8 +86,6 @@ namespace bsmd.database
else scmd.Parameters.AddWithValue("@P10", DBNull.Value);
if (this.AgentEMail != null) scmd.Parameters.AddWithValue("@P11", this.AgentEMail);
else scmd.Parameters.AddWithValue("@P11", DBNull.Value);
if (this.WasteDisposalServiceProviderName != null) scmd.Parameters.AddWithValue("@P12", this.WasteDisposalServiceProviderName);
else scmd.Parameters.AddWithValue("@P12", DBNull.Value);
if (this.IsNew)
{
@ -96,13 +93,13 @@ namespace bsmd.database
scmd.Parameters.AddWithValue("@ID", this.Id);
cmd.CommandText = string.Format("INSERT INTO {0} (Id, Title, AgentCompanyName, AgentStreetAndNumber, " +
"AgentPostalCode, AgentCity, AgentCountry, AgentLastName, AgentFirstName, AgentPhone, AgentFax, " +
"AgentEMail, WasteDisposalServiceProviderName) VALUES (@ID, @P1, @P2, @P3, @P4, @P5, @P6, @P7, @P8, @P9, @P10, @P11, @P12)", this.Tablename);
"AgentEMail) VALUES (@ID, @P1, @P2, @P3, @P4, @P5, @P6, @P7, @P8, @P9, @P10, @P11)", this.Tablename);
}
else
{
cmd.CommandText = string.Format("UPDATE {0} SET Title = @P1, AgentCompanyName = @P2, AgentStreetAndNumber = @P3, AgentPostalCode = @P4, AgentCity = @P5, " +
"AgentCountry = @P6, AgentLastName = @P7, AgentFirstName = @P8, AgentPhone = @P9, AgentFax = @P10, " +
"AgentEMail = @P11, WasteDisposalServiceProviderName = @P12 WHERE Id = @ID", this.Tablename);
"AgentEMail = @P11 WHERE Id = @ID", this.Tablename);
scmd.Parameters.AddWithValue("@ID", this.Id);
}
}
@ -110,7 +107,7 @@ namespace bsmd.database
public override void PrepareLoadCommand(System.Data.IDbCommand cmd, Message.LoadFilter filter, params object[] criteria)
{
string query = string.Format("SELECT Id, Title, AgentCompanyName, AgentStreetAndNumber, AgentPostalCode, AgentCity, AgentCountry, " +
"AgentLastName, AgentFirstName, AgentPhone, AgentFax, AgentEMail, WasteDisposalServiceProviderName FROM {0} ", this.Tablename);
"AgentLastName, AgentFirstName, AgentPhone, AgentFax, AgentEMail FROM {0} ", this.Tablename);
switch (filter)
{
@ -141,7 +138,6 @@ namespace bsmd.database
if (!reader.IsDBNull(9)) agnt_t.AgentPhone = reader.GetString(9);
if (!reader.IsDBNull(10)) agnt_t.AgentFax = reader.GetString(10);
if (!reader.IsDBNull(11)) agnt_t.AgentEMail = reader.GetString(11);
if (!reader.IsDBNull(12)) agnt_t.WasteDisposalServiceProviderName = reader.GetString(12);
result.Add(agnt_t);
}
@ -176,7 +172,6 @@ namespace bsmd.database
if (!reader.IsDBNull(9)) agnt_t.AgentPhone = reader.GetString(9);
if (!reader.IsDBNull(10)) agnt_t.AgentFax = reader.GetString(10);
if (!reader.IsDBNull(11)) agnt_t.AgentEMail = reader.GetString(11);
if (!reader.IsDBNull(12)) agnt_t.WasteDisposalServiceProviderName = reader.GetString(12);
}
return agnt_t;
}

View File

@ -137,8 +137,8 @@ namespace bsmd.database
}
}
//[ENI2Validation]
//[MaxLength(256)]
[ENI2Validation]
[MaxLength(256)]
public string Effects { get; set; }
[ENI2Validation]

View File

@ -112,17 +112,7 @@ namespace bsmd.database
return (await at.LoadListAsync(reader)).ConvertAll(x => (AGNT_Template)x);
}
public static async Task<List<SERV_Template>> GetSERVTemplatesAsync()
{
SqlCommand cmd = new SqlCommand();
SERV_Template st = new SERV_Template();
st.PrepareLoadCommand(cmd, Message.LoadFilter.ALL);
SqlDataReader reader = await PerformCommandAsync(cmd);
return (await st.LoadListAsync(reader)).ConvertAll(x => (SERV_Template)x);
}
public static async Task<List<WasteDisposalServiceProvider_Template>> GetWasteDisposalServiceProviderTemplatesAsync()
public static async Task<List<WasteDisposalServiceProvider_Template>> GetWastDisposalServiceProviderTemplatesAsync()
{
SqlCommand cmd = new SqlCommand();
WasteDisposalServiceProvider_Template wdsp_t = new WasteDisposalServiceProvider_Template();

View File

@ -1,92 +0,0 @@
// Copyright (c) 2024-present schick Informatik
// Description: Collection of classes for the customs XML upload app
using System;
using System.Collections.ObjectModel;
using System.Xml.Serialization;
namespace bsmd.database.EasyPeasy
{
// Root: <proofRequest>
[XmlRoot("proofRequest")]
public class ProofRequest
{
public string DelegateIdentificationType { get; set; }
public string TraderIdentificationType { get; set; }
public string LRN { get; set; }
public string TraderIdentificationNumber { get; set; }
public string Country { get; set; }
public ProofInformationT2LT2LF ProofInformationT2LT2LF { get; set; }
public string DelegateIdentificationNumber { get; set; }
}
public class ProofInformationT2LT2LF
{
public string CompetentCustomsOffice { get; set; }
public string DeclarationType { get; set; }
public DateTime DeclarationDate { get; set; }
public decimal TotalGrossMassKg { get; set; }
public RequestedValidityOfTheProof RequestedValidityOfTheProof { get; set; }
public GoodsShipmentForT2LT2LF GoodsShipmentForT2LT2LF { get; set; }
public string RequestType { get; set; }
}
public class RequestedValidityOfTheProof
{
public int NumberOfDays { get; set; }
}
public class GoodsShipmentForT2LT2LF
{
public bool ContainerIndication { get; set; }
public LocationOfGoods LocationOfGoods { get; set; }
[XmlElement("GoodsItemsForT2LT2LF")]
public ObservableCollection<GoodsItemForT2LT2LF> GoodsItemsForT2LT2LF { get; set; } = new ObservableCollection<GoodsItemForT2LT2LF>();
public TransportDocuments TransportDocuments { get; set; }
}
public class LocationOfGoods
{
public string TypeOfLocation { get; set; }
public string QualifierOfIdentification { get; set; }
public string UNLocode { get; set; }
}
public class GoodsItemForT2LT2LF
{
public Commodity Commodity { get; set; } = new Commodity();
public int GoodsItemNumber { get; set; }
public string DescriptionOfGoods { get; set; }
public GoodsMeasure GoodsMeasure { get; set; } = new GoodsMeasure();
public Packaging Packaging { get; set; } = new Packaging();
}
public class Commodity
{
public string HarmonizedSystemSubHeadingCode { get; set; }
}
public class GoodsMeasure
{
public decimal GrossMass { get; set; }
public decimal NetMass { get; set; }
}
public class Packaging
{
public string ShippingMarks { get; set; }
public int NumberOfPackages { get; set; }
public string TypeOfPackages { get; set; }
}
public class TransportDocuments
{
public string Type { get; set; }
public string ReferenceNumber { get; set; }
}
}

View File

@ -68,10 +68,7 @@ namespace bsmd.database
while(reader.Read())
{
string type = "";
if (!reader.IsDBNull(4))
type = reader.GetString(4);
if (reader.IsDBNull(4)) continue; // this row has no type -> ignore
HAZPosTemplate hpt = new HAZPosTemplate();
hpt.Description = reader.GetString(0);
if (!reader.IsDBNull(1))
@ -84,7 +81,8 @@ namespace bsmd.database
if (specRefString.Equals("JA", StringComparison.OrdinalIgnoreCase) || specRefString.Equals("Yes", StringComparison.OrdinalIgnoreCase)) hpt.SpecRef15_19 = true;
if (specRefString.Equals("NEIN", StringComparison.OrdinalIgnoreCase) || specRefString.Equals("No", StringComparison.OrdinalIgnoreCase)) hpt.SpecRef15_19 = false;
}
string type = reader.GetString(4);
switch(type)
{
case "IBC": hpt.TemplateType = SublistType.IBC; break;
@ -92,7 +90,7 @@ namespace bsmd.database
case "IMSBC": hpt.TemplateType = SublistType.IMSBC ; break;
case "MARPOL": hpt.TemplateType = SublistType.MARPOL; break;
default:
break;
continue; // ignore this thing
}
if(!reader.IsDBNull(5))

View File

@ -216,8 +216,9 @@ namespace bsmd.database
errors.Add(RuleEngine.CreateError(ValidationCode.IMPLAUSIBLE, "PortArea", this.PortArea, "INFO", "", this.Tablename));
}
else
{
errors.Add(RuleEngine.CreateError(ValidationCode.PORTAREA, "PortArea", this.PortArea ?? "", "INFO", "", this.Tablename));
{
if(this.MessageCore.PoC != "DEHAM")
errors.Add(RuleEngine.CreateError(ValidationCode.PORTAREA, "PortArea", this.PortArea ?? "", "INFO", "", this.Tablename));
}
if(DeplacementSummerDraught_TNE.HasValue)

View File

@ -6,6 +6,9 @@ using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bsmd.database
{

View File

@ -66,32 +66,32 @@ namespace bsmd.database
/// NSW notification class
/// </summary>
public enum NotificationClass
{
{
VISIT, // 0
TRANSIT, // 1
NOA_NOD, // 2
ATA,
ATD,
ATA,
ATD,
SEC, // 5
POBA,
POBD,
NAME,
TIEFA,
POBA,
POBD,
NAME,
TIEFA,
TIEFD, // 10
BKRA,
BKRD,
STAT,
LADG,
BKRA,
BKRD,
STAT,
LADG,
INFO, // 15
SERV,
PRE72H,
MDH,
WAS,
SERV,
PRE72H,
MDH,
WAS,
CREWA, // 20
PASA,
BPOL,
TOWA,
TOWD,
PASA,
BPOL,
TOWA,
TOWD,
HAZA, // 25
HAZD,
AGNT,
@ -145,7 +145,7 @@ namespace bsmd.database
WASRCPT_ID,
BY_FILE_SEQ_NUM,
BY_TYPE
}
}
/// <summary>
/// Message Status einer NSW Einzelnachricht
@ -182,7 +182,7 @@ namespace bsmd.database
[Description("HIS-Nord")]
DUDR,
[Description("dbh / Maersk")]
DBH_MAERSK
}
@ -213,7 +213,7 @@ namespace bsmd.database
/// <summary>
/// Dieser Wert wird vom NSW / HIS vergeben
/// </summary>
public string ClientRequestId { set; get; }
public string ClientRequestId { set; get; }
public Guid? MessageId { get; set; }
@ -269,15 +269,6 @@ namespace bsmd.database
/// </summary>
public BSMDStatus InternalStatus { get; set; }
/// <summary>
/// Display helper property for overview status
/// </summary>
public string BSMDStatusOverviewDisplay {
get {
return (InternalStatus != BSMDStatus.UNDEFINED) ? InternalStatus.ToString() : "";
}
}
/// <summary>
/// Vorheriger Status (z.B. für nach der Report-Generierung), wird nicht immer gesetzt
/// </summary>
@ -293,17 +284,6 @@ namespace bsmd.database
/// </summary>
public NSWProvider HIS { get; set; }
/// <summary>
/// Display helper property for overview HIS
/// </summary>
public string HISOverviewDisplay
{
get
{
return (HIS != NSWProvider.UNDEFINED) ? HIS.ToString() : string.Empty;
}
}
/// <summary>
/// Fehlerliste (Rückgabe vom NSW)
/// </summary>
@ -426,17 +406,6 @@ namespace bsmd.database
/// </summary>
public int? FileSequenceNumber { get; set; }
/// <summary>
/// Number of violations during last validation
/// </summary>
public int? ViolationCount { get; set; }
/// <summary>
/// Number of errors during last validation
/// </summary>
public int? ErrorCount { get; set; }
#endregion
#region IDatabaseEntity implementation

View File

@ -34,64 +34,37 @@ namespace bsmd.database
public static void Enqueue(Message.NSWProvider provider, Message message)
{
// Validate inputs
if (message == null)
{
_log.ErrorFormat("Enqueue called with null message for provider {0}", provider);
return;
}
if (!message.Id.HasValue)
{
_log.ErrorFormat("Enqueue called with message that has no Id assigned for provider {0}", provider);
return;
}
if (!_telemetry.ContainsKey(provider))
_telemetry.Add(provider, new Dictionary<Guid, MessageTelemetry>());
Guid messageId = message.Id.Value;
if (_telemetry[provider].ContainsKey(messageId))
if (_telemetry[provider].ContainsKey(message.Id.Value))
{
_telemetry[provider][messageId].NumTries++;
_telemetry[provider][message.Id.Value].NumTries++;
}
else
{
MessageTelemetry mt = new MessageTelemetry();
mt.SendDate = DateTime.Now;
mt.NumTries = 1;
_telemetry[provider][messageId] = mt;
_telemetry[provider][message.Id.Value] = mt;
}
}
public static void Dequeue(Message.NSWProvider provider, Message message)
{
if (message == null)
{
_log.ErrorFormat("Dequeue called with null message for provider {0}", provider);
return;
}
if (!message.Id.HasValue)
{
_log.ErrorFormat("Dequeue called with message that has no Id assigned for provider {0}", provider);
return;
}
if (_telemetry.ContainsKey(provider))
{
Guid messageId = message.Id.Value;
if (_telemetry[provider].ContainsKey(messageId))
if (_telemetry[provider].ContainsKey(message.Id.Value))
{
MessageTelemetry mt = _telemetry[provider][messageId];
_log.InfoFormat("[{0,10}][{1,8}][{2:00000}][{3:00}] ", provider, message.MessageNotificationClassDisplay, (DateTime.Now - mt.SendDate).TotalSeconds, mt.NumTries);
_telemetry[provider].Remove(messageId);
MessageTelemetry mt = _telemetry[provider][message.Id.Value];
_log.InfoFormat("[{0,10}][{1,8}][{2:00000}][{3:00}] ",provider, message.MessageNotificationClassDisplay, (DateTime.Now - mt.SendDate).TotalSeconds, mt.NumTries);
_telemetry[provider].Remove(message.Id.Value);
}
else
{
// this can happen if the service gets re-started and not all sent messages have yet been received
_log.WarnFormat("trying to deque a message from telemetry that we don't know about. Provider: {0} MessageId: {1}",
provider.ToString(), messageId);
provider.ToString(), message.Id.Value);
}
}
}

View File

@ -2,6 +2,6 @@
[assembly: AssemblyCompany("schick Informatik")]
[assembly: AssemblyProduct("BSMD NSW interface")]
[assembly: AssemblyInformationalVersion("7.2.14")]
[assembly: AssemblyInformationalVersion("7.2.8")]
[assembly: AssemblyCopyright("Copyright © 2014-2025 schick Informatik")]
[assembly: AssemblyTrademark("")]

View File

@ -1,4 +1,4 @@
using System.Reflection;
[assembly: AssemblyVersion("7.2.14.*")]
[assembly: AssemblyVersion("7.2.8.*")]

View File

@ -97,22 +97,6 @@ namespace bsmd.database
#endregion
#region for extra waste validation
private static readonly HashSet<string> SpecialNextPortPrefixes = new HashSet<string>
{
"BE", "BG", "DK", "DE", "EE", "FI", "FR", "GR", "IR", "IT",
"HR", "LV", "LT", "LU", "MT", "NL", "AT", "PL", "PT", "RO",
"SE", "SK", "SL", "ES", "CZ", "HU", "CY", "NO", "IS", "GB", "GI"
};
private static readonly HashSet<string> SpecialNextPortExact = new HashSet<string>
{
"RUPRI", "RUULU", "RULED", "RUBLT", "RUKGD", "RUVYS"
};
#endregion
public enum LocodeMode
{
STANDARD,
@ -147,20 +131,6 @@ namespace bsmd.database
public static LocodeValidHandler LocodeChecker { get { return _locodeChecker; } }
public static NationalityValidHandler NationalityChecker { get { return _nationalityChecker; } }
/// <summary>
/// Used to test for special next port values for waste messages
/// </summary>
/// <param name="nextPort">a locode</param>
/// <returns>true if the next port is a special waste port</returns>
public static bool IsSpecialNextPort(string nextPort)
{
if (string.IsNullOrEmpty(nextPort) || nextPort.Length < 2)
return false;
return SpecialNextPortExact.Contains(nextPort) ||
SpecialNextPortPrefixes.Contains(nextPort.Substring(0, 2));
}
#region public static property validation
public static void RegisterLocodeChecker(LocodeValidHandler handler) { _locodeChecker = handler; }

View File

@ -1,128 +0,0 @@
// Copyright (c) 2024-present schick Informatik
// Description:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace bsmd.database
{
public class SERV_Template : DatabaseEntityAsync, IComparable
{
#region Construction
public SERV_Template()
{
this.tablename = "[dbo].[SERV_template]";
}
#endregion
#region Properties
[MaxLength(99)]
public string ServiceName { get; set; }
[MaxLength(255)]
public string ServiceBeneficiary { get; set; }
[MaxLength(255)]
public string ServiceInvoiceRecipient { get; set; }
#endregion
#region DatabaseEntity implementation
public override void PrepareSave(IDbCommand cmd)
{
SqlCommand scmd = cmd as SqlCommand;
if (this.ServiceName != null) scmd.Parameters.AddWithValue("@P1", this.ServiceName);
else scmd.Parameters.AddWithValue("@P1", DBNull.Value);
if (this.ServiceBeneficiary != null) scmd.Parameters.AddWithValue(@"P2", this.ServiceBeneficiary);
else scmd.Parameters.AddWithValue("@P2", DBNull.Value);
if (this.ServiceInvoiceRecipient != null) scmd.Parameters.AddWithValue("@P3", this.ServiceInvoiceRecipient);
else scmd.Parameters.AddWithValue("@P3", DBNull.Value);
if (this.IsNew)
{
this.CreateId();
cmd.CommandText = string.Format("INSERT INTO {0} (Id, ServiceName, ServiceBeneficiary, ServiceInvoiceRecipient) VALUES " +
"(@ID, @P1, @P2, @P3)", this.Tablename);
}
else
{
cmd.CommandText = string.Format("UPDATE {0} SET ServiceName = @P1, ServiceBeneficiary = @P2, ServiceInvoiceRecipient = @P3 WHERE Id = @ID", this.Tablename);
}
scmd.Parameters.AddWithValue("@ID", this.Id);
}
public override void PrepareLoadCommand(IDbCommand cmd, Message.LoadFilter filter, params object[] criteria)
{
string query = string.Format("SELECT Id, ServiceName, ServiceBeneficiary, ServiceInvoiceRecipient FROM {0}", this.Tablename);
switch (filter)
{
case Message.LoadFilter.ALL:
default:
break;
}
cmd.CommandText = query;
}
public override List<DatabaseEntity> LoadList(System.Data.IDataReader reader)
{
List<DatabaseEntity> result = new List<DatabaseEntity>();
while (reader.Read())
{
SERV_Template serv_t = new SERV_Template();
serv_t.id = reader.GetGuid(0);
if (!reader.IsDBNull(1)) serv_t.ServiceName = reader.GetString(1);
if (!reader.IsDBNull(2)) serv_t.ServiceBeneficiary = reader.GetString(2);
if (!reader.IsDBNull(3)) serv_t.ServiceInvoiceRecipient = reader.GetString(3);
result.Add(serv_t);
}
reader.Close();
return result;
}
protected override DatabaseEntityAsync ReadRowFromReader(IDataReader reader)
{
SERV_Template serv_t = null;
if (reader != null)
{
serv_t = new SERV_Template();
serv_t.id = reader.GetGuid(0);
if (!reader.IsDBNull(1)) serv_t.ServiceName = reader.GetString(1);
if (!reader.IsDBNull(2)) serv_t.ServiceBeneficiary = reader.GetString(2);
if (!reader.IsDBNull(3)) serv_t.ServiceInvoiceRecipient = reader.GetString(3);
}
return serv_t;
}
#endregion
#region IComparable implementation
public int CompareTo(object obj)
{
if (obj is SERV_Template template)
{
return this.ServiceName.CompareTo(template.ServiceName);
}
return 0;
}
#endregion
}
}

View File

@ -502,7 +502,7 @@ namespace bsmd.database
/// Convenience Methode, die fehlende Waste Einträge ergänzt. Verbesserte Version, aus ENI-2 herüberkopiert, damit es auch im
/// Excel_Reader nutzbar wird
/// </summary>
public void AddMissingWaste(bool fixExisting = true)
public void AddMissingWaste()
{
foreach (string wasteCodeString in WAS.WasteCodes)
@ -538,15 +538,12 @@ namespace bsmd.database
}
else
{
if (fixExisting)
{
if (!foundWaste.WasteAmountGeneratedTillNextPort_MTQ.HasValue) foundWaste.WasteAmountGeneratedTillNextPort_MTQ = 0;
if (!foundWaste.WasteAmountRetained_MTQ.HasValue) foundWaste.WasteAmountRetained_MTQ = 0;
if (!foundWaste.WasteCapacity_MTQ.HasValue) foundWaste.WasteCapacity_MTQ = 0;
if (foundWaste.WasteDescription.IsNullOrEmpty() && foundWaste.IsDashWasteCode) foundWaste.WasteDescription = "-";
if (!foundWaste.WasteDisposalAmount_MTQ.HasValue) foundWaste.WasteDisposalAmount_MTQ = 0;
if (foundWaste.WasteDisposalPort.IsNullOrEmpty()) foundWaste.WasteDisposalPort = "ZZUKN";
}
if (!foundWaste.WasteAmountGeneratedTillNextPort_MTQ.HasValue) foundWaste.WasteAmountGeneratedTillNextPort_MTQ = 0;
if (!foundWaste.WasteAmountRetained_MTQ.HasValue) foundWaste.WasteAmountRetained_MTQ = 0;
if (!foundWaste.WasteCapacity_MTQ.HasValue) foundWaste.WasteCapacity_MTQ = 0;
if (foundWaste.WasteDescription.IsNullOrEmpty() && foundWaste.IsDashWasteCode) foundWaste.WasteDescription = "-";
if (!foundWaste.WasteDisposalAmount_MTQ.HasValue) foundWaste.WasteDisposalAmount_MTQ = 0;
if (foundWaste.WasteDisposalPort.IsNullOrEmpty()) foundWaste.WasteDisposalPort = "ZZUKN";
}
}
}

View File

@ -146,13 +146,6 @@ namespace bsmd.database
};
this.WasteReceived.Add(foundWasteReceived);
}
else
{
if (!foundWasteReceived.AmountWasteReceived_MTQ.HasValue)
{
foundWasteReceived.AmountWasteReceived_MTQ = 0;
}
}
if (foundWasteReceived.WasteDescription.IsNullOrEmpty())
{

View File

@ -266,13 +266,11 @@ namespace bsmd.database
if (this.WasteAmountGeneratedTillNextPort_MTQ >= 10000)
errors.Add(RuleEngine.CreateError(ValidationCode.IMPLAUSIBLE, "Waste generated till next port too high", null, this.Title, this.Identifier, this.Tablename));
// Removed this for version 7.2.14 (new rules depending on next port implemented in ENI / DetailRootControl.cs)
if(this.WasteDisposalAmount_MTQ > this.WasteCapacity_MTQ)
violations.Add(RuleEngine.CreateViolation(ValidationCode.IMPLAUSIBLE, "Disposal greater than capacity!", null, this.Title, this.Identifier, this.Tablename));
// if(this.WasteDisposalAmount_MTQ > this.WasteCapacity_MTQ)
// violations.Add(RuleEngine.CreateViolation(ValidationCode.IMPLAUSIBLE, "Disposal greater than capacity!", null, this.Title, this.Identifier, this.Tablename));
// if((this.WasteAmountGeneratedTillNextPort_MTQ + this.WasteAmountRetained_MTQ) > this.WasteCapacity_MTQ)
// violations.Add(RuleEngine.CreateViolation(ValidationCode.IMPLAUSIBLE, "Waste generated+retained greater than capacity!", null, this.Title, this.Identifier, this.Tablename));
if((this.WasteAmountGeneratedTillNextPort_MTQ + this.WasteAmountRetained_MTQ) > this.WasteCapacity_MTQ)
violations.Add(RuleEngine.CreateViolation(ValidationCode.IMPLAUSIBLE, "Waste generated+retained greater than capacity!", null, this.Title, this.Identifier, this.Tablename));
}
#endregion

View File

@ -98,7 +98,7 @@ namespace bsmd.database
public int CompareTo(object obj)
{
if (obj is WasteDisposalServiceProvider_Template template)
return this.Remark?.CompareTo(template.Remark ?? "") ?? 0;
this.Remark?.CompareTo(template.Remark ?? "");
return 0;
}

View File

@ -76,7 +76,7 @@ namespace bsmd.database
wasteReceived.id = reader.GetGuid(0);
if (!reader.IsDBNull(1)) wasteReceived.WasteCode = reader.GetString(1);
if (!reader.IsDBNull(2)) wasteReceived.WasteDescription = reader.GetString(2);
if (!reader.IsDBNull(3)) wasteReceived.AmountWasteReceived_MTQ = (float)reader.GetDouble(3);
if (!reader.IsDBNull(3)) wasteReceived.AmountWasteReceived_MTQ = (float)reader.GetDouble(3);
if (!reader.IsDBNull(4)) wasteReceived.Identifier = reader.GetString(4);
result.Add(wasteReceived);
}
@ -111,7 +111,7 @@ namespace bsmd.database
scmd.Parameters.AddWithValue("@P1", this.WAS_RCPT.Id);
scmd.Parameters.AddWithNullableValue("@P2", this.WasteCode);
scmd.Parameters.AddWithNullableValue("@P3", this.WasteDescription);
scmd.Parameters.AddWithNullableValue("@P4", this.AmountWasteReceived_MTQ);
scmd.Parameters.AddWithNullableValue("@P4", this.AmountWasteReceived_MTQ);
scmd.Parameters.AddWithNullableValue("@P5", this.Identifier);
if (this.IsNew)

View File

@ -89,11 +89,11 @@
<UseWinFormsOutOfProcDesigner>False</UseWinFormsOutOfProcDesigner>
</PropertyGroup>
<ItemGroup>
<Reference Include="log4net, Version=3.2.0.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<HintPath>..\ENI2\packages\log4net.3.2.0\lib\net462\log4net.dll</HintPath>
<Reference Include="log4net, Version=3.1.0.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<HintPath>..\packages\log4net.3.1.0\lib\net462\log4net.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.13.0.4\lib\net45\Newtonsoft.Json.dll</HintPath>
<HintPath>..\ENI2\packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="PresentationCore" />
<Reference Include="PresentationFramework" />
@ -119,7 +119,6 @@
<Compile Include="Customer.cs" />
<Compile Include="DatabaseEntityAsync.cs" />
<Compile Include="DBManagerAsync.cs" />
<Compile Include="EasyPeasy.cs" />
<Compile Include="Extensions.cs" />
<Compile Include="HAZ.cs" />
<Compile Include="HAZPosTemplate.cs" />
@ -174,7 +173,6 @@
<Compile Include="SanitaryMeasuresDetail.cs" />
<Compile Include="SEC.cs" />
<Compile Include="SERV.cs" />
<Compile Include="SERV_Template.cs" />
<Compile Include="ShipToShipActivitiesDuringLastTenPortFacilitiesCalled.cs" />
<Compile Include="ShowReportAttribute.cs" />
<Compile Include="SOAPLoggerExtension.cs" />
@ -212,7 +210,7 @@
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>

View File

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="log4net" version="3.2.0" targetFramework="net48" />
<package id="Newtonsoft.Json" version="13.0.4" targetFramework="net48" />
<package id="log4net" version="3.1.0" targetFramework="net48" />
<package id="Newtonsoft.Json" version="13.0.3" targetFramework="net48" />
</packages>

View File

@ -38,8 +38,8 @@
<AssemblyOriginatorKeyFile>..\bsmdKey.snk</AssemblyOriginatorKeyFile>
</PropertyGroup>
<ItemGroup>
<Reference Include="log4net, Version=3.2.0.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<HintPath>..\packages\log4net.3.2.0\lib\net462\log4net.dll</HintPath>
<Reference Include="log4net, Version=3.1.0.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a, processorArchitecture=MSIL">
<HintPath>..\packages\log4net.3.1.0\lib\net462\log4net.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />

Some files were not shown because too many files have changed in this diff Show More