예제 #1
0
        public static void CopyTo(string path, Folder folder, CopyResult copyResult)
        {
            System.IO.Directory.CreateDirectory(path);
            foreach (var file in folder.Files)
            {
                if (!System.IO.File.Exists(System.IO.Path.Combine(path, (file as File).Title)))
                {
                    copyResult.NewFiles++;
                }
                else if (System.IO.File.GetLastWriteTime((file as File).Path) != System.IO.File.GetLastWriteTime(System.IO.Path.Combine(path, (file as File).Title)))
                {
                    copyResult.ReplacedFiles++;
                }
                else
                {
                    copyResult.NotCopiedFiles++;
                }

                // Copy anyway, in case of rare equal time or whatnot..
                FileService.CopyFile(path, (file as File).Path);
            }

            foreach (var nextFolder in folder.Folders)
            {
                CopyTo(FileService.CreateFolder(path, nextFolder.Title), nextFolder, copyResult);
            }
        }
예제 #2
0
        public CopyResult Copy(int id, int[] selectedActionsIds)
        {
            var result = new CopyResult();
            var action = ReadForModify(id);

            action.Id = 0;
            if (action.Action != null)
            {
                action.Action.Id = 0;
            }

            if (action == null)
            {
                throw new Exception(string.Format(CustomActionStrings.ActionNotFoundByCode, id));
            }
            if (!action.IsUpdatable || !action.IsAccessible(ActionTypeCode.Read))
            {
                result.Message = MessageResult.Error(CustomActionStrings.CannotCopyBecauseOfSecurity);
            }

            if (result.Message == null)
            {
                action = Normalize(action, selectedActionsIds);
                action = CustomActionRepository.Copy(action);
            }

            return(result);
        }
예제 #3
0
        public void UdiskCopyTest()
        {
            CopyResult copyResult = 0;

            //string srcDir = @"C:\Users\BM021671\Documents\ProjectFiles\Cell4\SourceFiles\";
            string srcDir = @"C:\a";

            copyResult = CopyFilesToUDisk(srcDir, Common.copyfilelist);
            Debug.WriteLine("udisktest copyresult " + copyResult.ToString());
            if (copyResult == CopyResult.GOOD)
            {
                copyTcp.Send("Copy Test Complete");
            }
            else if (copyResult == CopyResult.COPYFAILED)
            {
                copyTcp.Send("Copy Test Failed");
            }
            else if (copyResult == CopyResult.MISSTORAGE)
            {
                copyTcp.Send("Storage Error");
            }
            else
            {
                copyTcp.Send("Unknown Result");
            }
        }
예제 #4
0
        private async Task ProcessCopyResult(CopyResult copyResult)
        {
            switch (copyResult)
            {
            case CopyResult.Success:
                logger.Log("AlreadyIso.CopySuccess");
                await ShowSimpleContentDialog("Copy completed!");

                break;

            case CopyResult.IoException:
                logger.Log("AlreadyIso.CopyIOException");
                await ShowSimpleContentDialog("Exception while accessing files. Copy aborted.");

                break;

            case CopyResult.CopyCanceled:
                logger.Log("AlreadyIso.CopyCanceled");
                await ShowSimpleContentDialog("Copy canceled by user.");

                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(copyResult), copyResult, null);
            }

            if (copyResult == CopyResult.Success)
            {
                await AskForReview();

                ClearIsoFile();
                ClearMdfFile();
            }
        }
예제 #5
0
        public static void StartWithCopy(Target target, Config config)
        {
            var result = new CopyResult();

            CopyService.CopyTo(FileService.GetDirectory(target.Path), config.Folders, result);
            Start(target);
            EventService.Publish(Const.MessageEvent, result);
        }
예제 #6
0
 public uint CopyIntoItemsLocal(string SourceUrl, string[] DestinationUrls, out CopyResult[] Results)
 {
     object[] results1 = this.Invoke("CopyIntoItemsLocal", new object[] {
             SourceUrl,
             DestinationUrls});
     Results = ((CopyResult[])(results1[1]));
     return ((uint)(results1[0]));
 }
예제 #7
0
 public static CopyResult ToCopyResult(this CopyRequest.Result data)
 {
     var res = new CopyResult
     {
         IsSuccess = data.status == 200,
         NewName = data.body
     };
     return res;
 }
예제 #8
0
        public static CopyResult ToCopyResult(this MoveRequest.Result data, string newName)
        {
            var res = new CopyResult
            {
                IsSuccess = true,
                NewName   = newName
            };

            return(res);
        }
예제 #9
0
        public static CopyResult ToCopyResult(this CommonOperationResult <string> data)
        {
            var res = new CopyResult
            {
                IsSuccess = data.Status == 200,
                NewName   = data.Body
            };

            return(res);
        }
예제 #10
0
        public static ItemOperation ToItemOperation(this CopyResult data)
        {
            var res = new ItemOperation
            {
                DateTime = data.DateTime,
                Path     = data.OldFullPath
            };

            return(res);
        }
예제 #11
0
        public static CopyResult ToMoveResult(this YadResponceModel <YadMoveRequestData, YadMoveRequestParams> data)
        {
            var res = new CopyResult
            {
                IsSuccess = true,
                NewName   = data.Params.Dst.Remove(0, "/disk".Length)
            };

            return(res);
        }
예제 #12
0
        public static CopyResult ToMoveResult(this YadResponseModel <YadMoveRequestData, YadMoveRequestParams> data)
        {
            var res = new CopyResult
            {
                IsSuccess   = null == data.Data.Error,
                NewName     = data.Params.Dst.Remove(0, "/disk".Length),
                OldFullPath = data.Params.Src.Remove(0, "/disk".Length),
                DateTime    = DateTime.Now
            };

            return(res);
        }
예제 #13
0
        /// <summary>
        /// get the color for the copy result
        /// </summary>
        /// <param name="resultOfCopy"></param>
        /// <returns></returns>
        public static System.Drawing.Color CopyResultColor(CopyResult resultOfCopy)
        {
            switch (resultOfCopy)
            {
            case CopyResult.copygood:
                return(System.Drawing.Color.Green);

            case CopyResult.samedate:
            case CopyResult.targetexists:
                return(System.Drawing.Color.Blue);

            case CopyResult.copyfail:
            case CopyResult.sourcedoesnotexists:
            case CopyResult.targetisnewer:
                return(System.Drawing.Color.Red);

            default:
                return(System.Drawing.Color.Black);
            }
        }
예제 #14
0
        private void SyncAllBtn_Click(object sender, EventArgs e)
        {
            if (SyncList.Items.Count == 0)
            {
                LogLine("Nothing to sync.");
                return;
            }
            int successes = 0;
            int upToDates = 0;
            int failures  = 0;

            string statusMsg;
            string failureMsgs = "";

            foreach (FileSync fs in SyncList.Items)
            {
                CopyResult copyResult = CopyFile(fs, out statusMsg);

                switch (copyResult)
                {
                case CopyResult.Success:
                    successes++;
                    break;

                case CopyResult.UpToDate:
                    upToDates++;
                    break;

                case CopyResult.Fail:
                    failures++;
                    failureMsgs += statusMsg + "\r\n";
                    break;
                }
            }

            LogLine($"Sync Finished: {successes} copied. {upToDates} up-to-date. {failures} failed.");
            if (failures != 0)
            {
                LogLine("Failure messages: \r\n" + failureMsgs);
            }
        }
예제 #15
0
        /// <summary>
        /// get the string value for the copy result
        /// </summary>
        /// <param name="resultOfCopy"></param>
        /// <returns></returns>
        public static string CopyResultToString(CopyResult resultOfCopy)
        {
            switch (resultOfCopy)
            {
            case CopyResult.copyfail:
                return("Copy failed");

            case CopyResult.sourcedoesnotexists:
                return("Source file does not exist");

            case CopyResult.samedate:
                return("Same date for target and source files");

            case CopyResult.targetisnewer:
                return("Target file is newer than source file");

            case CopyResult.targetexists:
                return("Target already exists");

            default:
                return("Copy successful");
            }
        }
예제 #16
0
        public CopyResult Copy(int id)
        {
            var result = new CopyResult();
            var group  = UserGroupRepository.GetPropertiesById(id);

            if (group == null)
            {
                throw new ApplicationException(string.Format(UserGroupStrings.GroupNotFound, id));
            }

            group.MutateName();
            var newId = UserGroupRepository.CopyGroup(group, QPContext.CurrentUserId);

            if (newId == 0)
            {
                result.Message = MessageResult.Error(UserGroupStrings.GroupHasNotBeenCreated);
            }
            else
            {
                result.Id = newId;
            }
            return(result);
        }
예제 #17
0
        public CopyResult Copy(int id)
        {
            var result = new CopyResult();
            var user   = UserRepository.GetById(id, true);

            if (user == null)
            {
                throw new ApplicationException(string.Format(UserStrings.UserNotFound, id));
            }

            user.MutateLogin();
            var newId = UserRepository.CopyUser(user, QPContext.CurrentUserId);

            if (newId == 0)
            {
                result.Message = MessageResult.Error(UserStrings.UserHasNotBeenCreated);
            }
            else
            {
                result.Id = newId;
            }

            return(result);
        }
예제 #18
0
        public CopyResult Copy(int id)
        {
            var result = new CopyResult();
            var page   = PageRepository.GetPagePropertiesById(id);

            if (page == null)
            {
                throw new ApplicationException(string.Format(TemplateStrings.PageNotFound, id));
            }

            page.MutatePage();
            ManagePageFolders(page, FolderManagingType.CreateFolder);
            var newId = PageRepository.CopyPage(page, QPContext.CurrentUserId);

            if (newId == 0)
            {
                result.Message = MessageResult.Error(TemplateStrings.PageNotCreated);
            }
            else
            {
                result.Id = newId;
            }
            return(result);
        }
예제 #19
0
 /// <remarks/>
 public uint EndCopyIntoItemsLocal(System.IAsyncResult asyncResult, out CopyResult[] Results)
 {
     object[] results1 = this.EndInvoke(asyncResult);
     Results = ((CopyResult[])(results1[1]));
     return ((uint)(results1[0]));
 }
예제 #20
0
        private async Task ProcessAlreadyIso()
        {
            logger.Log("Conversion.InputAlreadyISO");
            ContentDialog alreadyIsoChoiceDialog = new ContentDialog
            {
                Title             = "Input file is already in ISO format",
                Content           = "You can change the extension directly to .iso, or copy its content to the new file",
                PrimaryButtonText = "Copy it as a new .iso file",
            };

            //Move option is available only on 1703 and later, beacause of number of buttons

            bool isCloseButtonTextSupported = ApiInformation.IsPropertyPresent("Windows.UI.Xaml.Controls.ContentDialog",
                                                                               nameof(ContentDialog.CloseButtonText));

            if (isCloseButtonTextSupported)
            {
                alreadyIsoChoiceDialog.SecondaryButtonText = "Just rename the .mdf file to .iso";
                alreadyIsoChoiceDialog.CloseButtonText     = "Cancel";
            }
            else
            {
                alreadyIsoChoiceDialog.SecondaryButtonText = "Cancel";
            }

            ContentDialogResult choiceDialogResult = await alreadyIsoChoiceDialog.ShowAsync();

            switch (choiceDialogResult)
            {
            case ContentDialogResult.Primary:
                CopyResult copyResult = await Task.Run(() => Mdf2IsoConverter.CopyAsync(
                                                           MdfFile,
                                                           IsoFile,
                                                           progress,
                                                           LogViewer.LogWriter,
                                                           token: tokenSource.Token
                                                           ));
                await ProcessCopyResult(copyResult);

                break;

            case ContentDialogResult.Secondary:
                if (isCloseButtonTextSupported)
                {
                    bool renameResult = await ChangeExtension();
                    await ProcessRenameResult(renameResult);
                }
                else
                {
                    logger.Log("AlreadyIso.DoNothing");
                }
                break;

            case ContentDialogResult.None:
                logger.Log("AlreadyIso.DoNothing");
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
예제 #21
0
 public static void CopyTo(string path, ObservableCollection <Folder> folders, CopyResult copyResult)
 {
     try
     {
         foreach (var folder in folders)
         {
             if (folder.IsSelected)
             {
                 CopyTo(path, folder, copyResult);
             }
         }
     }
     catch (Exception e)
     {
         EventService.Publish(Const.MessageEvent, e.Message);
     }
 }
예제 #22
0
        int NativeInterfaces.IFileDialogEvents.OnFileOk(NativeInterfaces.IFileDialog pfd)
        {
            int hr = NativeConstants.S_OK;

            NativeInterfaces.IShellItemArray results = null;
            FileOpenDialog.GetResults(out results);

            uint count = 0;

            results.GetCount(out count);

            List <NativeInterfaces.IShellItem> items         = new List <NativeInterfaces.IShellItem>();
            List <NativeInterfaces.IShellItem> needLocalCopy = new List <NativeInterfaces.IShellItem>();
            List <NativeInterfaces.IShellItem> cannotCopy    = new List <NativeInterfaces.IShellItem>();
            List <string> localPathNames = new List <string>();

            for (uint i = 0; i < count; ++i)
            {
                NativeInterfaces.IShellItem item = null;
                results.GetItemAt(i, out item);
                items.Add(item);
            }

            foreach (NativeInterfaces.IShellItem item in items)
            {
                // If it's a file system object, nothing special needs to be done.
                NativeConstants.SFGAO sfgaoAttribs;
                item.GetAttributes((NativeConstants.SFGAO) 0xffffffff, out sfgaoAttribs);

                if ((sfgaoAttribs & NativeConstants.SFGAO.SFGAO_FILESYSTEM) == NativeConstants.SFGAO.SFGAO_FILESYSTEM)
                {
                    string pathName = null;
                    item.GetDisplayName(NativeConstants.SIGDN.SIGDN_FILESYSPATH, out pathName);

                    localPathNames.Add(pathName);
                }
                else if ((sfgaoAttribs & NativeConstants.SFGAO.SFGAO_STREAM) == NativeConstants.SFGAO.SFGAO_STREAM)
                {
                    needLocalCopy.Add(item);
                }
                else
                {
                    cannotCopy.Add(item);
                }
            }

            Marshal.ReleaseComObject(results);
            results = null;

            if (needLocalCopy.Count > 0)
            {
                IntPtr hwnd = IntPtr.Zero;
                NativeInterfaces.IOleWindow oleWindow = (NativeInterfaces.IOleWindow)pfd;
                oleWindow.GetWindow(out hwnd);
                Win32Window win32Window = new Win32Window(hwnd, oleWindow);

                IFileTransferProgressEvents progressEvents = this.FileDialogUICallbacks.CreateFileTransferProgressEvents();

                ThreadStart copyThreadProc =
                    delegate()
                {
                    try
                    {
                        progressEvents.SetItemCount(needLocalCopy.Count);

                        for (int i = 0; i < needLocalCopy.Count; ++i)
                        {
                            NativeInterfaces.IShellItem item = needLocalCopy[i];

                            string pathName = null;

                            progressEvents.SetItemOrdinal(i);
                            CopyResult result = CreateLocalCopy(item, progressEvents, out pathName);

                            if (result == CopyResult.Success)
                            {
                                localPathNames.Add(pathName);
                            }
                            else if (result == CopyResult.Skipped)
                            {
                                // do nothing
                            }
                            else if (result == CopyResult.CancelOperation)
                            {
                                hr = NativeConstants.S_FALSE;
                                break;
                            }
                            else
                            {
                                throw new InvalidEnumArgumentException();
                            }
                        }
                    }

                    finally
                    {
                        OperationResult result;

                        if (hr == NativeConstants.S_OK)
                        {
                            result = OperationResult.Finished;
                        }
                        else
                        {
                            result = OperationResult.Canceled;
                        }

                        progressEvents.EndOperation(result);
                    }
                };

                Thread copyThread = new Thread(copyThreadProc);
                copyThread.SetApartmentState(ApartmentState.STA);

                EventHandler onUIShown =
                    delegate(object sender, EventArgs e)
                {
                    copyThread.Start();
                };

                this.cancelSink = new CancelableTearOff();
                progressEvents.BeginOperation(win32Window, onUIShown, cancelSink);
                this.cancelSink = null;
                copyThread.Join();

                Marshal.ReleaseComObject(oleWindow);
                oleWindow = null;
            }

            this.FileNames = localPathNames.ToArray();

            // If they selected a bunch of files, and then they all errored or something, then don't proceed.
            if (this.FileNames.Length == 0)
            {
                hr = NativeConstants.S_FALSE;
            }

            foreach (NativeInterfaces.IShellItem item in items)
            {
                Marshal.ReleaseComObject(item);
            }

            items.Clear();
            items = null;

            GC.KeepAlive(pfd);
            return(hr);
        }
 /// <summary>
 /// Initializes a new instance of the CopyIntoItemsResponse class.
 /// </summary>
 /// <param name="copyIntoItemsResult">A parameter represents the result status of "CopyIntoItems" operation.</param>
 /// <param name="results">A parameter represents the copy results collection of the copy actions performed in "CopyIntoItems" operation.</param>
 public CopyIntoItemsResponse(uint copyIntoItemsResult, CopyResult[] results)
 {
     this.copyIntoItemsResultValue = copyIntoItemsResult;
     this.resultsCollection = results;
 }
예제 #24
0
        public static CopyResult Copy(Article article, bool?boundToExternal, bool disableNotifications, Guid?guidForSubstitution)
        {
            var result = new CopyResult();

            Ensure.NotNull(article, string.Format(ArticleStrings.ArticleNotFound, article.Id));

            if (article.IsAggregated)
            {
                return(new CopyResult {
                    Message = MessageResult.Error(ArticleStrings.OperationIsNotAllowedForAggregated)
                });
            }

            if (!article.IsArticleChangingActionsAllowed(boundToExternal))
            {
                return(new CopyResult {
                    Message = MessageResult.Error(ContentStrings.ArticleChangingIsProhibited)
                });
            }

            article.LoadFieldValues();
            if (!article.Content.IsUpdatable || !article.IsAccessible(ActionTypeCode.Read))
            {
                return(new CopyResult {
                    Message = MessageResult.Error(ArticleStrings.CannotCopyBecauseOfSecurity)
                });
            }

            if (!article.IsUpdatableWithWorkflow)
            {
                return(new CopyResult {
                    Message = MessageResult.Error(ArticleStrings.CannotAddBecauseOfWorkflow)
                });
            }

            if (!article.IsUpdatableWithRelationSecurity)
            {
                return(new CopyResult {
                    Message = MessageResult.Error(ArticleStrings.CannotAddBecauseOfRelationSecurity)
                });
            }

            article.UniqueId = guidForSubstitution ?? Guid.NewGuid();
            result.UniqueId  = article.UniqueId.Value;

            var previousAggregatedArticles = article.AggregatedArticles;

            article.ReplaceAllUrlsToPlaceHolders();

            try
            {
                article   = ArticleRepository.Copy(article);
                result.Id = article.Id;
                article.CopyAggregates(previousAggregatedArticles);

                var repo = new NotificationPushRepository();
                repo.PrepareNotifications(article, new[] { NotificationCode.Create }, disableNotifications);
                repo.SendNotifications();
            }
            catch (UnsupportedConstraintException)
            {
                result.Message = MessageResult.Error(ArticleStrings.UnsupportedConstraint);
            }

            return(result);
        }
예제 #25
0
        public static CopyResult CopyFilesToUDisk(string srcDir, List <string> filelist)
        {
            CopyResult result     = 0;
            bool       uexist     = false;
            bool       ustorageok = false;

            List <string> Udisks = new List <string>();

            //find all removable disks
            DriveInfo[] drvInfos = DriveInfo.GetDrives();
            foreach (DriveInfo drv in drvInfos)
            {
                Debug.WriteLine(drv.ToString());
                if (drv.DriveType == DriveType.Removable)
                {
                    uexist = true;
                    Messages.WriteLine("U盘容量:" + drv.TotalSize);
                    if (7000000000 < drv.TotalSize && drv.TotalSize < 9000000000)
                    {
                        Udisks.Add(drv.ToString());
                        ustorageok = true;
                        break;
                        // Debug.WriteLine(i.ToString());
                    }
                }
            }

            //copy file

            bool copyComplete = false;

            foreach (string u in Udisks)
            {
                Messages.WriteLine(string.Format("文件复制:{0} 到 {1}", srcDir, u));
                if (FileSys.CopyFiles(srcDir, u, filelist))
                {
                    copyComplete = true;
                    Messages.WriteLine("文件复制成功");
                }
                Messages.WriteLine("弹出U盘");
                Udisk.Reject(u);
                break;//copy file to the first udisk then break;
            }

            if (uexist && ustorageok && copyComplete)
            {
                result = CopyResult.GOOD;
            }
            else if (!uexist || !ustorageok)
            {
                result = CopyResult.MISSTORAGE;
            }
            else if (!copyComplete)
            {
                result = CopyResult.COPYFAILED;
            }
            else
            {
                result = CopyResult.UNKNOWN;
            }

            Messages.WriteLine("文件复制结果:" + result.ToString());

            return(result);
        }
예제 #26
0
 public uint CopyIntoItems(string SourceUrl, string[] DestinationUrls, [System.Xml.Serialization.XmlArrayItemAttribute(IsNullable = false)] FieldInformation[] Fields, [System.Xml.Serialization.XmlElementAttribute(DataType = "base64Binary")] byte[] Stream, out CopyResult[] Results)
 {
     object[] results1 = this.Invoke("CopyIntoItems", new object[] {
             SourceUrl,
             DestinationUrls,
             Fields,
             Stream});
     Results = ((CopyResult[])(results1[1]));
     return ((uint)(results1[0]));
 }
예제 #27
0
        static void Main(string[] args)
        {
            Console.WriteLine("Generating format...");

            #region Params

            var p_copy = new CopyParam
            {
                CurrentFolderPath    = "/",
                SourceDirectory      = "/",
                DestinationDirectory = "/",
                Overwrite            = false,
                Targets = new System.Collections.Generic.List <BaseActionTarget>
                {
                    new BaseActionTarget
                    {
                        IsFile = true,
                        Name   = "sample.txt"
                    }
                }
            };

            var p_move = new MoveParam
            {
                CurrentFolderPath    = "/",
                SourceDirectory      = "/",
                DestinationDirectory = "/",
                Overwrite            = false,
                Targets = new System.Collections.Generic.List <BaseActionTarget>
                {
                    new BaseActionTarget
                    {
                        IsFile = true,
                        Name   = "sample.txt"
                    }
                }
            };

            var p_createFolder = new CreateFolderParam
            {
                CurrentFolderPath = "/",
                Name = "new folder name"
            };

            var p_delete = new DeleteParam
            {
                CurrentFolderPath = "/",
                Targets           = new System.Collections.Generic.List <string>
                {
                    "itemNameToDelete"
                }
            };

            var p_folderStruct = new FolderStructParam
            {
                CurrentFolderPath = "/",
                FileExtensions    = new string[] { ".txt" }
            };

            var p_rename = new RenameParam
            {
                CurrentFolderPath = "/",
                Targets           = new System.Collections.Generic.List <RenameActionTarget>
                {
                    new RenameActionTarget
                    {
                        IsFile  = true,
                        Name    = "new name",
                        OldName = "old name"
                    }
                }
            };

            #endregion

            #region Results

            var r_copy = new CopyResult
            {
                Errors = new System.Collections.Generic.List <string>
                {
                    "Error message."
                }
            };

            var r_move = new MoveResult
            {
                Errors = new System.Collections.Generic.List <string>
                {
                    "Error message."
                }
            };

            var r_createFolder = new CreateFolderResult
            {
                Errors = new System.Collections.Generic.List <string>
                {
                    "Error message."
                }
            };

            var r_delete = new DeleteResult
            {
                Affected = 0,
                Errors   = new System.Collections.Generic.List <string>
                {
                    "Error message."
                }
            };

            var r_folderStruct = new FolderStructResult
            {
                Errors = new System.Collections.Generic.List <string>
                {
                    "Error message."
                },
                Files = new System.Collections.Generic.List <FileInfoProxy>
                {
                    new FileInfoProxy
                    {
                        Name       = "file.name",
                        Properties = new System.Collections.Generic.Dictionary <string, string>
                        {
                            { "Property", "Value" }
                        }
                    }
                },
                Folders = new System.Collections.Generic.List <FileInfoProxy>
                {
                    new FileInfoProxy
                    {
                        Name       = "folder name",
                        Properties = new System.Collections.Generic.Dictionary <string, string>
                        {
                            { "Property", "Value" }
                        }
                    }
                }
            };

            var r_rename = new RenameResult
            {
                Affected = 0,
                Errors   = new System.Collections.Generic.List <string>
                {
                    "Error message."
                },
                RenamedObjects = new System.Collections.Generic.List <RenameActionTarget>()
                {
                    new RenameActionTarget
                    {
                        IsFile  = true,
                        Name    = "new name",
                        OldName = "old name"
                    }
                }
            };

            #endregion

            SaveFormat("p_copy.json", p_copy);
            SaveFormat("p_move.json", p_move);
            SaveFormat("p_createFolder.json", p_createFolder);
            SaveFormat("p_delete.json", p_delete);
            SaveFormat("p_folderStruct.json", p_folderStruct);
            SaveFormat("p_rename.json", p_rename);

            SaveFormat("r_copy.json", r_copy);
            SaveFormat("r_move.json", r_move);
            SaveFormat("r_createFolder.json", r_createFolder);
            SaveFormat("r_delete.json", r_delete);
            SaveFormat("r_folderStruct.json", r_folderStruct);
            SaveFormat("r_rename.json", r_rename);
        }
예제 #28
0
        // todo: refactor

        public CopyResult Copy(List <FileInfo> files)
        {
            var result = new CopyResult();

            foreach (var file in files)
            {
                var crf = new CopyResultFile
                {
                    FileInfo = FileInfo.Clone(file),
                    State    = CopyResultFileState.Incomplete
                };
                result.CopyResultFiles.Add(crf);
            }

            foreach (var file in result.CopyResultFiles)
            {
                CopyResultFileState?successState = null;

                string content = null;
                if (file.FileInfo.Binary)
                {
                    successState = CopyResultFileState.SuccessClone;
                }
                else
                {
                    try
                    {
                        content = File.ReadAllText(file.FileInfo.FromFile);
                    }
                    catch
                    {
                        file.State = CopyResultFileState.FailedRead;
                        continue;
                    }


                    switch (file.FileInfo.Action)
                    {
                    case Action.Transform:

                        foreach (var trans in file.FileInfo.Transforms)
                        {
                            if (trans.AcceptAllFiles || trans.FileExtensions.Contains(file.FileInfo.Extension))
                            {
                                content = trans.Transformation.Transform(content);
                            }
                        }
                        successState = CopyResultFileState.SuccessNoSolution;
                        break;

                    case Action.Copy:
                        successState = CopyResultFileState.SuccessClone;
                        break;

                    default:
                        file.State = CopyResultFileState.UnknownCopyStyle;
                        continue;
                    }
                }
                try
                {
                    var directory = GetDirectory(file.FileInfo.ToFile);
                    CreateDirectoryIfNotExist(directory);

                    if (file.FileInfo.Binary)
                    {
                        File.Copy(file.FileInfo.FromFile, file.FileInfo.ToFile, true);
                    }
                    else
                    {
                        File.WriteAllText(file.FileInfo.ToFile, content);
                    }
                }
                catch
                {
                    file.State = CopyResultFileState.FailedWrite;
                    continue;
                }

                file.State = (CopyResultFileState)successState;
            }
            return(result);
        }