diff options
| author | Victoria Plitt <Victoria.Plitt@twine-s.com> | 2022-10-03 17:34:03 +0300 |
|---|---|---|
| committer | Victoria Plitt <Victoria.Plitt@twine-s.com> | 2022-10-03 17:34:03 +0300 |
| commit | fa8ac9f8559a1e6e56b1bd9247da9828b8fedbb1 (patch) | |
| tree | c2d263e5b4744abdf54bbddcf8e2c58c81320635 /Software/Visual_Studio/Utilities | |
| parent | 6d54b8da0fefd5dbb2f40f3ccc268497dd0bbe09 (diff) | |
| download | Tango-fa8ac9f8559a1e6e56b1bd9247da9828b8fedbb1.tar.gz Tango-fa8ac9f8559a1e6e56b1bd9247da9828b8fedbb1.zip | |
Saving Flow Test Results automatically In Excel File - first version
Related Work Items: #7268
Diffstat (limited to 'Software/Visual_Studio/Utilities')
12 files changed, 404 insertions, 25 deletions
diff --git a/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/Analysis/AnalysisService.cs b/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/Analysis/AnalysisService.cs index 0dbf9a83e..a27307af6 100644 --- a/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/Analysis/AnalysisService.cs +++ b/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/Analysis/AnalysisService.cs @@ -9,6 +9,7 @@ using Tango.DispenserAnalyzer.UI.Models; using System.Windows.Controls; using System.Windows.Media; using System.IO; +using System.Text.RegularExpressions; namespace Tango.DispenserAnalyzer.UI.Analysis { @@ -35,6 +36,39 @@ namespace Tango.DispenserAnalyzer.UI.Analysis return analyzerType.GetCustomAttribute<AnalyzerAttribute>().Name; } + public static string GetDispenserNumber(String fileName) + { + string filename = Path.GetFileNameWithoutExtension(fileName); + return GetUntilOrEmpty(filename," "); + } + + public static string GetUntilOrEmpty( string text, string stopAt = "-") + { + if (!String.IsNullOrWhiteSpace(text)) + { + int charLocation = text.IndexOf(stopAt, StringComparison.Ordinal); + + if (charLocation > 0) + { + return text.Substring(0, charLocation); + } + } + + return String.Empty; + } + + public static string GetDateTimeString(string text) + { + Regex regex = new Regex(@"\d{2}-\d{2}-\d{2}\s\d{2}-\d{2}"); + + Match m = regex.Match(text); + if (m.Success) + return m.Value; + return ""; + //if (m.Success) + //{ + // DateTime dt = DateTime.ParseExact(m.Value, "yyyy-MM-dd-hh-mm-ss", CultureInfo.InvariantCulture); + //} + } } - } diff --git a/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/Analyzers/FlowAnalyser.cs b/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/Analyzers/FlowAnalyser.cs index e6de49c3b..551d2631d 100644 --- a/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/Analyzers/FlowAnalyser.cs +++ b/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/Analyzers/FlowAnalyser.cs @@ -97,6 +97,7 @@ namespace Tango.DispenserAnalyzer.UI.Analyzers result.BackgroundMode = backgroundMode; result.AverageValue = averageResult.AverageValue; result.SetLocalErrors(differenceMaxMin, differenceMaxMinToLocationArr); + result.CalculteTrendOfChart(differenceMaxMin); results.Add(result); } else//testing PBU @@ -106,7 +107,8 @@ namespace Tango.DispenserAnalyzer.UI.Analyzers int avgMinIndex = rangeTestValues.Select(x => x.Index).Min(); int avgMaxIndex = rangeTestValues.Select(x => x.Index).Max(); double totalsec = TimeSpan.FromMilliseconds((avgMaxIndex - avgMinIndex) * 100).TotalSeconds; - result.Time = totalsec.ToString() + $" sec (succeed for period < {AnalyzerSettingsEnum.FlowPBUPassFail})"; ; + result.Time = totalsec.ToString() + $" sec (succeed for period < {AnalyzerSettingsEnum.FlowPBUPassFail})"; + result.OnlyTime = totalsec.ToString(); result.Result = (totalsec < (double)Settings.GetValueByName(AnalyzerSettingsEnum.FlowPBUPassFail)) ? AnalyzerResultValue.Passed : AnalyzerResultValue.Failed; results.Add(result); } @@ -152,6 +154,14 @@ namespace Tango.DispenserAnalyzer.UI.Analyzers public int TestNumber { get; set; } + public double PersentageOfError { get; set; } + + public int MaxLocalError { get; set; } + + public int Occurrence { get; set; } + + public string Trend { get; set; } + #endregion Properties public FlowAnalyzerResult(int testNumber) :base() @@ -211,6 +221,55 @@ namespace Tango.DispenserAnalyzer.UI.Analyzers } } + public void CalculteTrendOfChart(List<int> points) + { + int interval = (int)points.Count/6; + List<int> average_results = new List<int>(); + for (int i = 0; i < points.Count; i += interval) + { + var b = points.Skip(i).Take(interval).Average(); + average_results.Add((int)(points.Skip(i).Take(interval).Average())); + } + if(average_results.Count <=1) + { + Trend = "Unsteady"; + return; + } + // strictly increasing + if (average_results[0] < average_results[average_results.Count-1]) + { + + int i = 1; + // Check for strictly + // increasing condition + // & find the break point + while (i < average_results.Count && average_results[i - 1] <= average_results[i]) + { + i++; + } + if(i >= average_results.Count-1 ) + { + Trend = "Increase"; + return; + } + } + else + { + int i = 1; + while (i < average_results.Count && average_results[i - 1] >= average_results[i]) + { + i++; + } + if (i >= average_results.Count-1 ) + { Trend = "Decrease"; + return; + } + } + + Trend = "Wave"; + + } + private double BuildMeasurementError(List<int> range_values) { int count = range_values.Count(); @@ -228,8 +287,6 @@ namespace Tango.DispenserAnalyzer.UI.Analyzers double dividerMaxError = (double)Settings.GetValueByName(AnalyzerSettingsEnum.DividerMaxError);// BuildMeasurementError(range_values); double sum = 0; int max_key = 0; - int range = 0; - int occurrence = 0; for (int i = countValArr.Count() - 1; i >= 0; i--) { @@ -238,26 +295,26 @@ namespace Tango.DispenserAnalyzer.UI.Analyzers max_key = (int)countValArr[i].Key; if (sum > merror) { - double persentageOfError = countValArr[i].Key / dividerMaxError * 100; - range = countValArr[i].Key; - occurrence = countValArr[i].Value; - LocalErrors = $" {persentageOfError.ToString("F2")}% where max local error = {range.ToString()} and occurrence = {occurrence.ToString()}"; + PersentageOfError = countValArr[i].Key / dividerMaxError * 100; + MaxLocalError = countValArr[i].Key; + Occurrence = countValArr[i].Value; + LocalErrors = $" {PersentageOfError.ToString("F2")}% where max local error = {MaxLocalError.ToString()} and occurrence = {Occurrence.ToString()}"; break; } } - var res = range / dividerMaxError * 100; + var res = MaxLocalError / dividerMaxError * 100; if(res <= (double)Settings.GetValueByName(AnalyzerSettingsEnum.MaxError)) Result = AnalyzerResultValue.Passed; - else if(range <= 26) + else if(MaxLocalError <= 26) { Result = AnalyzerResultValue.Failed; - var entryindeviations = deviationsValArr.FirstOrDefault(x => x.Key == range); + var entryindeviations = deviationsValArr.FirstOrDefault(x => x.Key == MaxLocalError); if (entryindeviations != null) { int val = entryindeviations.Value; - if((occurrence - val) == 0) + if((Occurrence - val) == 0) Result = AnalyzerResultValue.Passed; } } diff --git a/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/Analyzers/PrimingAnalyzer.cs b/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/Analyzers/PrimingAnalyzer.cs index aee0e1c4c..5b7cb74f5 100644 --- a/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/Analyzers/PrimingAnalyzer.cs +++ b/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/Analyzers/PrimingAnalyzer.cs @@ -64,11 +64,14 @@ namespace Tango.DispenserAnalyzer.UI.Analyzers { [Description("PBU Time")] public String Time { get; set; } - + + public String OnlyTime { get; set; } + public PrimingAnalyzerResult() { Time = ""; + OnlyTime = ""; Result = AnalyzerResultValue.Undetermined; } } diff --git a/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/ExcelModel/ExcelDataModel.cs b/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/ExcelModel/ExcelDataModel.cs new file mode 100644 index 000000000..678038c59 --- /dev/null +++ b/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/ExcelModel/ExcelDataModel.cs @@ -0,0 +1,30 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Tango.DispenserAnalyzer.UI.ExcelModel +{ + public class ExcelDataModel + { + public int No___of_test { get; set; } + public String DISPENSER { get; set; } + public int iteration { get; set; } + public String Location { get; set; } + public String DATE { get; set; } + public String PBU___sec__First_cycle { get; set; } + public String Average_Value { get; set; } + public String Max_Error { get; set; } + public String Error__mBr { get; set; } + public String Trend { get; set; } + public String PBU___sec__Second_cycle { get; set; } + public String AverageValue2 { get; set; } + public String MaxError2 { get; set; } + public String Error2 { get; set; } + public String Trend2 { get; set; } + public String Test_result { get; set; } + public String Last_Action { get; set; } + public String Eng_Recommendations { get; set; } + } +} diff --git a/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/MainWindow.xaml b/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/MainWindow.xaml index a3ec370f2..544425328 100644 --- a/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/MainWindow.xaml +++ b/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/MainWindow.xaml @@ -84,8 +84,11 @@ <Border Visibility="Visible" BorderThickness="1" BorderBrush="Silver" CornerRadius="5" Margin="10" Grid.Row="3"> <DockPanel VerticalAlignment="Stretch" HorizontalAlignment="Stretch"> - <Grid DockPanel.Dock="Top" Height="35"> - <Label Height="35" Content="RESULT" Background="LightSkyBlue" Grid.Row="0" /> + <Grid DockPanel.Dock="Top" Height="35" Background="LightSkyBlue"> + <StackPanel Orientation="Horizontal"> + <Label Content="RESULTS" Background="Transparent" Foreground="WhiteSmoke" VerticalAlignment="Center" FontWeight="SemiBold" /> + <Button BorderThickness="1" BorderBrush="Transparent" Margin="16 2 2 2" Padding="6" Height="30" Command="{Binding SaveExelCommand}" MinWidth="60" VerticalContentAlignment="Center">Save in excel</Button> + </StackPanel> <StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Visibility="{Binding IsCompareVisible}"> <ListBox ItemsSource="{Binding ResultsToCompare}" ScrollViewer.VerticalScrollBarVisibility="Auto" MaxWidth="660"> <ListBox.ItemsPanel> diff --git a/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/Settings.cs b/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/Settings.cs index b370169c7..f93b89d96 100644 --- a/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/Settings.cs +++ b/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/Settings.cs @@ -47,6 +47,8 @@ namespace Tango.DispenserAnalyzer.UI DeviationAtRevolutionsMin, [Description("Deviation range")] DeviationAtRevolutionsMax, + [Description("Directory path to save excel file")] + DirectoryPath, } @@ -75,6 +77,7 @@ namespace Tango.DispenserAnalyzer.UI DefaultValues[AnalyzerSettingsEnum.DividerMaxError] = 1500.0; DefaultValues[AnalyzerSettingsEnum.DeviationAtRevolutionsMin] = 200.0; DefaultValues[AnalyzerSettingsEnum.DeviationAtRevolutionsMax] = 218.0; + DefaultValues[AnalyzerSettingsEnum.DirectoryPath] = ""; CurrentValues = new Dictionary<AnalyzerSettingsEnum, object>(DefaultValues); @@ -102,6 +105,10 @@ namespace Tango.DispenserAnalyzer.UI } return value; } + public static void SetDefaultPath(string path) + { + DefaultValues[AnalyzerSettingsEnum.DirectoryPath] = path; + } public static void SerializeSettings(string path) { diff --git a/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/Tango.DispenserAnalyzer.UI.csproj b/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/Tango.DispenserAnalyzer.UI.csproj index cbcd737c9..455a475b9 100644 --- a/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/Tango.DispenserAnalyzer.UI.csproj +++ b/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/Tango.DispenserAnalyzer.UI.csproj @@ -15,7 +15,7 @@ <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects> <Deterministic>true</Deterministic> <IsWebBootstrapper>false</IsWebBootstrapper> - <PublishUrl>X:\Dispenser Analyzer Installer\Version 5.1.1.1\</PublishUrl> + <PublishUrl>X:\Dispenser Analyzer Installer\Version 6.1.1.1\</PublishUrl> <Install>true</Install> <InstallFrom>Disk</InstallFrom> <UpdateEnabled>false</UpdateEnabled> @@ -29,8 +29,8 @@ <ProductName>Dispenser Analyser</ProductName> <PublisherName>Twine</PublisherName> <OpenBrowserOnPublish>false</OpenBrowserOnPublish> - <ApplicationRevision>4</ApplicationRevision> - <ApplicationVersion>5.1.1.%2a</ApplicationVersion> + <ApplicationRevision>1</ApplicationRevision> + <ApplicationVersion>6.1.1.%2a</ApplicationVersion> <UseApplicationTrust>true</UseApplicationTrust> <CreateDesktopShortcut>true</CreateDesktopShortcut> <PublishWizardCompleted>true</PublishWizardCompleted> @@ -81,6 +81,15 @@ <Reference Include="MathNet.Numerics, Version=4.9.0.0, Culture=neutral, processorArchitecture=MSIL"> <HintPath>..\..\packages\MathNet.Numerics.4.9.0\lib\net461\MathNet.Numerics.dll</HintPath> </Reference> + <Reference Include="Microsoft.WindowsAPICodePack, Version=1.1.0.0, Culture=neutral, processorArchitecture=MSIL"> + <HintPath>..\..\packages\Microsoft.WindowsAPICodePack-Core.1.1.0.0\lib\Microsoft.WindowsAPICodePack.dll</HintPath> + </Reference> + <Reference Include="Microsoft.WindowsAPICodePack.Shell, Version=1.1.0.0, Culture=neutral, processorArchitecture=MSIL"> + <HintPath>..\..\packages\Microsoft.WindowsAPICodePack-Shell.1.1.0.0\lib\Microsoft.WindowsAPICodePack.Shell.dll</HintPath> + </Reference> + <Reference Include="Microsoft.WindowsAPICodePack.ShellExtensions, Version=1.1.0.0, Culture=neutral, processorArchitecture=MSIL"> + <HintPath>..\..\packages\Microsoft.WindowsAPICodePack-Shell.1.1.0.0\lib\Microsoft.WindowsAPICodePack.ShellExtensions.dll</HintPath> + </Reference> <Reference Include="Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL"> <HintPath>..\..\packages\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll</HintPath> </Reference> @@ -148,6 +157,7 @@ <Compile Include="Analysis\AnalyzerAttribute.cs" /> <Compile Include="Converters\ObjectToBoolConverter.cs" /> <Compile Include="Converters\ObjectToDoubleConverter.cs" /> + <Compile Include="ExcelModel\ExcelDataModel.cs" /> <Compile Include="FileHelper.cs" /> <Compile Include="Models\CompareResultModel.cs" /> <Compile Include="Models\DispenserCsvRow.cs" /> @@ -207,12 +217,15 @@ <LastGenOutput>Resources.Designer.cs</LastGenOutput> </EmbeddedResource> <EmbeddedResource Include="Models\FlowRangeToTimeResults.xlsx" /> - <None Include="packages.config" /> + <None Include="packages.config"> + <SubType>Designer</SubType> + </None> <None Include="Properties\app.manifest" /> <None Include="Properties\Settings.settings"> <Generator>SettingsSingleFileGenerator</Generator> <LastGenOutput>Settings.Designer.cs</LastGenOutput> </None> + <EmbeddedResource Include="Templates\DispensersData.xlsx" /> </ItemGroup> <ItemGroup> <None Include="App.config" /> diff --git a/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/Templates/DispensersData.xlsx b/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/Templates/DispensersData.xlsx Binary files differnew file mode 100644 index 000000000..a5445a951 --- /dev/null +++ b/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/Templates/DispensersData.xlsx diff --git a/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/View/SettingsWnd.xaml b/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/View/SettingsWnd.xaml index c054627a1..febb2086f 100644 --- a/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/View/SettingsWnd.xaml +++ b/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/View/SettingsWnd.xaml @@ -148,7 +148,7 @@ <DataGridTemplateColumn.CellTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> - <TextBox Text="{Binding PropertyValue, Mode=TwoWay, UpdateSourceTrigger=LostFocus, Converter={StaticResource ObjectToDoubleConverter}}" Width="50" VerticalAlignment="Top"> + <TextBox Text="{Binding PropertyValue, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="150" VerticalAlignment="Top" TextWrapping="Wrap"> <TextBox.Style> <Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource MaterialDesignTextBox}"> <Setter Property="Visibility" Value="Visible"/> @@ -193,7 +193,7 @@ </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> - <DataGridTextColumn Header="Default Value" Binding="{Binding DefaultValueDisplay}" Width="150" ElementStyle="{StaticResource WrapText}" /> + <DataGridTextColumn Header="Default Value" Binding="{Binding DefaultValueDisplay}" Width="150" ElementStyle="{StaticResource WrapText}" CanUserReorder="False" IsReadOnly="True" /> <DataGridTemplateColumn Header="" Width="Auto"> <DataGridTemplateColumn.CellStyle> <Style TargetType="DataGridCell" BasedOn="{StaticResource {x:Type DataGridCell}}"> diff --git a/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/ViewModels/MainWindowVM.cs b/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/ViewModels/MainWindowVM.cs index 9981166e2..33b0cb2f7 100644 --- a/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/ViewModels/MainWindowVM.cs +++ b/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/ViewModels/MainWindowVM.cs @@ -4,6 +4,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Win32; +using Microsoft.WindowsAPICodePack.Dialogs; using Tango.Core.Commands; using Tango.CSV; using Tango.DispenserAnalyzer.UI.Models; @@ -26,9 +27,15 @@ using System.Windows.Xps.Packaging; using System.Windows.Media.Imaging; using PdfSharp; using OxyPlot.Reporting; -using System.Threading; +using Tango.Documents; using Tango.DispenserAnalyzer.UI.View; - +using Tango.Core.Helpers; +using Tango.DispenserAnalyzer.UI.ExcelModel; +using Tango.DispenserAnalyzer.UI.Analyzers; +using static Tango.DispenserAnalyzer.UI.Analyzers.FlowAnalyser; +using System.Text.RegularExpressions; +using System.Reflection; +using System.Globalization; namespace Tango.DispenserAnalyzer.UI.ViewModels { @@ -249,6 +256,7 @@ namespace Tango.DispenserAnalyzer.UI.ViewModels public RelayCommand GenerateCommand { get; set; } public RelayCommand OpenSettingWndCommand { get; set; } public RelayCommand CompareCommand { get; set; } + public RelayCommand SaveExelCommand { get; set; } #endregion public MainWindowVM() @@ -259,6 +267,7 @@ namespace Tango.DispenserAnalyzer.UI.ViewModels GenerateCommand = new RelayCommand(Generate, CanGenerate); OpenSettingWndCommand = new RelayCommand(OpenSettingWnd); CompareCommand = new RelayCommand(Compareresults, CanCompareresults); + SaveExelCommand = new RelayCommand(SaveExel, CanSaveExel); YFormatter = value => value.ToString(); _from = 0; @@ -382,6 +391,7 @@ namespace Tango.DispenserAnalyzer.UI.ViewModels FileHelper.OpenFilePath = OpenFilePath; FileName = Path.GetFileName(OpenFilePath); } + SaveExelCommand.RaiseCanExecuteChanged(); } #endregion @@ -389,6 +399,7 @@ namespace Tango.DispenserAnalyzer.UI.ViewModels public bool CanGenerate() { + var value = (OpenFilePath != null && OpenFilePath.Length != 0 && File.Exists(OpenFilePath)); return (OpenFilePath!= null && OpenFilePath.Length != 0 && File.Exists(OpenFilePath)); } @@ -464,6 +475,7 @@ namespace Tango.DispenserAnalyzer.UI.ViewModels { await PrintToXpsFile(); } + InvalidateRelayCommands(); } /// <summary> @@ -497,6 +509,7 @@ namespace Tango.DispenserAnalyzer.UI.ViewModels List<IAnalyzerResult> res = await analyzer.Process(samples, true); AnalyzerResults = new ObservableCollection<IAnalyzerResult>(res); + await ExportResultsToTextFile(); } @@ -707,6 +720,205 @@ namespace Tango.DispenserAnalyzer.UI.ViewModels }); } + + public async void ExportFlowResultsToExcel() + { + string filePath = (string)Settings.GetValueByName(AnalyzerSettingsEnum.DirectoryPath); + + if (!Directory.Exists(filePath)) + { + CommonOpenFileDialog dialog = new CommonOpenFileDialog(); + dialog.InitialDirectory = "C:\\Users"; + dialog.IsFolderPicker = true; + if (dialog.ShowDialog() == CommonFileDialogResult.Ok) + { + filePath = dialog.FileName; + if (filePath.Count(x => x == '%') == 2) + { + var variable = Regex.Match(filePath, "(?<=%)(.*?)(?=%)").Value; + filePath = filePath.Replace($"%{variable}%", Environment.ExpandEnvironmentVariables($"%{variable}%")); + } + Settings.SetValueByName(AnalyzerSettingsEnum.DirectoryPath, filePath); + Settings.SetDefaultPath(filePath); + } + else + { + MessageBox.Show("An error occurred while trying to open directory for saving result. ", + "Warning", + MessageBoxButton.OK, + MessageBoxImage.Warning); + return; + } + } + await Task.Run(() => + { + ExcelWriter writer = null; + ExcelReader reader = null; + try + { + IsFree = false; + + Stream stream = null; + bool dispose = false; + + if (false == filePath.EndsWith(@"\")) + { + filePath += @"\"; + } + String file = filePath + $"DispensersData.xlsx"; + + if (File.Exists(file)) + { + //stream = File.OpenRead(file); + stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); + dispose = true; + } + else + { + var b = Assembly.GetExecutingAssembly().GetManifestResourceNames(); + stream = EmbeddedResourceHelper.GetEmbeddedResourceStream("Tango.DispenserAnalyzer.UI.Templates.DispensersData.xlsx"); + } + if (stream == null) + return; + + byte[] data = new byte[stream.Length]; + stream.Read(data, 0, data.Length); + File.WriteAllBytes(file, data); + + if (dispose) + { + stream.Dispose(); + } + reader = new ExcelReader(file); + List<ExcelDataModel> old_threadCharacteristicsExelModels = reader.GetDataByIndex<ExcelDataModel>("Data", 2); + reader.Dispose(); + reader = null; + + + int maxNumber = old_threadCharacteristicsExelModels.Count > 0 ? old_threadCharacteristicsExelModels.OrderBy(x => x.No___of_test).Max(x => x.No___of_test) : 0; + maxNumber++; + var time_test = AnalysisService.GetDateTimeString(FileName); + + var dispenser = AnalysisService.GetDispenserNumber(FileName); + int iterations = 0; + if (old_threadCharacteristicsExelModels.Count > 0) + { + var one_existed = old_threadCharacteristicsExelModels.OrderBy(x => x.No___of_test).Count(x => x.DISPENSER == dispenser && x.DATE == time_test); + if (one_existed > 0) + { + InvokeUI(() => + { + var warningresult = MessageBox.Show($"The result is already saved for the dispenser {dispenser} at time {time_test}. Do you want to save it anyway?", + "Warning", + MessageBoxButton.YesNo, + MessageBoxImage.Question); + if(warningresult == MessageBoxResult.Cancel) + return; + }); + } + iterations = old_threadCharacteristicsExelModels.OrderBy(x => x.No___of_test).Count(x => x.DISPENSER == dispenser ); + + } + iterations++; + + //write results + List<ExcelDataModel> threadCharacteristicsExelModels = new List<ExcelDataModel>(); + ExcelDataModel model = new ExcelDataModel(); + + model.No___of_test = maxNumber;//Could be defiend and saved + model.DISPENSER = dispenser; + model.iteration = iterations; + model.Location = FileName.IndexOf("CH8") > 0 ? "Dagesh" : "Twine"; + model.DATE = time_test; + List<IAnalyzerResult> results = AnalyzerResults.ToList(); + bool firstFlowAverageResult = true; + bool firstPrimingResult = true; + bool firstErrorResult = true; + bool pass = true; + foreach (var res in results) + { + if (res is PrimingAnalyzerResult) + { + if (firstPrimingResult) + { + model.PBU___sec__First_cycle = (res as PrimingAnalyzerResult).OnlyTime; + firstPrimingResult = false; + } + else + { + model.PBU___sec__Second_cycle = (res as PrimingAnalyzerResult).OnlyTime; + } + } + else if (res is FlowAverageAnalyzerResult) + { + if (firstFlowAverageResult) + { + model.Average_Value = (res as FlowAverageAnalyzerResult).AverageValue.ToString("0.##"); + firstFlowAverageResult = false; + if ((res as FlowAverageAnalyzerResult).Result == AnalyzerResultValue.Failed) + pass = false; + } + else + { + model.AverageValue2 = (res as FlowAverageAnalyzerResult).AverageValue.ToString("0.##"); + if ((res as FlowAverageAnalyzerResult).Result == AnalyzerResultValue.Failed) + pass = false; + } + } + else if (res is FlowAnalyzerResult) + { + if (firstErrorResult) + { + model.Max_Error = (res as FlowAnalyzerResult).PersentageOfError.ToString("0.##"); + model.Error__mBr = (res as FlowAnalyzerResult).MaxLocalError.ToString(); + model.Trend = (res as FlowAnalyzerResult).Trend; + firstErrorResult = false; + } + else + { + model.MaxError2 = (res as FlowAnalyzerResult).PersentageOfError.ToString("0.##"); + model.Error2 = (res as FlowAnalyzerResult).MaxLocalError.ToString(); + model.Trend2 = (res as FlowAnalyzerResult).Trend; + } + } + } + + model.Test_result = pass ? "Pass" : "Fail"; + model.Eng_Recommendations = "-"; + model.Last_Action = "-"; + + threadCharacteristicsExelModels.Add(model); + + writer = new ExcelWriter(file); + writer.WriteData(threadCharacteristicsExelModels, "Data"); + + writer.Dispose(); + writer = null; + + } + catch (Exception ex) + { + InvokeUI(() => + { + MessageBox.Show("An error occurred while trying to save results in file DispensersData.xlsx. Error" + ex.Message, + "Warning", + MessageBoxButton.OK, + MessageBoxImage.Warning); + }); + } + finally + { + IsFree = true; + + if (reader != null) + reader.Dispose(); + if (writer != null) + writer.Dispose(); + + } + }); + + } #endregion #region CompareResults @@ -762,6 +974,23 @@ namespace Tango.DispenserAnalyzer.UI.ViewModels } } - #endregion - } + public bool CanSaveExel(object arg) + { + var analyzer = AnalysisService.GetAnalyzer(OpenFilePath); + if (analyzer == null) + return false; + return AnalyzerResults.Count > 0 && analyzer is FlowAnalyser; + } + + private void SaveExel() + { + if(!IsFree) + return; + + // await ExportRMLToExcel().ConfigureAwait(false); + ExportFlowResultsToExcel(); + } + + #endregion + } } diff --git a/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/ViewModels/SettingsVM.cs b/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/ViewModels/SettingsVM.cs index 515b2df4e..a65e26169 100644 --- a/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/ViewModels/SettingsVM.cs +++ b/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/ViewModels/SettingsVM.cs @@ -93,6 +93,7 @@ namespace Tango.DispenserAnalyzer.UI.ViewModels list.Add(new BaseSettingModel(AnalyzerSettingsEnum.CancelMovingAVG, "False")); list.Add(new BaseSettingModel(AnalyzerSettingsEnum.DividerMaxError, "1500")); list.Add(new BaseSettingModel(AnalyzerSettingsEnum.DeviationAtRevolutionsMin, AnalyzerSettingsEnum.DeviationAtRevolutionsMax, "200-218")); + list.Add(new BaseSettingModel(AnalyzerSettingsEnum.DirectoryPath, "")); list.ForEach(x => x.SettingValueEvent += new EventHandler(OnSettingValueChanged)); model.AddSettings(list); Settings.Add(model); diff --git a/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/packages.config b/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/packages.config index 6b2dea0ab..6da0d32dc 100644 --- a/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/packages.config +++ b/Software/Visual_Studio/Utilities/Tango.DispenserAnalyzer.UI/packages.config @@ -1,6 +1,8 @@ <?xml version="1.0" encoding="utf-8"?> <packages> <package id="MathNet.Numerics" version="4.9.0" targetFramework="net461" /> + <package id="Microsoft.WindowsAPICodePack-Core" version="1.1.0.0" targetFramework="net461" /> + <package id="Microsoft.WindowsAPICodePack-Shell" version="1.1.0.0" targetFramework="net461" /> <package id="Newtonsoft.Json" version="12.0.3" targetFramework="net461" /> <package id="OxyPlot.Core" version="2.0.0" targetFramework="net461" /> <package id="OxyPlot.Wpf" version="2.0.0" targetFramework="net461" /> |
