public void JsonFormat_CommentJson_Allowed() { var json = $@" {{ // this is destination ""destination"": ""{_destination}"", // this is pattern ""pattern"": ""{_pattern}"", // this is excludes ""excludes"": [ ""{_excludes[0]}"", ""{_excludes[1]}"", ], // this is exclude_folders ""exclude_folders"": [ ""{_excludeFolders[0]}"", ""{_excludeFolders[1]}"", ] }}"; var settings = CopySettings.LoadJson(json); Assert.Equal(_destination, settings.Destination); Assert.Equal(_pattern, settings.Pattern); Assert.Equal(_excludes, settings.Excludes); Assert.Equal(_excludeFolders, settings.ExcludeFolders); }
public static List <string> CopyDirectoryRecursively(string sourceDirName, string destDirName, List <string> filesToExclude, List <string> foldersToExclude, bool doContainsSearch) { List <string> filesCopied = new List <string>(); if (filesToExclude == null) { filesToExclude = new List <string>(); } if (foldersToExclude == null) { foldersToExclude = new List <string>(); } CopySettings settings = new CopySettings() { IsMovingFiles = false, CopySubFolders = true, ExcludeFiles = filesToExclude, ExcludeFolders = foldersToExclude, ContainsSearchForFiles = doContainsSearch }; try { CopyOrMoveDirectoryRecursively(sourceDirName, destDirName, settings, filesCopied); } catch (Exception e) { Sys.Message(new WMessage(StringKey.FailedToCopyDirectory, WMessageLogLevel.LogOnly, e)); } return(filesCopied); }
private void tsbCopyComponents_Click(object sender, EventArgs e) { var settings = new CopySettings { SourceSolutions = sourceSolutionPicker.SelectedSolutions, TargetSolutions = targetSolutionPicker.SelectedSolutions }; var csForm = new ComponentTypeSelector(); if (csForm.ShowDialog(ParentForm) == DialogResult.OK) { settings.ComponentsTypes = csForm.SelectedComponents; } else { return; } WorkAsync("Starting copy...", (bw, evt) => sManager.CopyComponents((CopySettings)evt.Argument, bw), evt => { if (evt.Error != null) { MessageBox.Show(ParentForm, "An error occured: " + evt.Error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }, evt => SetWorkingMessage(evt.UserState.ToString()), settings); }
public static void MoveDirectoryRecursively(string sourceDirName, string destDirName, List <string> filesToExclude, List <string> foldersToExclude, bool doContainsSearch) { if (filesToExclude == null) { filesToExclude = new List <string>(); } if (foldersToExclude == null) { foldersToExclude = new List <string>(); } CopySettings settings = new CopySettings() { IsMovingFiles = true, CopySubFolders = true, ExcludeFiles = filesToExclude, ExcludeFolders = foldersToExclude, ContainsSearchForFiles = doContainsSearch }; try { CopyOrMoveDirectoryRecursively(sourceDirName, destDirName, settings); } catch (Exception e) { Sys.Message(new WMessage("failed to move directory", WMessageLogLevel.LogOnly, e)); } }
internal static void MoveDirectoryRecursively(string sourceDirName, string destDirName, List <string> filesToExclude, List <string> foldersToExclude, bool doContainsSearch, IProgress <double> progress = null) { if (filesToExclude == null) { filesToExclude = new List <string>(); } if (foldersToExclude == null) { foldersToExclude = new List <string>(); } CopySettings settings = new CopySettings() { IsMovingFiles = true, CopySubFolders = true, ExcludeFiles = filesToExclude, ExcludeFolders = foldersToExclude, ContainsSearchForFiles = doContainsSearch }; try { int count = 0, totalCount = 0; CopyOrMoveDirectoryRecursively(sourceDirName, destDirName, settings, fileCount: ref totalCount, currentCount: ref count, copiedFiles: null, progress: progress); } catch (Exception e) { Logger.Error(e); } }
/// <summary> /// Reflect the fields that are contained within the supplied object and create a copy of them /// </summary> /// <param name="original">The original object that is being copied</param> /// <param name="settings">The copy settings that define how this operation is handled</param> /// <param name="objectCopy">The copy of the original that is being setup</param> /// <param name="typeValue">The type of the original object being copied</param> /// <param name="bindingFlags">The reflection flags that are being used to determine the fields that will be collected</param> /// <param name="filter">Callback function that can be used to determine fields that shouldn't be copied</param> private static void CopyFields(object original, CopySettings settings, object objectCopy, Type typeValue, BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy, Func <FieldInfo, bool> filter = null) { // Run the copy operation for all fields that are contained within this object foreach (FieldInfo field in typeValue.GetFields(bindingFlags)) { // Check if this field is filtered out if (filter != null && !filter(field)) { continue; } // If the field is a primitive type, doesn't need special treatment if (IsPrimitive(field.FieldType)) { continue; } // Create a copy of the field value object fieldOriginal = field.GetValue(original); object fieldCopy = InternalCopy(fieldOriginal, settings); field.SetValue(objectCopy, fieldCopy); } }
internal static void MoveDirectoryRecursively(string sourceDirName, string destDirName, List <string> filesToExclude, List <string> foldersToExclude, bool doContainsSearch) { if (filesToExclude == null) { filesToExclude = new List <string>(); } if (foldersToExclude == null) { foldersToExclude = new List <string>(); } CopySettings settings = new CopySettings() { IsMovingFiles = true, CopySubFolders = true, ExcludeFiles = filesToExclude, ExcludeFolders = foldersToExclude, ContainsSearchForFiles = doContainsSearch }; try { CopyOrMoveDirectoryRecursively(sourceDirName, destDirName, settings); } catch (Exception e) { Logger.Error(e); } }
private void tsbCopyComponents_Click(object sender, EventArgs e) { var settings = new CopySettings { SourceSolutions = sourceSolutionPicker.SelectedSolutions, TargetSolutions = targetSolutionPicker.SelectedSolutions, ConnectionDetail = ConnectionDetail, CheckBestPractice = chkCheckBestPractice.Checked }; var csForm = new ComponentTypeSelector(_omc); if (csForm.ShowDialog(ParentForm) == DialogResult.OK) { settings.ComponentsTypes = csForm.SelectedComponents; } else { return; } WorkAsync(new WorkAsyncInfo { Message = "Starting copy...", AsyncArgument = settings, Work = (bw, evt) => { sManager.CopyComponents((CopySettings)evt.Argument, _omc, bw); }, PostWorkCallBack = evt => { if (evt.Error != null) { MessageBox.Show(ParentForm, "An error occured: " + evt.Error.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }, ProgressChanged = evt => { if (evt.ProgressPercentage == 0) { SetWorkingMessage(evt.UserState.ToString()); } else if (evt.ProgressPercentage == -1) { lvLogs.Items.Add(new ListViewItem(evt.UserState.ToString()) { ForeColor = Color.Red }); } else if (evt.ProgressPercentage == 1) { lvLogs.Items.Add(new ListViewItem(evt.UserState.ToString()) { ForeColor = Color.Green }); } } }); }
public void Empty_Json_Fail() { var json = $@" {{ }}"; Assert.Throws <ArgumentNullException>(() => CopySettings.LoadJson(json)); }
public void Null_Excludes_ExcludeFolders_Fail() { var json = $@" {{ ""destination"": ""{_destination}"", ""pattern"": ""{_pattern}"" }}"; Assert.Throws <ArgumentNullException>(() => CopySettings.LoadJson(json)); }
internal static void MoveDirectoryRecursively(string sourceDirName, string destDirName) { CopySettings settings = new CopySettings() { IsMovingFiles = true, CopySubFolders = true, }; CopyOrMoveDirectoryRecursively(sourceDirName, destDirName, settings); }
/// <summary> /// Create a copy of the original object using a deep member clone by default /// </summary> /// <param name="original">The original object that is to be copied</param> /// <param name="settings">[Optional] The copy settings object that will be used to drive the copy operation</param> /// <returns>Returns a copy of the original object for use</returns> public static object Copy(this object original, CopySettings settings = null) { // Ensure that there is a settings object that can be used if (settings == null) { settings = new CopySettings(); } // Create the copy of the object return(InternalCopy(original, settings)); }
internal static void MoveDirectoryRecursively(string sourceDirName, string destDirName, List <string> filesToExclude, List <string> foldersToInclude) { CopySettings settings = new CopySettings() { IsMovingFiles = true, CopySubFolders = true, ExcludeFiles = filesToExclude, ExcludeFolders = foldersToInclude }; CopyOrMoveDirectoryRecursively(sourceDirName, destDirName, settings); }
/// <summary> /// Recurse down into the base types of the supplied object to copy their private fields /// </summary> /// <param name="original">The original object that is being copied</param> /// <param name="settings">The copy settings that define how this operation is handled</param> /// <param name="objectCopy">The copy of the original that is being setup</param> /// <param name="typeValue">The type of the original object being copied</param> private static void RecursiveCopyBaseTypePrivateFields(object original, CopySettings settings, object objectCopy, Type typeValue) { if (typeValue.BaseType != null) { RecursiveCopyBaseTypePrivateFields(original, settings, objectCopy, typeValue.BaseType); CopyFields( original, settings, objectCopy, typeValue.BaseType, BindingFlags.Instance | BindingFlags.NonPublic, info => info.IsPrivate ); } }
public void InitCommandTest() { var expected = CopySettings.LoadJson(CopySettings.GetTemplateJson()); var program = new Program(); program.Init(_projectDir); Assert.True(File.Exists(_settings)); var generated = File.ReadAllText(_settings, Encoding.UTF8); var actual = CopySettings.LoadJson(generated); Assert.Equal(expected.Destination, actual.Destination); Assert.Equal(expected.Pattern, actual.Pattern); Assert.Equal(expected.Excludes, actual.Excludes); Assert.Equal(expected.ExcludeFolders, actual.ExcludeFolders); }
public void Null_Destination_Fail() { var json = $@" {{ ""pattern"": ""{_pattern}"", ""excludes"": [ ""{_excludes[0]}"", ""{_excludes[1]}"" ], ""exclude_folders"": [ ""{_excludeFolders[0]}"", ""{_excludeFolders[1]}"" ] }}"; Assert.Throws <ArgumentNullException>(() => CopySettings.LoadJson(json)); }
public void Null_Excludes_Allowed() { var json = $@" {{ ""destination"": ""{_destination}"", ""pattern"": ""{_pattern}"", ""exclude_folders"": [ ""{_excludeFolders[0]}"", ""{_excludeFolders[1]}"" ] }}"; var settings = CopySettings.LoadJson(json); Assert.Equal(_destination, settings.Destination); Assert.Equal(_pattern, settings.Pattern); Assert.Equal(Array.Empty <string>(), settings.Excludes); Assert.Equal(_excludeFolders, settings.ExcludeFolders); }
public static void CopyDirectoryRecursively(string sourceDirName, string destDirName) { CopySettings settings = new CopySettings() { IsMovingFiles = false, CopySubFolders = true, ContainsSearchForFiles = false }; try { CopyOrMoveDirectoryRecursively(sourceDirName, destDirName, settings); } catch (Exception e) { Sys.Message(new WMessage("failed to copy directory", WMessageLogLevel.LogOnly, e)); } }
internal static void CopyDirectoryRecursively(string sourceDirName, string destDirName) { CopySettings settings = new CopySettings() { IsMovingFiles = false, CopySubFolders = true, ContainsSearchForFiles = false }; try { CopyOrMoveDirectoryRecursively(sourceDirName, destDirName, settings); } catch (Exception e) { Logger.Error(e); } }
internal static void CopyDirectoryRecursively(string sourceDirName, string destDirName, IProgress <double> progress = null) { CopySettings settings = new CopySettings() { IsMovingFiles = false, CopySubFolders = true, ContainsSearchForFiles = false }; try { int count = 0, totalCount = 0; CopyOrMoveDirectoryRecursively(sourceDirName, destDirName, settings, fileCount: ref totalCount, currentCount: ref count, copiedFiles: null, progress: progress); } catch (Exception e) { Logger.Error(e); } }
private void SectionButtons(CopySettings OnCopySettings, PasteSettings OnPasteSettings) { GUILayout.Space(4); EditorGUILayout.BeginHorizontal(); { GUILayout.FlexibleSpace(); if (GUILayout.Button("Copy Settings", GUILayout.Height(24))) { OnCopySettings(); } GUILayout.Space(12); if (GUILayout.Button("Paste Settings", GUILayout.Height(24))) { OnPasteSettings(); } GUILayout.FlexibleSpace(); } EditorGUILayout.EndHorizontal(); }
public void TypeConverterIsUsed() { var obj1 = new DataObject1 { Hello = "Hello", Value1 = TestContext.CurrentContext.Random.GetString(50), Value2 = TestContext.CurrentContext.Random.GetString(50) }; var obj2 = new DataObject4(); var settings = new CopySettings(); settings.TypeConverters.Add(new StringToLengthConverter()); ReflectionUtilities.CopyProperties(obj1, obj2, settings); Assert.AreEqual(obj1.Hello.Length, obj2.Hello); Assert.AreEqual(obj1.Value1.Length, obj2.Value1); Assert.AreEqual(obj1.Value1.Length, obj2.Value2); }
public void PropertyMapping() { var obj1 = new DataObject1 { Hello = "Hello", Value1 = TestContext.CurrentContext.Random.GetString(50), Value2 = TestContext.CurrentContext.Random.GetString(50) }; var obj2 = new DataObject2(); var settings = new CopySettings(); settings.PropertyMapping.Add(nameof(DataObject1.Value1), nameof(DataObject2.Value2)); settings.PropertyMapping.Add(nameof(DataObject1.Value2), nameof(DataObject2.Value1)); ReflectionUtilities.CopyProperties(obj1, obj2, settings); Assert.AreEqual(obj1.Hello, obj2.Hello); Assert.AreEqual(obj1.Value2, obj2.Value1); Assert.AreEqual(obj1.Value1, obj2.Value2); }
public void Null_Pattern_Allowed() { var json = $@" {{ ""destination"": ""{_destination}"", ""excludes"": [ ""{_excludes[0]}"", ""{_excludes[1]}"" ], ""exclude_folders"": [ ""{_excludeFolders[0]}"", ""{_excludeFolders[1]}"" ] }}"; var settings = CopySettings.LoadJson(json); Assert.Equal(_destination, settings.Destination); Assert.Equal("*", settings.Pattern); Assert.Equal(_excludes, settings.Excludes); Assert.Equal(_excludeFolders, settings.ExcludeFolders); }
public void IgnoredProperties() { var obj1 = new DataObject { Hello = "Hello", Value1 = TestContext.CurrentContext.Random.GetString(50), Value2 = TestContext.CurrentContext.Random.GetString(50) }; var obj2 = new DataObject(); var settings = new CopySettings(); settings.IgnoredPropertyNames.Add(nameof(obj1.Value2)); ReflectionUtilities.CopyProperties(obj1, obj2, settings); Assert.AreEqual(obj1.Hello, obj2.Hello); Assert.AreEqual(obj1.Value1, obj2.Value1); Assert.AreEqual(default(string), obj2.Value2); }
public void FullPath_Destination_Allow() { var json = $@" {{ ""destination"": ""{_destination}"", ""pattern"": ""{_pattern}"", ""excludes"": [ ""{_excludes[0]}"", ""{_excludes[1]}"" ], ""exclude_folders"": [ ""{_excludeFolders[0]}"", ""{_excludeFolders[1]}"" ] }}"; var settings = CopySettings.LoadJson(json); Assert.Equal(CopySettings.SafeJsonStringReplace(_destination), settings.Destination); Assert.Equal("*", settings.Pattern); Assert.Equal(_excludes, settings.Excludes); Assert.Equal(_excludeFolders, settings.ExcludeFolders); }
public (bool succes, string error) Copy(CopySettings copySettings) { if (copySettings == null) { //log return(false, InputValidatinoError); } if (string.IsNullOrWhiteSpace(copySettings.Source) || string.IsNullOrWhiteSpace(copySettings.Target) || !Enum.IsDefined(typeof(CopySettings), copySettings.Item)) { //log return(false, InputValidatinoError); } try { switch (copySettings.Item) { case CopyItem.FILE: return(CopyOnlyFile(copySettings.Source, copySettings.Target)); case CopyItem.FOLDER: return(CopyDirectory(copySettings.Source, copySettings.Target)); default: throw new NotImplementedException(); } } catch (Exception ex) { //log Console.WriteLine(ex.Message); return(false, UnhandledError); } }
private static void CopyOrMoveDirectoryRecursively(string sourceDirName, string destDirName, CopySettings settings, List <string> copiedFiles = null) { if (copiedFiles == null) { copiedFiles = new List <string>(); } if (settings.ExcludeFiles == null) { settings.ExcludeFiles = new List <string>(); } if (settings.ExcludeFolders == null) { settings.ExcludeFolders = new List <string>(); } // reference: https://docs.microsoft.com/en-us/dotnet/standard/io/how-to-copy-directories // Get the subdirectories for the specified directory. DirectoryInfo dir = new DirectoryInfo(sourceDirName); if (!dir.Exists) { throw new DirectoryNotFoundException( "Source directory does not exist or could not be found: " + sourceDirName); } // Get the files in the directory and copy them to the new location. FileInfo[] files = dir.GetFiles(); foreach (FileInfo file in files) { if (settings.ExcludeFile(file)) { continue; // skip file as it is excluded } // If the destination directory doesn't exist, create it. if (!Directory.Exists(destDirName)) { Directory.CreateDirectory(destDirName); } string temppath = Path.Combine(destDirName, file.Name); if (settings.IsMovingFiles) { if (File.Exists(temppath)) { File.Delete(temppath); // delete existing file before moving new file } file.MoveTo(temppath); } else { file.CopyTo(temppath, true); } copiedFiles.Add(temppath); } // If copying subdirectories, copy them and their contents to new location. if (settings.CopySubFolders) { DirectoryInfo[] dirs = dir.GetDirectories(); foreach (DirectoryInfo subdir in dirs) { if (settings.ExcludeFolders.Contains(subdir.Name)) { continue; // skip folder as it is excluded } string tempPath = Path.Combine(destDirName, subdir.Name); CopyOrMoveDirectoryRecursively(subdir.FullName, tempPath, settings, copiedFiles); } } }
/*----------Functions----------*/ //PRIVATE /// <summary> /// Recurse into the original object to copy the contained information /// </summary> /// <param name="original">The original object that is to be copied</param> /// <param name="settings">The copy settings that define how this operation is handled</param> /// <returns>Returns a copy of the original object for use</returns> private static object InternalCopy(object original, CopySettings settings) { // If the original is null, don't bother if (original == null) { return(null); } // Get the type of the object to copied Type typeValue = original.GetType(); // Check if there is a processor that needs to handle this SpecialisedCopyProcessor copyProcessor = settings.SpecialisedProcessors.FindProcessor(typeValue, original); if (copyProcessor != null) { // Get the copy that will be used for this object object specialCopy = copyProcessor.ProcessCopy(original, typeValue); // Cache the value if it isn't a primitive if (!IsPrimitive(typeValue)) { settings.ObjectCache[original] = specialCopy; } return(specialCopy); } // If there is a cached version of the copy, use that if (settings.ObjectCache.ContainsKey(original)) { return(settings.ObjectCache[original]); } // If the object is a primitive type, can just use the original if (IsPrimitive(typeValue)) { return(original); } // If the original is a delegate, don't clone those if (typeof(Delegate).IsAssignableFrom(typeValue)) { return(null); } // Array doesn't like the memberwise clone, handle specifically object objectCopy; if (!typeValue.IsArray) { objectCopy = CLONE_METHOD.Invoke(original, null); } else { // Get the original array to be processed Array originalArray = (Array)original; // Create a shallow copy of the array Array copyArray = (Array)originalArray.Clone(); objectCopy = copyArray; // Get the underlying type of the array that is being copied Type arrayType = typeValue.GetElementType(); // Check if there is a specialised processor for this type copyProcessor = settings.SpecialisedProcessors.FindProcessor(arrayType, null); // If there is a specialised copy processor for the array type or the type isn't a primitive, handle the copying if (copyProcessor != null || !IsPrimitive(arrayType)) { copyArray.ForEach((array, indices) => array.SetValue(InternalCopy(copyArray.GetValue(indices), settings), indices) ); } } // Add this copied object to the cache collection settings.ObjectCache[original] = objectCopy; // Copy the values within the copied value CopyFields(original, settings, objectCopy, typeValue); RecursiveCopyBaseTypePrivateFields(original, settings, objectCopy, typeValue); return(objectCopy); }
/// <summary> /// Create a copy of the original object using a deep member clone by default /// </summary> /// <typeparam name="T">The type of the object that is to be copied</typeparam> /// <param name="original">The original object that is to be copied</param> /// <param name="settings">[Optional] The copy settings object that will be used to drive the copy operation</param> /// <returns>Returns a copy of the original object for use</returns> public static T Copy <T>(this T original, CopySettings settings = null) { return((T)Copy((object)original, settings)); }