Add logic for import of combination from xls files

This commit is contained in:
Evgeny Redikultsev
2025-01-18 22:13:11 +05:00
parent 13c3022c2f
commit f508399846
43 changed files with 1140 additions and 227 deletions

View File

@@ -85,12 +85,10 @@
<Setter Property="Background" Value="#FFA19BC3"/>
<Setter Property="BorderBrush" Value="Black"/>
</Style>
<Style x:Key="ToolButton24" TargetType="Button" BasedOn="{StaticResource ToolButton}">
<Setter Property="Height" Value="24"/>
<Setter Property="Width" Value="24"/>
</Style>
<Style x:Key="ButtonImage16" TargetType="Image">
<Setter Property="Height" Value="16"/>
<Setter Property="Width" Value="16"/>
@@ -116,16 +114,13 @@
<Setter Property="HorizontalAlignment" Value="Center"/>
<Setter Property="VerticalAlignment" Value="Center"/>
</Style>
<Style x:Key="ButtonCalculatorCanvas" TargetType="Canvas" BasedOn="{StaticResource ButtonCanvas}">
<Setter Property="Background" Value="{DynamicResource CalculatorCanvas}"/>
</Style>
<Style x:Key="ButtonResultCanvas" TargetType="Canvas" BasedOn="{StaticResource ButtonCanvas}">
<Setter Property="Background" Value="{DynamicResource ResultCanvas}"/>
</Style>
<Style x:Key="ButtonRect" TargetType="Rectangle">
<Setter Property="Margin" Value="3"/>
<Setter Property="Width" Value="26"/>
@@ -412,10 +407,20 @@
</Canvas>
</DataTemplate>
<DataTemplate x:Key="Report">
<Canvas Style="{DynamicResource ButtonResultCanvas}">
<Canvas.Children>
<ContentControl ContentTemplate="{DynamicResource ButtonResultRectangle}"/>
<ContentControl Canvas.Top="5" Canvas.Left="6" ContentTemplate="{DynamicResource Document}"/>
<ContentControl Canvas.Top="8" Canvas.Left="10" ContentTemplate="{DynamicResource Document}"/>
<ContentControl Canvas.Top="11" Canvas.Left="14" ContentTemplate="{DynamicResource Document}"/>
</Canvas.Children>
</Canvas>
</DataTemplate>
<DataTemplate x:Key="ExportToXLS">
<Canvas Style="{DynamicResource ButtonResultCanvas}">
<Canvas.Children>
<!--<ContentControl ContentTemplate="{DynamicResource ButtonResultRectangle}"/>-->
<ContentControl ContentTemplate="{DynamicResource Table}"/>
<TextBlock Text="CSV" FontSize="8" FontWeight="Bold" Margin="4,2,0,2"/>
<TextBlock Text="XLS" FontSize="12" FontWeight="Bold" FontStyle="Italic" Margin="6,14,0,2"/>
@@ -474,6 +479,21 @@
</Canvas>
</DataTemplate>
<DataTemplate x:Key="Settings">
<Canvas Style="{DynamicResource ButtonResultCanvas}">
<Canvas.Children>
<Path Margin="4" Data="M8,8 v-6 l-4,-4
a7,7 90 0 1 7,10
l12,12 v3 h-3 l-12,-12
a7,7 90 0 1 -10,-7
l4,4
z" Fill="DarkGray" Stroke="Black"/>
<Ellipse Height="2" Width="2" Fill="White" Canvas.Left="24" Canvas.Top="24"/>
<Ellipse Height="5" Width="5" Fill="White" Canvas.Left="6" Canvas.Top="6"/>
</Canvas.Children>
</Canvas>
</DataTemplate>
<DataTemplate x:Key="Diagrams">
<Canvas Style="{DynamicResource ButtonResultCanvas}">
<Canvas.Children>

View File

@@ -36,20 +36,23 @@
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="CombinationListTemplate">
<DataGrid x:Name="ForceGrid" Style="{StaticResource ItemsDataGrid}">
<DataGrid.Columns>
<DataGridComboBoxColumn Header="Limit state" Width="80" MinWidth="70" SelectedItemBinding="{Binding LimitState}" ItemsSource="{Binding Source={StaticResource LimitStateEnum}}"/>
<DataGridComboBoxColumn Header="Duration" Width="80" MinWidth="70" SelectedItemBinding="{Binding CalcTerm}" ItemsSource="{Binding Source={StaticResource CalcTermEnum}}"/>
<DataGridTextColumn Header="Moment Mx" Width="85" Binding="{Binding ForceTuple.Mx, Converter={StaticResource MomentConverter}, ValidatesOnExceptions=True}"/>
<DataGridTextColumn Header="Moment My" Width="85" Binding="{Binding ForceTuple.My, Converter={StaticResource MomentConverter}, ValidatesOnExceptions=True}"/>
<DataGridTextColumn Header="Force Nz" Width="85" Binding="{Binding ForceTuple.Nz, Converter={StaticResource ForceConverter}, ValidatesOnExceptions=True}"/>
</DataGrid.Columns>
</DataGrid>
</DataTemplate>
<DataTemplate x:Key="CombinationListTemplateWithButton">
<Grid Grid.Row="1" DataContext="{Binding DesignForces}">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="80"/>
</Grid.ColumnDefinitions>
<DataGrid x:Name="ForceGrid" Style="{StaticResource ItemsDataGrid}">
<DataGrid.Columns>
<DataGridComboBoxColumn Header="Limit state" Width="80" MinWidth="70" SelectedItemBinding="{Binding LimitState}" ItemsSource="{Binding Source={StaticResource LimitStateEnum}}"/>
<DataGridComboBoxColumn Header="Duration" Width="80" MinWidth="70" SelectedItemBinding="{Binding CalcTerm}" ItemsSource="{Binding Source={StaticResource CalcTermEnum}}"/>
<DataGridTextColumn Header="Moment Mx" Width="85" Binding="{Binding ForceTuple.Mx, Converter={StaticResource MomentConverter}, ValidatesOnExceptions=True}"/>
<DataGridTextColumn Header="Moment My" Width="85" Binding="{Binding ForceTuple.My, Converter={StaticResource MomentConverter}, ValidatesOnExceptions=True}"/>
<DataGridTextColumn Header="Force Nz" Width="85" Binding="{Binding ForceTuple.Nz, Converter={StaticResource ForceConverter}, ValidatesOnExceptions=True}"/>
</DataGrid.Columns>
</DataGrid>
<ContentControl ContentTemplate="{StaticResource CombinationListTemplate}" Content="{Binding}"/>
<StackPanel Grid.Column="1">
<Button Style="{StaticResource AddButton}"/>
<Button Style="{StaticResource DeleteButton}"/>

View File

@@ -48,6 +48,9 @@
<Compile Update="Windows\Forces\ForceCombinationFromFileView.xaml.cs">
<SubType>Code</SubType>
</Compile>
<Compile Update="Windows\Forces\ForceCombinationViewerView.xaml.cs">
<SubType>Code</SubType>
</Compile>
<Compile Update="Windows\Forces\ForceFilePropertyView.xaml.cs">
<SubType>Code</SubType>
</Compile>
@@ -164,6 +167,9 @@
<Page Update="Windows\Forces\ForceCombinationFromFileView.xaml">
<SubType>Designer</SubType>
</Page>
<Page Update="Windows\Forces\ForceCombinationViewerView.xaml">
<SubType>Designer</SubType>
</Page>
<Page Update="Windows\Forces\ForceFilePropertyView.xaml">
<SubType>Designer</SubType>
</Page>

View File

@@ -0,0 +1,76 @@
using StructureHelper.Infrastructure;
using StructureHelperCommon.Models.Forces;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StructureHelper.Windows.Forces
{
public class ColumnPropertyVM : ViewModelBase, IDataErrorInfo
{
private IColumnProperty model;
public ColumnPropertyVM(IColumnProperty model)
{
this.model = model;
}
public string this[string columnName]
{
get
{
string error = null;
if (columnName == nameof(Index))
{
if (Index < 0)
{
error = "Index must be greater or equal to zero";
}
}
return error;
}
}
public string Name
{
get => model.Name;
set
{
model.Name = value;
OnPropertyChanged(nameof(Name));
}
}
public string SearchingName
{
get => model.SearchingName;
set
{
model.SearchingName = value;
OnPropertyChanged(nameof(SearchingName));
}
}
public int Index
{
get => model.Index + 1;
set
{
model.Index = value - 1;
OnPropertyChanged(nameof(Index));
}
}
public double Factor
{
get => model.Factor;
set
{
model.Factor = value;
OnPropertyChanged(nameof(Factor));
}
}
public string Error => throw new NotImplementedException();
}
}

View File

@@ -18,7 +18,7 @@
</Grid.RowDefinitions>
<!--ForceTemplates.xaml-->
<ContentControl ContentTemplate="{StaticResource ResourceKey=ForceActionTemplate}" Content="{Binding}"/>
<ContentControl Grid.Row="1" ContentTemplate="{StaticResource ResourceKey=CombinationListTemplate}" Content="{Binding}"/>
<ContentControl Grid.Row="1" ContentTemplate="{StaticResource ResourceKey=CombinationListTemplateWithButton}" Content="{Binding}"/>
<ContentControl Grid.Row="2" ContentTemplate="{StaticResource OkCancelButtons}" Content="{Binding}"/>
</Grid>
</Window>

View File

@@ -0,0 +1,22 @@
using StructureHelper.Infrastructure;
using StructureHelperCommon.Models.Forces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StructureHelper.Windows.Forces
{
public class ForceCombinationViewerVM : ViewModelBase
{
private IForceAction model;
public List<IForceCombinationList> Combinations => model.GetCombinations();
public ForceCombinationViewerVM(IForceAction model)
{
this.model = model;
}
}
}

View File

@@ -0,0 +1,12 @@
<Window x:Class="StructureHelper.Windows.Forces.ForceCombinationViewerView"
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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:StructureHelper.Windows.Forces"
mc:Ignorable="d"
Title="Force Combination Viewer" Height="250" Width="400" MinHeight="250" MinWidth="400" MaxHeight="600" MaxWidth="1000" ResizeMode="CanResize" WindowStartupLocation="CenterScreen">
<Grid>
<ContentControl Grid.Row="1" ContentTemplate="{StaticResource ResourceKey=CombinationListTemplate}" Content="{Binding}"/>
</Grid>
</Window>

View File

@@ -0,0 +1,35 @@
using StructureHelperCommon.Models.Forces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace StructureHelper.Windows.Forces
{
/// <summary>
/// Interaction logic for ForceCombinationViewerView.xaml
/// </summary>
public partial class ForceCombinationViewerView : Window
{
ForceCombinationViewerVM viewModel;
public ForceCombinationViewerView(ForceCombinationViewerVM viewModel)
{
InitializeComponent();
this.viewModel = viewModel;
DataContext = this.viewModel;
}
public ForceCombinationViewerView(IForceAction action) : this (new ForceCombinationViewerVM(action))
{
}
}
}

View File

@@ -2,6 +2,7 @@
using StructureHelperCommon.Models.Forces;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
@@ -10,11 +11,15 @@ namespace StructureHelper.Windows.Forces
{
public class ForceFilePropertyVM : OkCancelViewModelBase
{
private IForceFileProperty model;
private IColumnedFileProperty model;
public ForceFilePropertyVM(IForceFileProperty model)
public ForceFilePropertyVM(IColumnedFileProperty model)
{
this.model = model;
foreach (var item in model.ColumnProperties)
{
ColumnProperties.Add(new ColumnPropertyVM(item));
}
}
public int SkipRowBeforeHeaderCount
@@ -54,7 +59,9 @@ namespace StructureHelper.Windows.Forces
}
}
public IForceFileProperty Model
public ObservableCollection<ColumnPropertyVM> ColumnProperties { get; set; } = new();
public IColumnedFileProperty Model
{
get
{

View File

@@ -8,7 +8,24 @@
mc:Ignorable="d"
Title="File import properties" Height="250" Width="400" ResizeMode="NoResize" WindowStartupLocation="CenterScreen">
<Window.Resources>
<DataTemplate x:Key="ColumnProperty">
<Expander Header="{Binding Name}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="25"/>
<RowDefinition Height="25"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Text="Column index"/>
<TextBox Grid.Row="0" Grid.Column="1" Text="{Binding Index, ValidatesOnDataErrors=True}"/>
<TextBlock Grid.Row="1" Text="Column factor"/>
<TextBox Grid.Row="1" Grid.Column="1" Text="{Binding Factor, Converter={StaticResource PlainDouble}, ValidatesOnDataErrors=True}"/>
</Grid>
</Expander>
</DataTemplate>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
@@ -30,21 +47,23 @@
<RowDefinition/>
</Grid.RowDefinitions>
<TextBlock Text="File name"/>
<TextBox Grid.Column="1" Text="{Binding FilePath}"/>
<TextBox Grid.Column="1" Text="{Binding FilePath}" IsEnabled="False"/>
<TextBlock Grid.Row="1" Text="Skip row(s) before header"/>
<TextBox Grid.Row="1" Grid.Column="1" Text="{Binding SkipRowBeforeHeaderCount, Converter={StaticResource PlainDouble}, ValidatesOnDataErrors=True}"/>
<TextBox Grid.Row="1" Grid.Column="1" Text="{Binding SkipRowBeforeHeaderCount, ValidatesOnDataErrors=True}"/>
<TextBlock Grid.Row="2" Text="Skip row(s) of header"/>
<TextBox Grid.Row="2" Grid.Column="1" Text="{Binding SkipRowHeaderCount, Converter={StaticResource PlainDouble}, ValidatesOnDataErrors=True}"/>
<TextBox Grid.Row="2" Grid.Column="1" Text="{Binding SkipRowHeaderCount, ValidatesOnDataErrors=True}"/>
<TextBlock Grid.Row="3" Text="Global factor value"/>
<TextBox Grid.Row="3" Grid.Column="1" Text="{Binding GlobalFactor, Converter={StaticResource PlainDouble}, ValidatesOnDataErrors=True}"/>
</Grid>
</TabItem>
<TabItem Header="Columns">
<ScrollViewer>
<Expander Header="Nz">
</Expander>
</ScrollViewer>
<ListBox ItemsSource="{Binding ColumnProperties}">
<ListBox.ItemTemplate>
<DataTemplate>
<ContentControl Width="350" ContentTemplate="{StaticResource ColumnProperty}" Content="{Binding}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</TabItem>
</TabControl>
<ContentControl Grid.Row="1" ContentTemplate="{StaticResource OkCancelButtons}" Content="{Binding}"/>

View File

@@ -1,4 +1,5 @@
using System;
using StructureHelperCommon.Models.Forces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -19,9 +20,18 @@ namespace StructureHelper.Windows.Forces
/// </summary>
public partial class ForceFilePropertyView : Window
{
public ForceFilePropertyView()
private ForceFilePropertyVM viewModel;
public ForceFilePropertyView(ForceFilePropertyVM viewModel)
{
InitializeComponent();
this.viewModel = viewModel;
this.viewModel.ParentWindow = this;
DataContext = this.viewModel;
}
public ForceFilePropertyView(IColumnedFileProperty fileProperty) : this (new ForceFilePropertyVM(fileProperty))
{
}
}
}

View File

@@ -1,5 +1,7 @@
using StructureHelper.Infrastructure;
using StructureHelper.Windows.ViewModels;
using StructureHelper.Windows.ViewModels.Errors;
using StructureHelperCommon.Infrastructures.Interfaces;
using StructureHelperCommon.Models;
using StructureHelperCommon.Models.Forces;
using StructureHelperCommon.Services.FileServices;
@@ -8,15 +10,19 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.Design;
using System.Windows.Input;
namespace StructureHelper.Windows.Forces
{
public class ListOfFilesVM : SelectItemVM<IForceFileProperty>
public class ListOfFilesVM : SelectItemVM<IColumnedFileProperty>
{
private ICommand openFileCommand;
public IShiftTraceLogger? TraceLogger;
private ICommand showSettingsCommand;
private IUpdateStrategy<IColumnedFileProperty> updateStrategy;
private ICommand showDocumentCommand;
public ICommand FileOpen => openFileCommand ?? (
openFileCommand = new RelayCommand(param =>
@@ -25,6 +31,43 @@ namespace StructureHelper.Windows.Forces
}
));
public ICommand ShowSettings => showSettingsCommand ?? (
showSettingsCommand = new RelayCommand(param =>
{
ShowSettingsMethod(param);
},o => SelectedItem is not null
));
public ICommand ShowDocument => showDocumentCommand ?? (
showDocumentCommand = new RelayCommand(param =>
{
SafetyProcessor.RunSafeProcess(ShowDocumentMethod, "Error of opening of settings");
}, o => SelectedItem is not null
));
private void ShowDocumentMethod()
{
if (SelectedItem is null) { return; }
}
private void ShowSettingsMethod(object param)
{
SafetyProcessor.RunSafeProcess(OpenSettingsWindow, "Error of opening of settings");
}
private void OpenSettingsWindow()
{
if (SelectedItem is null) { return; }
var clone = (IColumnedFileProperty)SelectedItem.Clone();
var wnd = new ForceFilePropertyView(SelectedItem);
wnd.ShowDialog();
if (! (bool)wnd.DialogResult)
{
updateStrategy ??= new ColumnedFilePropertyUpdateStrategy();
updateStrategy.Update(SelectedItem, clone);
}
}
private void OpenFileMethod(object param)
{
var result = GetFilePath();
@@ -32,15 +75,13 @@ namespace StructureHelper.Windows.Forces
{
return;
}
ForceFileProperty fileProperty = new()
{
FilePath = result.FilePath,
};
IColumnedFileProperty fileProperty = FilePropertyFactory.GetForceFileProperty(FilePropertyType.Forces);
fileProperty.FilePath = result.FilePath;
Collection.Add(fileProperty);
Refresh();
}
public ListOfFilesVM(List<IForceFileProperty> collection) : base(collection)
public ListOfFilesVM(List<IColumnedFileProperty> collection) : base(collection)
{
}

View File

@@ -113,6 +113,10 @@
Command="{Binding Add}"
CommandParameter="{x:Static enums:ActionType.ForceCombinationByFactor}"
Content="Fact" ToolTip="Add Factored Combination"/>
<Button Style="{StaticResource ToolButton}"
Command="{Binding Add}"
CommandParameter="{x:Static enums:ActionType.ForceCombinationFromFile}"
Content="File" ToolTip="Add Combination From File"/>
</ToolBar>
<ToolBar DataContext="{Binding MaterialsLogic}" ToolTip="Materials">
<Button Style="{StaticResource ToolButton}" Command="{Binding Add}" CommandParameter="{x:Static enums:MaterialType.Concrete}">

View File

@@ -8,7 +8,7 @@
xmlns:forces="clr-namespace:StructureHelper.Windows.Forces"
d:DataContext="{d:DesignInstance forces:ListOfFilesVM}"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
d:DesignHeight="250" d:DesignWidth="400">
<DockPanel>
<ToolBarTray DockPanel.Dock="Top">
<ToolBar>
@@ -23,6 +23,38 @@
<ContentControl ContentTemplate="{DynamicResource FileOpen}"/>
</Viewbox>
</Button>
<Button Style="{StaticResource ToolButton}" Command="{Binding Delete}">
<Button.ToolTip>
<uc:ButtonToolTipEh HeaderText="Delete reference to file"
IconContent="{StaticResource DeleteAnalysis }"
DescriptionText="Deletes selected reference to file"/>
</Button.ToolTip>
<Viewbox>
<ContentControl ContentTemplate="{DynamicResource DeleteAnalysis}"/>
</Viewbox>
</Button>
<Button Style="{StaticResource ToolButton}"
Command="{Binding ShowSettings}">
<Button.ToolTip>
<uc:ButtonToolTipEh HeaderText="Settings"
IconContent="{StaticResource Settings}"
DescriptionText="Shows settings of import of file"/>
</Button.ToolTip>
<Viewbox>
<ContentControl ContentTemplate="{DynamicResource Settings}"/>
</Viewbox>
</Button>
<Button Style="{StaticResource ToolButton}" Visibility="Hidden"
Command="{Binding ShowDocument}">
<Button.ToolTip>
<uc:ButtonToolTipEh HeaderText="View file"
IconContent="{StaticResource Report}"
DescriptionText="Shows file data if it is possible"/>
</Button.ToolTip>
<Viewbox>
<ContentControl ContentTemplate="{DynamicResource Report}"/>
</Viewbox>
</Button>
</ToolBar>
</ToolBarTray>
<Grid>

View File

@@ -1,13 +1,20 @@
using StructureHelper.Infrastructure.Enums;
using StructureHelper.Infrastructure;
using StructureHelper.Infrastructure.Enums;
using StructureHelper.Windows.Forces;
using StructureHelper.Windows.ViewModels.Errors;
using StructureHelperCommon.Infrastructures.Exceptions;
using StructureHelperCommon.Infrastructures.Interfaces;
using StructureHelperCommon.Models;
using StructureHelperCommon.Models.Calculators;
using StructureHelperCommon.Models.Forces;
using StructureHelperCommon.Models.Forces.Logics;
using StructureHelperLogics.Models.CrossSections;
using StructureHelperLogics.NdmCalculations.Analyses.ByForces;
using StructureHelperLogics.NdmCalculations.Cracking;
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Windows.Input;
namespace StructureHelper.Windows.ViewModels.Forces
{
@@ -15,6 +22,30 @@ namespace StructureHelper.Windows.ViewModels.Forces
{
readonly IUpdateStrategy<IAction> updateStrategy = new ActionUpdateStrategy();
ICrossSectionRepository repository;
private ICommand showCombinationsCommand;
public ICommand ShowCombinations => showCombinationsCommand ?? (
showCombinationsCommand = new RelayCommand(param =>
{
SafetyProcessor.RunSafeProcess(ShowDocumentMethod, "Error of opening of settings");
}, o => SelectedItem is not null
));
private void ShowDocumentMethod()
{
if (SelectedItem is null) { return; }
var checkLogic = new CheckForceActionsLogic()
{
Entity = new List<IForceAction>() { SelectedItem }
};
if (checkLogic.Check() == false)
{
SafetyProcessor.ShowMessage($"Action {SelectedItem.Name} returned wrong collection of combinations", checkLogic.CheckResult);
return;
}
var wnd = new ForceCombinationViewerView(SelectedItem);
wnd.ShowDialog();
}
public override void AddMethod(object parameter)
{

View File

@@ -1,4 +1,5 @@
using StructureHelper.Infrastructure;
using StructureHelperCommon.Infrastructures.Exceptions;
using System.Windows;
using System.Windows.Input;
@@ -11,12 +12,22 @@ namespace StructureHelper.Windows.ViewModels
public ICommand CancelCommand => new RelayCommand(o => CancelAction());
public virtual void CancelAction()
{
Check();
ParentWindow.DialogResult = false;
ParentWindow.Close();
}
private void Check()
{
if (ParentWindow is null)
{
throw new StructureHelperException(ErrorStrings.NullReference + ": Parent window");
}
}
public virtual void OkAction()
{
Check();
ParentWindow.DialogResult = true;
ParentWindow.Close();
}

View File

@@ -6,20 +6,34 @@ using System.Threading.Tasks;
namespace StructureHelperCommon.Models.Forces
{
/// <inheritdoc/>
public class ColumnProperty : IColumnProperty
{
/// <inheritdoc/>
public Guid Id { get; private set; }
public string ColumnName { get; set; } = string.Empty;
public int ColumnIndex { get; set; } = 0;
public double ColumnFactor { get; set; } = 1d;
/// <inheritdoc/>
public string Name { get; set; }
/// <inheritdoc/>
public string SearchingName { get; set; } = string.Empty;
/// <inheritdoc/>
public int Index { get; set; } = 0;
/// <inheritdoc/>
public double Factor { get; set; } = 1d;
public ColumnProperty(Guid id, string columnName)
{
Id = id;
ColumnName = columnName;
Name = columnName;
}
public ColumnProperty(string columnName) : this(Guid.NewGuid(), columnName)
{
}
public object Clone()
{
var cloneLogic = new ColumnPropertyCloningStrategy();
return cloneLogic.GetClone(this);
}
}
}

View File

@@ -0,0 +1,45 @@
using StructureHelperCommon.Infrastructures.Enums;
using StructureHelperCommon.Infrastructures.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StructureHelperCommon.Models.Forces
{
/// <inheritdoc/>
public class ColumnedFileProperty : IColumnedFileProperty
{
private IUpdateStrategy<IColumnedFileProperty> updateStrategy;
/// <inheritdoc/>
public Guid Id { get; private set; }
/// <inheritdoc/>
public string FilePath { get; set; } = string.Empty;
/// <inheritdoc/>
public int SkipRowBeforeHeaderCount { get; set; } = 2;
/// <inheritdoc/>
public int SkipRowHeaderCount { get; set; } = 1;
/// <inheritdoc/>
public double GlobalFactor { get; set; } = 1d;
/// <inheritdoc/>
public List<IColumnProperty> ColumnProperties { get; } = new();
public ColumnedFileProperty(Guid id)
{
Id = id;
}
public ColumnedFileProperty() : this (Guid.NewGuid())
{
}
public object Clone()
{
updateStrategy ??= new ColumnedFilePropertyUpdateStrategy();
ColumnedFileProperty newItem = new();
updateStrategy.Update(newItem, this);
return newItem;
}
}
}

View File

@@ -0,0 +1,40 @@
using StructureHelperCommon.Infrastructures.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StructureHelperCommon.Models.Forces
{
public enum FilePropertyType
{
Forces
}
public static class FilePropertyFactory
{
public static IColumnedFileProperty GetForceFileProperty(FilePropertyType propertyType)
{
if (propertyType == FilePropertyType.Forces)
{
ColumnedFileProperty fileProperty = new();
List<IColumnProperty> columnProperties = GetForceColumns();
fileProperty.ColumnProperties.AddRange(columnProperties);
return fileProperty;
}
else
{
throw new StructureHelperException(ErrorStrings.ObjectTypeIsUnknownObj(propertyType));
}
}
private static List<IColumnProperty> GetForceColumns()
{
List<IColumnProperty> columnProperties = new();
columnProperties.Add(new ColumnProperty("Nz") { SearchingName = "N", Index = 6 });
columnProperties.Add(new ColumnProperty("Mx") { SearchingName = "My", Index = 8 });
columnProperties.Add(new ColumnProperty("My") { SearchingName = "Mz", Index = 10 });
return columnProperties;
}
}
}

View File

@@ -14,12 +14,12 @@ namespace StructureHelperCommon.Models.Forces
{
IUpdateStrategy<IForceCombinationFromFile> updateStrategy;
IUpdateStrategy<IFactoredCombinationProperty> propertyUpdateStrategy;
IGetTupleFromFileLogic getTupleFromFileLogic;
IGetTuplesFromFileLogic getTupleFromFileLogic;
private IForceFactoredList factoredCombination;
public Guid Id { get; set; }
public string Name { get; set; } = string.Empty;
public List<IForceFileProperty> ForceFiles { get; set; } = new();
public List<IColumnedFileProperty> ForceFiles { get; set; } = new();
public bool SetInGravityCenter { get; set; } = true;
public IPoint2D ForcePoint { get; set; } = new Point2D();
@@ -35,7 +35,7 @@ namespace StructureHelperCommon.Models.Forces
public List<IForceCombinationList> GetCombinations()
{
getTupleFromFileLogic ??= new GetTupleFromFileLogic() { TraceLogger = new ShiftTraceLogger()};
getTupleFromFileLogic ??= new GetTuplesFromFileLogic() { TraceLogger = new ShiftTraceLogger()};
factoredCombination = new ForceFactoredList();
factoredCombination.ForceTuples.Clear();
propertyUpdateStrategy ??= new FactoredCombinationPropertyUpdateStrategy();

View File

@@ -1,30 +0,0 @@
using StructureHelperCommon.Infrastructures.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StructureHelperCommon.Models.Forces
{
public class ForceFileProperty : IForceFileProperty
{
public Guid Id { get; private set; }
public string FilePath { get; set; } = string.Empty;
public int SkipRowBeforeHeaderCount { get; set; } = 2;
public int SkipRowHeaderCount { get; set; } = 1;
public double GlobalFactor { get; set; } = 1d;
public IColumnProperty Nz { get; set; } = new ColumnProperty("N") { ColumnIndex = 6};
public IColumnProperty Mx { get; set; } = new ColumnProperty("My") { ColumnIndex = 8};
public IColumnProperty My { get; set; } = new ColumnProperty("Mz") { ColumnIndex = 10};
public ForceFileProperty(Guid id)
{
Id = id;
}
public ForceFileProperty() : this (Guid.NewGuid())
{
}
}
}

View File

@@ -10,19 +10,23 @@ namespace StructureHelperCommon.Models.Forces
/// <summary>
/// Settingth for column reading from MSExcel file
/// </summary>
public interface IColumnProperty : ISaveable
public interface IColumnProperty : ISaveable, ICloneable
{
/// <summary>
/// Name of column
/// </summary>
string Name { get; set; }
/// <summary>
/// Name of column for searching
/// </summary>
string ColumnName { get; set; }
string SearchingName { get; set; }
/// <summary>
/// Column index
/// </summary>
int ColumnIndex { get; set; }
int Index { get; set; }
/// <summary>
/// Factor for obtaining value from column
/// </summary>
double ColumnFactor { get; set; }
double Factor { get; set; }
}
}

View File

@@ -11,14 +11,23 @@ namespace StructureHelperCommon.Models.Forces
/// <summary>
/// Settings for extracting force combination from MSExcel file
/// </summary>
public interface IForceFileProperty : IFileProperty
public interface IColumnedFileProperty : IFileProperty
{
/// <summary>
/// Count of rows before header
/// </summary>
int SkipRowBeforeHeaderCount { get; set; }
/// <summary>
/// Count of rows of header
/// </summary>
int SkipRowHeaderCount { get; set; }
/// <summary>
/// Factor which imported value multyply to
/// </summary>
double GlobalFactor { get; set; }
IColumnProperty Mx { get; set; }
IColumnProperty My { get; set; }
IColumnProperty Nz { get; set; }
/// <summary>
/// Collection of column's properties which will be imported
/// </summary>
List<IColumnProperty> ColumnProperties { get; }
}
}

View File

@@ -1,8 +1,9 @@
using StructureHelperCommon.Infrastructures.Interfaces;
using System;
namespace StructureHelperCommon.Models.Forces
{
public interface IFileProperty : ISaveable
public interface IFileProperty : ISaveable, ICloneable
{
string FilePath { get; set; }
}

View File

@@ -14,6 +14,6 @@ namespace StructureHelperCommon.Models.Forces
/// <summary>
/// List of file properties for import combination
/// </summary>
List<IForceFileProperty> ForceFiles { get; set; }
List<IColumnedFileProperty> ForceFiles { get; set; }
}
}

View File

@@ -0,0 +1,48 @@
using StructureHelperCommon.Infrastructures.Exceptions;
using StructureHelperCommon.Infrastructures.Interfaces;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StructureHelperCommon.Models.Forces
{
public class CheckColumnedFilePropertyLogic : ICheckEntityLogic<IColumnedFileProperty>
{
private string checkResult;
private bool result;
public IColumnedFileProperty Entity { get; set; }
public string CheckResult => checkResult;
public IShiftTraceLogger? TraceLogger { get; set; }
public bool Check()
{
result = true;
int skipRows = Entity.SkipRowBeforeHeaderCount + Entity.SkipRowHeaderCount;
if (skipRows < 0)
{
string errorString = ErrorStrings.DataIsInCorrect + $": skip row count must be greater or equal to 0, bu was {skipRows}";
TraceMessage(errorString);
return false;
}
if (File.Exists(Entity.FilePath) == false)
{
string errorString = ErrorStrings.DataIsInCorrect + $": File {Entity.FilePath} does not exist";
TraceMessage(errorString);
return false;
}
return result;
}
private void TraceMessage(string errorString)
{
checkResult += errorString;
TraceLogger?.AddMessage(errorString, TraceLogStatuses.Error);
}
}
}

View File

@@ -0,0 +1,37 @@
using StructureHelperCommon.Infrastructures.Interfaces;
using StructureHelperCommon.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StructureHelperCommon.Models.Forces
{
public class ColumnPropertyCloningStrategy : ICloneStrategy<IColumnProperty>
{
private IUpdateStrategy<IColumnProperty> updateStrategy;
public ColumnPropertyCloningStrategy(IUpdateStrategy<IColumnProperty> updateStrategy)
{
this.updateStrategy = updateStrategy;
}
public ColumnPropertyCloningStrategy()
{
}
public IColumnProperty GetClone(IColumnProperty sourceObject)
{
CheckObject.IsNull(sourceObject);
if (updateStrategy is null)
{
updateStrategy = new ColumnPropertyUpdateStrategy();
}
ColumnProperty newItem = new(sourceObject.Name);
updateStrategy.Update(newItem, sourceObject);
return newItem;
}
}
}

View File

@@ -8,16 +8,17 @@ using System.Threading.Tasks;
namespace StructureHelperCommon.Models.Forces
{
public class ForceColumnPropertyUpdateStrategy : IUpdateStrategy<IColumnProperty>
public class ColumnPropertyUpdateStrategy : IUpdateStrategy<IColumnProperty>
{
public void Update(IColumnProperty targetObject, IColumnProperty sourceObject)
{
CheckObject.IsNull(targetObject);
CheckObject.IsNull(sourceObject);
if (ReferenceEquals(targetObject, sourceObject)) { return; }
targetObject.ColumnName = sourceObject.ColumnName;
targetObject.ColumnIndex = sourceObject.ColumnIndex;
targetObject.ColumnFactor = sourceObject.ColumnFactor;
targetObject.Name = sourceObject.Name;
targetObject.SearchingName = sourceObject.SearchingName;
targetObject.Index = sourceObject.Index;
targetObject.Factor = sourceObject.Factor;
}
}
}

View File

@@ -0,0 +1,39 @@
using StructureHelperCommon.Infrastructures.Interfaces;
using StructureHelperCommon.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StructureHelperCommon.Models.Forces
{
/// <inheritdoc/>
public class ColumnedFilePropertyUpdateStrategy : IUpdateStrategy<IColumnedFileProperty>
{
/// <inheritdoc/>
public void Update(IColumnedFileProperty targetObject, IColumnedFileProperty sourceObject)
{
CheckObject.IsNull(targetObject);
CheckObject.IsNull(sourceObject);
if (ReferenceEquals(targetObject, sourceObject)) { return; }
UpdateObjects(targetObject, sourceObject);
}
private static void UpdateObjects(IColumnedFileProperty targetObject, IColumnedFileProperty sourceObject)
{
targetObject.FilePath = sourceObject.FilePath;
targetObject.GlobalFactor = sourceObject.GlobalFactor;
targetObject.SkipRowBeforeHeaderCount = sourceObject.SkipRowBeforeHeaderCount;
targetObject.SkipRowHeaderCount = sourceObject.SkipRowHeaderCount;
CheckObject.IsNull(targetObject.ColumnProperties);
CheckObject.IsNull(sourceObject.ColumnProperties);
targetObject.ColumnProperties.Clear();
foreach (var item in sourceObject.ColumnProperties)
{
IColumnProperty clone = (IColumnProperty)item.Clone();
targetObject.ColumnProperties.Add(clone);
}
}
}
}

View File

@@ -0,0 +1,36 @@
using StructureHelperCommon.Infrastructures.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StructureHelperCommon.Models.Forces
{
public class FillTupleArrayByColumnNameLogic : IFillTupleArrayByColumnNameLogic
{
public IShiftTraceLogger? TraceLogger { get; set; }
public void ProceeForceTupleArray(double[] nDouble, double doubleValue, string columnName, string filePath)
{
if (columnName == "Nz")
{
nDouble[0] = doubleValue;
}
else if (columnName == "Mx")
{
nDouble[1] = doubleValue;
}
else if (columnName == "My")
{
nDouble[2] = doubleValue;
}
else
{
string errorString = ErrorStrings.DataIsInCorrect + $": column {columnName} in file {filePath}, ";
TraceLogger?.AddMessage(errorString, TraceLogStatuses.Error);
throw new StructureHelperException(errorString);
}
}
}
}

View File

@@ -1,4 +1,5 @@
using StructureHelperCommon.Infrastructures.Interfaces;
using StructureHelperCommon.Models.Forces.Logics;
using StructureHelperCommon.Services;
using System;
using System.Collections.Generic;
@@ -11,31 +12,37 @@ namespace StructureHelperCommon.Models.Forces
public class ForceCombinationFromFileUpdateStrategy : IUpdateStrategy<IForceCombinationFromFile>
{
private IUpdateStrategy<IForceAction> baseUpdateStrategy;
private IUpdateStrategy<IForceFileProperty> fileUpdateStrategy;
private IUpdateStrategy<IColumnedFileProperty> filePropertyUpdateStrategy;
private IUpdateStrategy<IFactoredCombinationProperty> combinationPropertyUpdateStrategy;
public ForceCombinationFromFileUpdateStrategy(IUpdateStrategy<IForceAction> baseUpdateStrategy,
IUpdateStrategy<IForceFileProperty> fileUpdateStrategy)
IUpdateStrategy<IColumnedFileProperty> filePropertyUpdateStrategy,
IUpdateStrategy<IFactoredCombinationProperty> combinationPropertyUpdateStrategy)
{
this.baseUpdateStrategy = baseUpdateStrategy;
this.fileUpdateStrategy = fileUpdateStrategy;
this.filePropertyUpdateStrategy = filePropertyUpdateStrategy;
this.combinationPropertyUpdateStrategy = combinationPropertyUpdateStrategy;
}
public ForceCombinationFromFileUpdateStrategy()
{
}
void IUpdateStrategy<IForceCombinationFromFile>.Update(IForceCombinationFromFile targetObject, IForceCombinationFromFile sourceObject)
public void Update(IForceCombinationFromFile targetObject, IForceCombinationFromFile sourceObject)
{
CheckObject.IsNull(targetObject);
CheckObject.IsNull(sourceObject);
if (ReferenceEquals(targetObject, sourceObject)) { return; }
InitializeLogics();
baseUpdateStrategy.Update(targetObject, sourceObject);
CheckObject.IsNull(targetObject.CombinationProperty, "Target object combination property");
CheckObject.IsNull(sourceObject.CombinationProperty, "Source object combination property");
combinationPropertyUpdateStrategy.Update(targetObject.CombinationProperty, sourceObject.CombinationProperty);
targetObject.ForceFiles.Clear();
foreach (var file in sourceObject.ForceFiles)
{
ForceFileProperty newProperty = new();
fileUpdateStrategy.Update(newProperty, file);
ColumnedFileProperty newProperty = new();
filePropertyUpdateStrategy.Update(newProperty, file);
targetObject.ForceFiles.Add(newProperty);
}
}
@@ -43,7 +50,8 @@ namespace StructureHelperCommon.Models.Forces
private void InitializeLogics()
{
baseUpdateStrategy ??= new ForceActionBaseUpdateStrategy();
fileUpdateStrategy ??= new ForceFilePropertyUpdateStrategy();
filePropertyUpdateStrategy ??= new ColumnedFilePropertyUpdateStrategy();
combinationPropertyUpdateStrategy ??= new FactoredCombinationPropertyUpdateStrategy();
}
}
}

View File

@@ -1,39 +0,0 @@
using StructureHelperCommon.Infrastructures.Interfaces;
using StructureHelperCommon.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StructureHelperCommon.Models.Forces
{
public class ForceFilePropertyUpdateStrategy : IUpdateStrategy<IForceFileProperty>
{
private IUpdateStrategy<IColumnProperty> columnUpdateStrategy;
public ForceFilePropertyUpdateStrategy(IUpdateStrategy<IColumnProperty> columnUpdateStrategy)
{
this.columnUpdateStrategy = columnUpdateStrategy;
}
public ForceFilePropertyUpdateStrategy() : this (new ForceColumnPropertyUpdateStrategy())
{
}
public void Update(IForceFileProperty targetObject, IForceFileProperty sourceObject)
{
CheckObject.IsNull(targetObject);
CheckObject.IsNull(sourceObject);
if (ReferenceEquals(targetObject, sourceObject)) { return; }
targetObject.FilePath = sourceObject.FilePath;
targetObject.GlobalFactor = sourceObject.GlobalFactor;
targetObject.SkipRowBeforeHeaderCount = sourceObject.SkipRowBeforeHeaderCount;
targetObject.SkipRowHeaderCount = sourceObject.SkipRowHeaderCount;
columnUpdateStrategy.Update(targetObject.Mx, sourceObject.Mx);
columnUpdateStrategy.Update(targetObject.My, sourceObject.My);
columnUpdateStrategy.Update(targetObject.Nz, sourceObject.Nz);
}
}
}

View File

@@ -0,0 +1,52 @@
using ExcelDataReader;
using StructureHelperCommon.Infrastructures.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StructureHelperCommon.Models.Forces
{
public class GetTupleByExcelReaderLogic : IGetTupleByExcelReaderLogic
{
IFillTupleArrayByColumnNameLogic fillArrayLogic;
public GetTupleByExcelReaderLogic(IFillTupleArrayByColumnNameLogic fillArrayLogic)
{
this.fillArrayLogic = fillArrayLogic;
}
public GetTupleByExcelReaderLogic()
{
}
public IShiftTraceLogger? TraceLogger { get; set; }
public IColumnedFileProperty ForceFileProperty { get; set; }
public IForceTuple GetForceTuple(IExcelDataReader? reader)
{
// Ensure ExcelDataReader's encoding provider is registered
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
double[] nDouble = new double[3];
foreach (var item in ForceFileProperty.ColumnProperties)
{
if (reader is null)
{
throw new StructureHelperException(ErrorStrings.NullReference + $": reader value for column {item.Name} in file {ForceFileProperty.FilePath}");
}
var readerValue = reader.GetValue(item.Index);
var strValue = readerValue.ToString();
double factor = ForceFileProperty.GlobalFactor * item.Factor * 1000d;
var doubleValue = Convert.ToDouble(strValue) * factor;
fillArrayLogic ??= new FillTupleArrayByColumnNameLogic() { TraceLogger = TraceLogger };
fillArrayLogic.ProceeForceTupleArray(nDouble, doubleValue, item.Name, ForceFileProperty.FilePath);
}
TraceLogger?.AddMessage($"String values: Nz = {nDouble[0]}, Mx = {nDouble[1]}, My = {nDouble[2]} were gained", TraceLogStatuses.Debug);
ForceTuple newTuple = new() { Nz = nDouble[0], Mx = nDouble[1], My = nDouble[2] };
return newTuple;
}
}
}

View File

@@ -1,79 +0,0 @@
using ExcelDataReader;
using StructureHelperCommon.Infrastructures.Exceptions;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StructureHelperCommon.Models.Forces.Logics
{
public class GetTupleFromFileLogic : IGetTupleFromFileLogic
{
public IForceFileProperty ForceFileProperty { get; set; }
public IShiftTraceLogger? TraceLogger { get; set; }
public List<IForceTuple> GetTuples()
{
// Ensure ExcelDataReader's encoding provider is registered
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
var result = ReadDataFromFile();
return result;
}
private List<IForceTuple> ReadDataFromFile()
{
List<IForceTuple> result = new();
// Open the Excel file stream
using (var stream = File.Open(ForceFileProperty.FilePath, FileMode.Open, FileAccess.Read))
{
// Create an Excel reader
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
// Skip the first two header rows if necessary (adjust based on structure)
int skipRows = ForceFileProperty.SkipRowBeforeHeaderCount + ForceFileProperty.SkipRowHeaderCount;
for (int i = 0; i < skipRows; i++)
{
reader.Read(); // Skip row
}
// Loop through the rows
while (reader.Read())
{
var nValue = reader.GetValue(ForceFileProperty.Nz.ColumnIndex)?.ToString();
var mxValue = reader.GetValue(ForceFileProperty.Mx.ColumnIndex)?.ToString();
var myValue = reader.GetValue(ForceFileProperty.My.ColumnIndex)?.ToString();
TraceLogger?.AddMessage($"Values: Nz = {nValue}(N), Mx = {mxValue}(N*m), My = {myValue}(N*m) were gained", TraceLogStatuses.Debug);
if (nValue is not null && mxValue is not null && myValue is not null)
{
ForceTuple newTuple = GetForceTuple(nValue, mxValue, myValue);
result.Add(newTuple);
}
}
}
}
return result;
}
private ForceTuple GetForceTuple(string? nValue, string? mxValue, string? myValue)
{
try
{
double nDouble = Convert.ToDouble(nValue);
double mxDouble = Convert.ToDouble(mxValue);
double myDouble = Convert.ToDouble(myValue);
TraceLogger?.AddMessage($"Values: Nz = {nDouble}(N), Mx = {mxDouble}(N*m), My = {myDouble}(N*m) were converted successfully", TraceLogStatuses.Debug);
ForceTuple newTuple = new() { Nz = nDouble, Mx = mxDouble, My = myDouble };
return newTuple;
}
catch (Exception ex)
{
string errorString = ErrorStrings.DataIsInCorrect + $": incorrect data in file {ForceFileProperty.FilePath}, " + ex.Message;
TraceLogger?.AddMessage(errorString, TraceLogStatuses.Error);
throw new StructureHelperException(errorString);
}
}
}
}

View File

@@ -0,0 +1,105 @@
using ExcelDataReader;
using StructureHelperCommon.Infrastructures.Exceptions;
using StructureHelperCommon.Infrastructures.Interfaces;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
//Copyright (c) 2025 Redikultsev Evgeny, Ekaterinburg, Russia
//All rights reserved.
namespace StructureHelperCommon.Models.Forces
{
public class GetTuplesFromFileLogic : IGetTuplesFromFileLogic
{
private IGetTupleByExcelReaderLogic excelReaderLogic;
private ICheckEntityLogic<IColumnedFileProperty> checkEntityLogic;
public GetTuplesFromFileLogic(IGetTupleByExcelReaderLogic excelReaderLogic,
ICheckEntityLogic<IColumnedFileProperty> checkEntityLogic)
{
this.excelReaderLogic = excelReaderLogic;
this.checkEntityLogic = checkEntityLogic;
}
public GetTuplesFromFileLogic()
{
}
private List<IForceTuple> result;
private int skipRows;
public IColumnedFileProperty ForceFileProperty { get; set; }
public IShiftTraceLogger? TraceLogger { get; set; }
public List<IForceTuple> GetTuples()
{
Check();
// Ensure ExcelDataReader's encoding provider is registered
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
result = ReadDataFromFile();
return result;
}
private List<IForceTuple> ReadDataFromFile()
{
result = new();
skipRows = ForceFileProperty.SkipRowBeforeHeaderCount + ForceFileProperty.SkipRowHeaderCount;
// Open the Excel file stream
using (var stream = File.Open(ForceFileProperty.FilePath, FileMode.Open, FileAccess.Read))
{
// Create an Excel reader
using (var reader = ExcelReaderFactory.CreateReader(stream))
{
// Skip the first two header rows if necessary (adjust based on structure)
for (int i = 0; i < skipRows; i++)
{
reader.Read(); // Skip row
}
excelReaderLogic ??= new GetTupleByExcelReaderLogic()
{
ForceFileProperty = ForceFileProperty,
TraceLogger = TraceLogger
};
// Loop through the rows
while (reader.Read())
{
try
{
IForceTuple newTuple = excelReaderLogic.GetForceTuple(reader);
result.Add(newTuple);
}
catch (Exception ex)
{
string errorString = ErrorStrings.DataIsInCorrect + $": incorrect data in file {ForceFileProperty.FilePath}, " + ex.Message;
TraceLogger?.AddMessage(errorString, TraceLogStatuses.Error);
throw new StructureHelperException(errorString);
}
}
}
}
return result;
}
private void Check()
{
checkEntityLogic ??= new CheckColumnedFilePropertyLogic()
{
Entity = ForceFileProperty,
TraceLogger = TraceLogger
};
if (checkEntityLogic.Check() == false)
{
throw new StructureHelperException(checkEntityLogic.CheckResult);
}
}
}
}

View File

@@ -0,0 +1,9 @@
using StructureHelperCommon.Infrastructures.Interfaces;
namespace StructureHelperCommon.Models.Forces
{
public interface IFillTupleArrayByColumnNameLogic : ILogic
{
void ProceeForceTupleArray(double[] nDouble, double doubleValue, string columnName, string filePath);
}
}

View File

@@ -0,0 +1,16 @@
using ExcelDataReader;
using StructureHelperCommon.Infrastructures.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StructureHelperCommon.Models.Forces
{
public interface IGetTupleByExcelReaderLogic : ILogic
{
IColumnedFileProperty ForceFileProperty { get; set;}
IForceTuple GetForceTuple(IExcelDataReader? reader);
}
}

View File

@@ -1,12 +0,0 @@
using StructureHelperCommon.Infrastructures.Interfaces;
using System.Collections.Generic;
namespace StructureHelperCommon.Models.Forces.Logics
{
public interface IGetTupleFromFileLogic : ILogic
{
IForceFileProperty ForceFileProperty { get; set; }
List<IForceTuple> GetTuples();
}
}

View File

@@ -0,0 +1,12 @@
using StructureHelperCommon.Infrastructures.Interfaces;
using System.Collections.Generic;
namespace StructureHelperCommon.Models.Forces
{
public interface IGetTuplesFromFileLogic : ILogic
{
IColumnedFileProperty ForceFileProperty { get; set; }
List<IForceTuple> GetTuples();
}
}

View File

@@ -38,6 +38,12 @@ namespace StructureHelperCommon.Services
IsNull(sourceObject, $"{senderName} source object");
}
/// <summary>
/// Checks if object is null, if it is null throws new exception
/// </summary>
/// <param name="item">Checked object</param>
/// <param name="message">Message while error occur</param>
/// <exception cref="StructureHelperException"></exception>
public static void IsNull(object item, string message = "")
{
if (item is null)

View File

@@ -0,0 +1,84 @@
using NUnit.Framework;
using Moq;
using System.IO;
using StructureHelperCommon.Models.Forces;
using StructureHelperCommon.Models;
namespace StructureHelperTests.UnitTests.ForcesTests
{
[TestFixture]
public class CheckColumnedFilePropertyLogicTests
{
private Mock<IShiftTraceLogger> _mockTraceLogger;
private Mock<IColumnedFileProperty> _mockFileProperty;
private CheckColumnedFilePropertyLogic _logic;
[SetUp]
public void SetUp()
{
_mockTraceLogger = new Mock<IShiftTraceLogger>();
_mockFileProperty = new Mock<IColumnedFileProperty>();
_logic = new CheckColumnedFilePropertyLogic
{
TraceLogger = _mockTraceLogger.Object,
Entity = _mockFileProperty.Object
};
}
[Test]
public void Check_ShouldReturnTrue_WhenFileExistsAndSkipRowsAreValid()
{
// Arrange
_mockFileProperty.Setup(x => x.SkipRowBeforeHeaderCount).Returns(1);
_mockFileProperty.Setup(x => x.SkipRowHeaderCount).Returns(1);
_mockFileProperty.Setup(x => x.FilePath).Returns("tmp_valid_file.xlsx");
File.Create("tmp_valid_file.xlsx").Dispose(); // Create a temporary file
// Act
var result = _logic.Check();
// Assert
Assert.That(result, Is.True);
// Cleanup
File.Delete("tmp_valid_file.xlsx");
}
[Test]
public void Check_ShouldReturnFalse_WhenSkipRowsAreNegative()
{
// Arrange
_mockFileProperty.Setup(x => x.SkipRowBeforeHeaderCount).Returns(-1);
_mockFileProperty.Setup(x => x.SkipRowHeaderCount).Returns(-1);
// Act
var result = _logic.Check();
// Assert
Assert.That(result, Is.False);
Assert.That(_logic.CheckResult, Does.Contain("skip row count must be greater or equal to 0"));
_mockTraceLogger.Verify(x => x.AddMessage(It.IsAny<string>(), TraceLogStatuses.Error), Times.Once);
}
[Test]
public void Check_ShouldReturnFalse_WhenFileDoesNotExist()
{
// Arrange
_mockFileProperty.Setup(x => x.SkipRowBeforeHeaderCount).Returns(1);
_mockFileProperty.Setup(x => x.SkipRowHeaderCount).Returns(1);
_mockFileProperty.Setup(x => x.FilePath).Returns("non_existent_file.xlsx");
// Act
var result = _logic.Check();
// Assert
Assert.That(result, Is.False);
Assert.That(_logic.CheckResult, Does.Contain("File non_existent_file.xlsx does not exist"));
_mockTraceLogger.Verify(x => x.AddMessage(It.IsAny<string>(), TraceLogStatuses.Error), Times.Once);
}
}
}

View File

@@ -0,0 +1,59 @@
using NUnit.Framework;
using Moq;
using System.Text;
using ExcelDataReader;
using StructureHelperCommon.Models.Forces;
using StructureHelperCommon.Models;
namespace StructureHelperTests.UnitTests.ForcesTests
{
[TestFixture]
public class GetTupleByExcelReaderLogicTests
{
private Mock<IShiftTraceLogger> _mockTraceLogger;
private Mock<IColumnedFileProperty> _mockFileProperty;
private Mock<IExcelDataReader> _mockReader;
private Mock<IFillTupleArrayByColumnNameLogic> _mockFillArray;
private GetTupleByExcelReaderLogic _logic;
[SetUp]
public void SetUp()
{
_mockTraceLogger = new Mock<IShiftTraceLogger>();
_mockFileProperty = new Mock<IColumnedFileProperty>();
_mockReader = new Mock<IExcelDataReader>();
_mockFillArray = new Mock<IFillTupleArrayByColumnNameLogic>();
_logic = new GetTupleByExcelReaderLogic(_mockFillArray.Object)
{
TraceLogger = _mockTraceLogger.Object,
ForceFileProperty = _mockFileProperty.Object
};
}
[Test]
public void GetForceTuple_ShouldReturnForceTuple_WhenDataIsValid()
{
// Arrange
var columnProperties = new List<IColumnProperty>
{
new Mock<IColumnProperty>().SetupAllProperties().Object
};
_mockFileProperty.Setup(x => x.ColumnProperties).Returns(columnProperties);
_mockFileProperty.Setup(x => x.GlobalFactor).Returns(1.0);
_mockFillArray.Setup(x => x.ProceeForceTupleArray(It.IsAny<double[]>(), It.IsAny<double>(), It.IsAny<string>(),It.IsAny<string>()));
_mockReader.Setup(x => x.GetValue(It.IsAny<int>())).Returns("1");
// Act
var result = _logic.GetForceTuple(_mockReader.Object);
// Assert
Assert.That(result, Is.InstanceOf<IForceTuple>());
}
}
}

View File

@@ -0,0 +1,119 @@
using NUnit.Framework;
using Moq;
using System.Collections.Generic;
using System.Text;
using System.IO;
using StructureHelperCommon.Models.Forces;
using StructureHelperCommon.Models;
using StructureHelperCommon.Infrastructures.Interfaces;
using StructureHelperCommon.Infrastructures.Exceptions;
namespace StructureHelperTests.UnitTests.ForcesTests
{
[TestFixture]
public class GetTuplesFromFileLogicTests
{
private Mock<IGetTupleByExcelReaderLogic> _mockExcelReaderLogic;
private Mock<ICheckEntityLogic<IColumnedFileProperty>> _mockCheckEntityLogic;
private Mock<IShiftTraceLogger> _mockTraceLogger;
private GetTuplesFromFileLogic _logic;
[SetUp]
public void SetUp()
{
_mockExcelReaderLogic = new Mock<IGetTupleByExcelReaderLogic>();
_mockCheckEntityLogic = new Mock<ICheckEntityLogic<IColumnedFileProperty>>();
_mockTraceLogger = new Mock<IShiftTraceLogger>();
_logic = new GetTuplesFromFileLogic(
_mockExcelReaderLogic.Object,
_mockCheckEntityLogic.Object
)
{
TraceLogger = _mockTraceLogger.Object
};
}
[Test]
public void GetTuples_ShouldReturnListOfForceTuples_WhenDataIsValid()
{
// Arrange
var mockFileProperty = new Mock<IColumnedFileProperty>();
mockFileProperty.Setup(x => x.FilePath).Returns("valid_file.xlsx");
mockFileProperty.Setup(x => x.SkipRowBeforeHeaderCount).Returns(2);
mockFileProperty.Setup(x => x.SkipRowHeaderCount).Returns(1);
_logic.ForceFileProperty = mockFileProperty.Object;
var mockForceTuple = new Mock<IForceTuple>();
var forceTuples = new List<IForceTuple> { mockForceTuple.Object };
_mockCheckEntityLogic.Setup(x => x.Check()).Returns(true);
_mockExcelReaderLogic.Setup(x => x.GetForceTuple(It.IsAny<ExcelDataReader.IExcelDataReader>())).Returns(mockForceTuple.Object);
// Mock file reading and ExcelReader behavior
var fileStream = new MemoryStream(Encoding.UTF8.GetBytes("mock data"));
FileStream mockStream = MockFileHelper.CreateMockFileStream(fileStream);
// Act
var result = _logic.GetTuples();
// Assert
Assert.That(result, Is.Not.Null);
Assert.That(result.Count, Is.EqualTo(forceTuples.Count));
_mockCheckEntityLogic.Verify(x => x.Check(), Times.Once);
_mockExcelReaderLogic.Verify(x => x.GetForceTuple(It.IsAny<ExcelDataReader.IExcelDataReader>()), Times.AtLeastOnce);
}
[Test]
public void GetTuples_ShouldThrowException_WhenCheckFails()
{
// Arrange
_mockCheckEntityLogic.Setup(x => x.Check()).Returns(false);
_mockCheckEntityLogic.Setup(x => x.CheckResult).Returns("Invalid file property");
// Act & Assert
var ex = Assert.Throws<StructureHelperException>(() => _logic.GetTuples());
Assert.That(ex.Message, Is.EqualTo("Invalid file property"));
}
[Test]
public void GetTuples_ShouldLogErrorAndThrowException_WhenExceptionOccursInDataProcessing()
{
// Arrange
var mockFileProperty = new Mock<IColumnedFileProperty>();
mockFileProperty.Setup(x => x.FilePath).Returns("valid_file.xlsx");
mockFileProperty.Setup(x => x.SkipRowBeforeHeaderCount).Returns(1);
mockFileProperty.Setup(x => x.SkipRowHeaderCount).Returns(1);
_logic.ForceFileProperty = mockFileProperty.Object;
_mockCheckEntityLogic.Setup(x => x.Check()).Returns(true);
_mockExcelReaderLogic.Setup(x => x.GetForceTuple(It.IsAny<ExcelDataReader.IExcelDataReader>()))
.Throws(new StructureHelperException("Mock exception"));
// Act & Assert
var ex = Assert.Throws<StructureHelperException>(() => _logic.GetTuples());
Assert.That(ex.Message, Does.Contain("Mock exception"));
_mockTraceLogger.Verify(x => x.AddMessage(It.IsAny<string>(), TraceLogStatuses.Error), Times.AtLeastOnce);
}
public static class MockFileHelper
{
public static FileStream CreateMockFileStream(Stream inputStream)
{
var tempFilePath = Path.GetTempFileName();
using (var fileStream = File.Create(tempFilePath))
{
inputStream.CopyTo(fileStream);
}
return new FileStream(tempFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 4096, FileOptions.DeleteOnClose);
}
}
}
}