Move data validation on modelview data structure.

This commit is contained in:
Adrien Allard committed 2019-07-01 17:07:58 +02:00
1 parent 6ad9c72b7e
commit 92477c8c79
5 files changed
+273 -275

No files matched your search

@@ -17,7 +17,7 @@ namespace FileConverter
[XmlRoot]
[XmlType]
public class ConversionPreset : ObservableObject, IDataErrorInfo, IXmlSerializable
public class ConversionPreset : ObservableObject, IXmlSerializable
{
private string shortName;
@@ -282,34 +282,6 @@ namespace FileConverter
}
}
public string Error
{
get
{
string errorString = this.Validate("ShortName");
if (!string.IsNullOrEmpty(errorString))
{
return errorString;
}
errorString = this.Validate("OutputFileNameTemplate");
if (!string.IsNullOrEmpty(errorString))
{
return errorString;
}
return string.Empty;
}
}
public string this[string columnName]
{
get
{
return this.Validate(columnName);
}
}
public void Clean()
{
// Remove unrelevant settings.
@@ -587,107 +559,6 @@ namespace FileConverter
}
}
private string Validate(string propertyName)
{
// Return error message if there is an error, else return empty or null string.
switch (propertyName)
{
case "ShortName":
{
if (string.IsNullOrEmpty(this.ShortName))
{
return "The preset name can't be empty.";
}
if (this.ShortName.Contains(";"))
{
return "The preset name can't contains the character ';'.";
}
if (this.ShortName.Contains("/"))
{
return "The preset name can't contains the character '/'.";
}
ISettingsService settingsService = SimpleIoc.Default.GetInstance<ISettingsService>();
int? count = settingsService.Settings?.ConversionPresets?.Count(match => match?.shortName == this.ShortName);
if (count > 1)
{
return "The preset name is already used.";
}
}
break;
case "OutputFileNameTemplate":
{
string sampleOutputFilePath = this.GenerateOutputFilePath(FileConverter.Properties.Resources.OutputFileNameTemplateSample, 1, 3);
if (string.IsNullOrEmpty(sampleOutputFilePath))
{
return "The output filename template must produce a non empty result.";
}
if (!PathHelpers.IsPathValid(sampleOutputFilePath))
{
// Diagnostic to feedback purpose.
// Drive letter.
if (!PathHelpers.IsPathDriveLetterValid(sampleOutputFilePath))
{
return "The output filename template must define a root (for example c:\\, use (p) to use the input file path).";
}
// File name.
string filename = PathHelpers.GetFileName(sampleOutputFilePath);
if (filename == null)
{
return "The output file name must not be empty (use (f) to use the name of the input file).";
}
char[] invalidFileNameChars = System.IO.Path.GetInvalidFileNameChars();
for (int index = 0; index < invalidFileNameChars.Length; index++)
{
if (filename.Contains(invalidFileNameChars[index]))
{
return "The output file name must not contains the character '" + invalidFileNameChars[index] + "'.";
}
}
// Directory names.
string path = sampleOutputFilePath.Substring(3, sampleOutputFilePath.Length - 3 - filename.Length);
char[] invalidPathChars = System.IO.Path.GetInvalidPathChars();
for (int index = 0; index < invalidPathChars.Length; index++)
{
if (string.IsNullOrEmpty(path))
{
return "The output directory name must not be empty (use (d0), (d1), ... to use the name of the parent directories of the input file).";
}
if (path.Contains(invalidPathChars[index]))
{
return "The output directory name must not contains the character '" + invalidPathChars[index] + "'.";
}
}
string[] directories = path.Split('\\');
for (int index = 0; index < directories.Length; ++index)
{
string directoryName = directories[index];
if (string.IsNullOrEmpty(directoryName))
{
return "The output directory name must not be empty (use (d0), (d1), ... to use the name of the parent directories of the input file).";
}
}
return "The output filename template is invalid";
}
}
break;
}
return string.Empty;
}
public struct ConversionSetting
{
public ConversionSetting(KeyValuePair<string, string> keyValuePair)
+1 -28
View File
@@ -12,7 +12,7 @@ namespace FileConverter
[XmlRoot]
[XmlType]
public class Settings : ObservableObject, IDataErrorInfo, IXmlSerializable
public class Settings : ObservableObject, IXmlSerializable
{
public const int Version = 4;
@@ -22,33 +22,6 @@ namespace FileConverter
private bool checkUpgradeAtStartup = true;
private CultureInfo applicationLanguage;
private int maximumNumberOfSimultaneousConversions;
[XmlIgnore]
public string Error
{
get
{
for (int index = 0; index < this.ConversionPresets.Count; index++)
{
string error = this.ConversionPresets[index].Error;
if (!string.IsNullOrEmpty(error))
{
return error;
}
}
return string.Empty;
}
}
[XmlIgnore]
public string this[string columnName]
{
get
{
return this.Error;
}
}
public ConversionPreset GetPresetFromName(string presetName)
{
@@ -2,11 +2,13 @@
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using GalaSoft.MvvmLight;
namespace FileConverter.ViewModels
{
public abstract class AbstractTreeNode : ObservableObject
public abstract class AbstractTreeNode : ObservableObject, IDataErrorInfo
{
private PresetFolderNode parent;
@@ -36,6 +38,72 @@ namespace FileConverter.ViewModels
get;
set;
}
public string this[string columnName] => this.Validate(columnName);
public string Error
{
get
{
if (this.Parent == null)
{
// This is the root folder. Don't check rules on this specific folder.
return string.Empty;
}
string errorString = this.Validate("Name");
if (!string.IsNullOrEmpty(errorString))
{
return errorString;
}
errorString = this.Validate("OutputFileNameTemplate");
if (!string.IsNullOrEmpty(errorString))
{
return errorString;
}
return string.Empty;
}
}
protected virtual string Validate(string propertyName)
{
// Return error message if there is an error, else return empty or null string.
switch (propertyName)
{
case "Name":
{
if (string.IsNullOrEmpty(this.Name))
{
return "The preset name can't be empty.";
}
if (this.Name.Contains(";"))
{
return "The preset name can't contains the character ';'.";
}
if (this.Name.Contains("/"))
{
return "The preset name can't contains the character '/'.";
}
if (this.Parent != null)
{
int count = this.Parent.Children.Count(node => node.Name == this.Name);
if (count > 1)
{
return "The preset name is already used.";
}
}
}
break;
}
return string.Empty;
}
}
public class PresetNode : AbstractTreeNode
@@ -69,6 +137,100 @@ namespace FileConverter.ViewModels
this.RaisePropertyChanged();
}
}
public string OutputFileNameTemplate
{
get
{
return this.Preset.OutputFileNameTemplate;
}
set
{
this.Preset.OutputFileNameTemplate = value;
this.RaisePropertyChanged();
}
}
protected override string Validate(string propertyName)
{
string error = base.Validate(propertyName);
if (!string.IsNullOrEmpty(error))
{
return error;
}
// Return error message if there is an error, else return empty or null string.
switch (propertyName)
{
case "OutputFileNameTemplate":
{
string sampleOutputFilePath = this.Preset.GenerateOutputFilePath(FileConverter.Properties.Resources.OutputFileNameTemplateSample, 1, 3);
if (string.IsNullOrEmpty(sampleOutputFilePath))
{
return "The output filename template must produce a non empty result.";
}
if (!PathHelpers.IsPathValid(sampleOutputFilePath))
{
// Diagnostic to feedback purpose.
// Drive letter.
if (!PathHelpers.IsPathDriveLetterValid(sampleOutputFilePath))
{
return "The output filename template must define a root (for example c:\\, use (p) to use the input file path).";
}
// File name.
string filename = PathHelpers.GetFileName(sampleOutputFilePath);
if (filename == null)
{
return "The output file name must not be empty (use (f) to use the name of the input file).";
}
char[] invalidFileNameChars = System.IO.Path.GetInvalidFileNameChars();
for (int index = 0; index < invalidFileNameChars.Length; index++)
{
if (filename.Contains(invalidFileNameChars[index]))
{
return "The output file name must not contains the character '" + invalidFileNameChars[index] + "'.";
}
}
// Directory names.
string path = sampleOutputFilePath.Substring(3, sampleOutputFilePath.Length - 3 - filename.Length);
char[] invalidPathChars = System.IO.Path.GetInvalidPathChars();
for (int index = 0; index < invalidPathChars.Length; index++)
{
if (string.IsNullOrEmpty(path))
{
return "The output directory name must not be empty (use (d0), (d1), ... to use the name of the parent directories of the input file).";
}
if (path.Contains(invalidPathChars[index]))
{
return "The output directory name must not contains the character '" + invalidPathChars[index] + "'.";
}
}
string[] directories = path.Split('\\');
for (int index = 0; index < directories.Length; ++index)
{
string directoryName = directories[index];
if (string.IsNullOrEmpty(directoryName))
{
return "The output directory name must not be empty (use (d0), (d1), ... to use the name of the parent directories of the input file).";
}
}
return "The output filename template is invalid";
}
}
break;
}
return string.Empty;
}
}
public class PresetFolderNode : AbstractTreeNode
@@ -34,7 +34,7 @@ namespace FileConverter.ViewModels
/// See http://www.galasoft.ch/mvvm
/// </para>
/// </summary>
public class SettingsViewModel : ViewModelBase
public class SettingsViewModel : ViewModelBase, IDataErrorInfo
{
private InputExtensionCategory[] inputCategories;
private PresetFolderNode presetsRootFolder;
@@ -61,6 +61,16 @@ namespace FileConverter.ViewModels
/// </summary>
public SettingsViewModel()
{
this.getChangeLogContentCommand = new RelayCommand(this.DownloadChangeLogAction);
this.openUrlCommand = new RelayCommand<string>((url) => Process.Start(url));
this.createFolderCommand = new RelayCommand(this.CreateFolder);
this.movePresetUpCommand = new RelayCommand(this.MoveSelectedPresetUp, this.CanMoveSelectedPresetUp);
this.movePresetDownCommand = new RelayCommand(this.MoveSelectedPresetDown, this.CanMoveSelectedPresetDown);
this.addNewPresetCommand = new RelayCommand(this.AddNewPreset);
this.removePresetCommand = new RelayCommand(this.RemoveSelectedPreset, this.CanRemoveSelectedPreset);
this.saveCommand = new RelayCommand(this.SaveSettings, this.CanSaveSettings);
this.closeCommand = new RelayCommand<CancelEventArgs>(this.CloseSettings);
if (this.IsInDesignMode)
{
// Code runs in Blend --> create design time data.
@@ -260,122 +270,23 @@ namespace FileConverter.ViewModels
}
}
public ICommand GetChangeLogContentCommand
{
get
{
if (this.getChangeLogContentCommand == null)
{
this.getChangeLogContentCommand = new RelayCommand(this.DownloadChangeLogAction);
}
public ICommand GetChangeLogContentCommand => this.getChangeLogContentCommand;
return this.getChangeLogContentCommand;
}
}
public ICommand OpenUrlCommand => this.openUrlCommand;
public ICommand OpenUrlCommand
{
get
{
if (this.openUrlCommand == null)
{
this.openUrlCommand = new RelayCommand<string>((url) => Process.Start(url));
}
public ICommand CreateFolderCommand => this.createFolderCommand;
return this.openUrlCommand;
}
}
public ICommand MovePresetUpCommand => this.movePresetUpCommand;
public ICommand CreateFolderCommand
{
get
{
if (this.createFolderCommand == null)
{
this.createFolderCommand = new RelayCommand(this.CreateFolder);
}
public ICommand MovePresetDownCommand => this.movePresetDownCommand;
return this.createFolderCommand;
}
}
public ICommand AddNewPresetCommand => this.addNewPresetCommand;
public ICommand MovePresetUpCommand
{
get
{
if (this.movePresetUpCommand == null)
{
this.movePresetUpCommand = new RelayCommand(this.MoveSelectedPresetUp, this.CanMoveSelectedPresetUp);
}
public ICommand RemoveSelectedPresetCommand => this.removePresetCommand;
return this.movePresetUpCommand;
}
}
public ICommand SaveCommand => this.saveCommand;
public ICommand MovePresetDownCommand
{
get
{
if (this.movePresetDownCommand == null)
{
this.movePresetDownCommand = new RelayCommand(this.MoveSelectedPresetDown, this.CanMoveSelectedPresetDown);
}
return this.movePresetDownCommand;
}
}
public ICommand AddNewPresetCommand
{
get
{
if (this.addNewPresetCommand == null)
{
this.addNewPresetCommand = new RelayCommand(this.AddNewPreset);
}
return this.addNewPresetCommand;
}
}
public ICommand RemoveSelectedPresetCommand
{
get
{
if (this.removePresetCommand == null)
{
this.removePresetCommand = new RelayCommand(this.RemoveSelectedPreset, this.CanRemoveSelectedPreset);
}
return this.removePresetCommand;
}
}
public ICommand SaveCommand
{
get
{
if (this.saveCommand == null)
{
this.saveCommand = new RelayCommand(this.SaveSettings, this.CanSaveSettings);
}
return this.saveCommand;
}
}
public ICommand CloseCommand
{
get
{
if (this.closeCommand == null)
{
this.closeCommand = new RelayCommand<CancelEventArgs>(this.CloseSettings);
}
return this.closeCommand;
}
}
public ICommand CloseCommand => this.closeCommand;
public TreeViewSelectionBehavior.IsChildOfPredicate PresetsHierarchyPredicate => (object nodeA, object nodeB) =>
{
@@ -390,6 +301,45 @@ namespace FileConverter.ViewModels
return parentFolder.IsNodeInHierarchy(nodeB as AbstractTreeNode, true);
};
public string Error
{
get
{
string nodeError = this.CheckErrorRecursively(this.presetsRootFolder);
if (!string.IsNullOrEmpty(nodeError))
{
return nodeError;
}
return string.Empty;
}
}
public string this[string columnName] => this.Error;
private string CheckErrorRecursively(AbstractTreeNode node)
{
string nodeError = node.Error;
if (!string.IsNullOrEmpty(nodeError))
{
return nodeError;
}
if (node is PresetFolderNode folder)
{
foreach (AbstractTreeNode child in folder.Children)
{
nodeError = this.CheckErrorRecursively(child);
if (!string.IsNullOrEmpty(nodeError))
{
return nodeError;
}
}
}
return string.Empty;
}
private void SelectedPresetPropertyChanged(object sender, PropertyChangedEventArgs eventArgs)
{
if (eventArgs.PropertyName == "OutputType")
@@ -400,6 +350,11 @@ namespace FileConverter.ViewModels
this.saveCommand.RaiseCanExecuteChanged();
}
private void NodePropertyChanged(object sender, PropertyChangedEventArgs eventArgs)
{
this.saveCommand.RaiseCanExecuteChanged();
}
private void DownloadChangeLogAction()
{
IUpgradeService upgradeService = SimpleIoc.Default.GetInstance<IUpgradeService>();
@@ -457,6 +412,8 @@ namespace FileConverter.ViewModels
{
subFolder = new PresetFolderNode(folderName, parent);
parent.Children.Add(subFolder);
subFolder.PropertyChanged += this.NodePropertyChanged;
}
parent = subFolder;
@@ -464,6 +421,8 @@ namespace FileConverter.ViewModels
PresetNode presetNode = new PresetNode(preset, parent);
parent.Children.Add(presetNode);
presetNode.PropertyChanged += this.NodePropertyChanged;
}
this.RaisePropertyChanged(nameof(this.PresetsRootFolder));
@@ -505,7 +464,7 @@ namespace FileConverter.ViewModels
private bool CanSaveSettings()
{
return this.settings != null && string.IsNullOrEmpty(this.settings.Error);
return string.IsNullOrEmpty(this.Error);
}
private void SaveSettings()
@@ -556,8 +515,12 @@ namespace FileConverter.ViewModels
parent.Children.Insert(insertIndex, newFolder);
newFolder.PropertyChanged += this.NodePropertyChanged;
this.SelectedItem = newFolder;
this.saveCommand.RaiseCanExecuteChanged();
Messenger.Default.Send<string>("FolderName", "DoFocus");
}
@@ -612,8 +575,9 @@ namespace FileConverter.ViewModels
}
this.SelectedItem = itemToMoveUp;
this.movePresetUpCommand?.RaiseCanExecuteChanged();
this.movePresetDownCommand?.RaiseCanExecuteChanged();
this.movePresetUpCommand.RaiseCanExecuteChanged();
this.movePresetDownCommand.RaiseCanExecuteChanged();
this.saveCommand.RaiseCanExecuteChanged();
}
private bool CanMoveSelectedPresetDown()
@@ -668,8 +632,9 @@ namespace FileConverter.ViewModels
this.SelectedItem = itemToMoveDown;
this.movePresetUpCommand?.RaiseCanExecuteChanged();
this.movePresetDownCommand?.RaiseCanExecuteChanged();
this.movePresetUpCommand.RaiseCanExecuteChanged();
this.movePresetDownCommand.RaiseCanExecuteChanged();
this.saveCommand.RaiseCanExecuteChanged();
}
private void AddNewPreset()
@@ -718,25 +683,51 @@ namespace FileConverter.ViewModels
parent.Children.Insert(insertIndex, node);
node.PropertyChanged += this.NodePropertyChanged;
this.SelectedItem = node;
Messenger.Default.Send<string>("PresetName", "DoFocus");
this.removePresetCommand.RaiseCanExecuteChanged();
this.saveCommand.RaiseCanExecuteChanged();
}
private void RemoveSelectedPreset()
{
this.SelectedItem.PropertyChanged -= this.NodePropertyChanged;
this.SelectedItem.Parent.Children.Remove(this.SelectedItem);
this.SelectedItem = null;
this.removePresetCommand.RaiseCanExecuteChanged();
this.saveCommand.RaiseCanExecuteChanged();
}
private bool CanRemoveSelectedPreset()
{
return this.SelectedItem != null;
}
public override void Cleanup()
{
base.Cleanup();
this.UnbindNode(this.presetsRootFolder);
}
private void UnbindNode(AbstractTreeNode node)
{
node.PropertyChanged -= this.NodePropertyChanged;
if (node is PresetFolderNode folder)
{
foreach (AbstractTreeNode child in folder.Children)
{
this.UnbindNode(child);
}
}
}
}
}
@@ -274,8 +274,9 @@
<RowDefinition Height="23"/>
</Grid.RowDefinitions>
<Label Content="{x:Static project:Resources.FileNameTemplate}" Grid.Row="0" HorizontalContentAlignment="Right" Margin="0,0,5,0"/>
<TextBox Grid.Row="0" Grid.Column="1" Margin="5,2,25,2" TextWrapping="Wrap" Width="Auto" ToolTip="{x:Static project:Resources.OutputFilePathTemplateHelp}"
Text="{Binding SelectedPreset.Preset.OutputFileNameTemplate, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" />
<TextBox Grid.Row="0" Grid.Column="1" Margin="5,2,25,2" TextWrapping="Wrap" Width="Auto"
ToolTip="{x:Static project:Resources.OutputFilePathTemplateHelp}"
Text="{Binding SelectedPreset.OutputFileNameTemplate, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" />
<Label Content="{x:Static project:Resources.InputExample}" Grid.Row="1" Grid.Column="0" HorizontalContentAlignment="Right" Margin="0,0,5,0" Foreground="Gray" FontSize="10"/>
<TextBlock Text="{x:Static project:Resources.OutputFileNameTemplateSample}" Grid.Row="1" Grid.Column="1" Margin="5,0,5,0" Foreground="Gray" FontSize="10" VerticalAlignment="Center"/>
<Label Content="{x:Static project:Resources.OutputExample}" Grid.Row="2" Grid.Column="0" HorizontalContentAlignment="Right" Margin="0,0,5,0" Foreground="Gray" FontSize="10"/>