Пример #1
0
        /// <summary>
        /// Sync All online directories of project
        /// </summary>
        /// <param name="project"></param>
        /// /// <param name="silentMode">true - without dialog boxes</param>
        private void StartSync(Project project, bool silentMode = false)
        {
            // if (List_Projects.SelectedItem == null) return;

            CONSTS.DisableButton(button1);
            // var selectedProj = Projects.First(x => x.Name == List_Projects.SelectedItem.ToString());
            SyncThread = new Thread(delegate()
            {
                try
                {
                    SetSyncStatus(true);
                    int newfiles     = 0;
                    int updatedfiles = 0;
                    int errorCopy    = 0;

                    var OnlineDirs = project.OnlineDirs.Where(x => x.PC_Name == pc_name || x.PC_Name == CONSTS.FlashDrive);    //.AllProjectDirs.Where(x => x.IsOnline);

                    if (OnlineDirs.Count() == 0)
                    {
                        SetSyncStatus(false); return;
                    }
                    if (OnlineDirs.Count() == 1)
                    {
                        foreach (var t in OnlineDirs.First().Info2())
                        {
                            tmr.Start("Вывод инфо директории");
                            CONSTS.AddNewLine(tblog, t);
                            tmr.Stop();
                        }
                        SetSyncStatus(false);
                        return;
                    }


                    if (OnlineDirs.Count() > 1)     //run SYNC
                    {
                        //DateTime t = DateTime.Now;
                        int filesCount     = 0;                  //count of files in dir
                        int cTotal         = 0;
                        List <Queue> queue = new List <Queue>(); //очередь файлов источника и назначений
                        Queue.Count        = 0;
                        //перебор всех Онлайн директорий
                        List <string> skippedFiles = new List <string>();   //relativ path!!!
                        foreach (var dir in OnlineDirs)
                        {
                            dir.ReadFiles();
                        }
                        foreach (var Dir in OnlineDirs)     //перебор все папок проекта
                        {
                            //каждый файл ищется в других папках проекта и добавляется в очередь
                            foreach (var dateFile in Dir.AllFiles())
                            {
                                //получаем относительный путь файла
                                string relatePath = GetRelationPath(dateFile.Key, Dir.Dir);
                                //проверялся ли такой файл раньше?
                                if (skippedFiles.Contains(relatePath))
                                {
                                    continue;                                        // ДА - пропускаем
                                }
                                //проверяем, нет ли такого файла уже в очереди
                                //поиск файла в очереди
                                if (queue.Any(x => x.SourceFile.EndsWith(relatePath)))
                                {
                                    continue;              //dataFile.Key - Full filePath
                                }
                                var newest    = dateFile;  //самый свежий файл
                                string SrcDir = Dir.Dir;
                                //создаем список файлов, которые нужно заменить файлом dateFile, файл назначения
                                // Dictionary<string, DateTime> otherFiles = new Dictionary<string, DateTime>();

                                List <Tuple <string, string, DateTime, bool> > otherFiles = new List <Tuple <string, string, DateTime, bool> >();
                                //item1 = Fullpath,
                                //item2 = Dir,
                                //item3 = DateTime lastWrite,
                                //item4 = IsNewfile
                                foreach (var otherDir in OnlineDirs)     //Поиск текущего файла dateFile в остальных директориях
                                {
                                    if (otherDir == Dir)
                                    {
                                        continue;                             //пропуск текущей директории
                                    }
                                    var file = otherDir.FindFile(relatePath); //поиск такого же файла
                                                                              //если такого файла в Директории нет
                                    if (String.IsNullOrEmpty(file.Key))       //создадим путь для копирования в эту директорию
                                    {
                                        //пара значений (Путь файла, Время последнего изменения)
                                        file = new KeyValuePair <string, DateTime>
                                                   (newest.Key.Replace(Dir.Dir, otherDir.Dir), newest.Value);
                                        otherFiles.Add(new Tuple <string, string, DateTime, bool>(file.Key, otherDir.Dir, file.Value, true));   //добавление в список назначения
                                        continue;
                                    }
                                    if (newest.Value > file.Value)
                                    {
                                        otherFiles.Add(new Tuple <string, string, DateTime, bool>(file.Key, otherDir.Dir, file.Value, false));   //добавление файла в список файлов
                                    }
                                    else if (newest.Value == file.Value)
                                    {
                                        continue;     //SKIP  SAME FILES, DONT COPY!!!
                                    }
                                    else
                                    //меняем переменную новейшего файла с текущим
                                    {
                                        if (!otherFiles.Any(x => x.Item1 == newest.Key))
                                        {
                                            otherFiles.Add(new Tuple <string, string, DateTime, bool>(newest.Key, Dir.Dir, newest.Value, false));
                                        }
                                        {
                                            newest = file;
                                            SrcDir = otherDir.Dir;
                                        }
                                    }
                                }
                                // tmr.Stop(1);
                                //нашли самый новый файл dateFile среди остальных директорий
                                //теперь добавляем в очередь
                                if (otherFiles.Count() != 0)
                                {
                                    foreach (var otherfile in otherFiles)
                                    {                                          //Добавление для каждого файла  назначения своей очереди
                                        queue.Add(new Queue(true,              //Active status
                                                            newest.Key,        //Full Source filepath
                                                            otherfile.Item1,   //full Targer filepath
                                                            SrcDir,            //Directory of source file
                                                            otherfile.Item2,   //directory of target file
                                                            newest.Value,      //last modification datetime Source File
                                                            otherfile.Item3,   //last modification datetime Target File
                                                            otherfile.Item4)); //is new file? or overwrited
                                    }
                                }

                                else
                                {
                                    skippedFiles.Add(GetRelationPath(newest.Key, Dir.Dir));      //если все файлы одинаковые как newest - пропускаем
                                }
                            }
                        }    //проверили все файлы и добавили их в очередь
                             //проверяем есть ли что копировать
                        if (queue.Count == 0)
                        {
                            if (!silentMode)
                            {
                                MessageBox.Show("Все папки одинаковые, нечего синхронизировать");
                            }
                            CONSTS.AddNewLine(tblog, project.Name + ": Нечего синхронизировать.");
                            SetSyncStatus(false);
                            return;
                        }


                        if (!silentMode)    // not silent
                        {
                            var msgBox = new MsgDialog(queue);
                            var dr     = msgBox.ShowDialog();
                            if (dr != DialogResult.OK)
                            {
                                SetSyncStatus(false); return;
                            }
                            else
                            {
                                queue = msgBox.ReturnedQueue;
                            }
                        }

                        CONSTS.AddNewLine(tblog, "--------------------------------------------");
                        cTotal     = queue.Count(); //count of SrcFiles
                        filesCount = 0;             //total copied DestFiles
                        int nUpd   = 0;             //count of updated files
                        int nNew   = 0;             //count of new files
                        foreach (var File in queue) //перебор файлов, которые надо копировать                            {
                        {
                            string SrcFile = File.SourceFile;
                            string DstFile = File.TargetFile;
                            string DstProjDir;
                            string SrcProjDir = File.SourceFileProjectDir;     //Папка проекта-источник
                                                                               // if (!Directory.Exists(SrcFile)) Directory.CreateDirectory(SrcFile);
                                                                               //var AllDestFiles = File.Value; //список куда копировать
                                                                               // int cAllSource = AllDestFiles.Count;
                                                                               //cTotal += AllDestFiles.Count;
                                                                               //================COPY========
                            int ID = 1000;
                            //процесс копирования
                            {
                                tmr.Start(DstFile, ID);
                                filesCount++;
                                if (System.IO.File.Exists(DstFile))    //File exist
                                {
                                    try
                                    {
                                        //update file
                                        var size = new FileInfo(SrcFile).Length;
                                        CONSTS.AddNewLine(tblog, filesCount.ToString() + "). " + "Updated :> " + SrcFile +
                                                          "\t(" + ((double)size / 1000) + "kbit)");
                                        CONSTS.AddToTempLine(tblog, "   Copy  :> " + SrcFile + " ==>" + DstFile);
                                        System.IO.File.Copy(SrcFile, DstFile, true);
                                        CONSTS.AddNewLine(tblog, "   Updated :> " + DstFile);
                                        nUpd++;
                                    }
                                    catch (Exception ex)
                                    {
                                        errorCopy++;
                                        CONSTS.AddNewLine(tblog,
                                                          "err:>\t" + ex.Message);
                                    }
                                }
                                else                                                                                                  //copy new file
                                {
                                    string Fullfiledir     = SrcFile.Remove(SrcFile.Length - SrcFile.Split('\\').Last().Length);      //полный путь файла-источника
                                    var targetProjDir      = project.AllProjectDirs.FirstOrDefault(x => DstFile.Contains(x.Dir)).Dir; //директория проекта файла-источника
                                    string relativefiledir = GetRelationPath(Fullfiledir, SrcProjDir);                                //вложенная папка(папки) внутри директории проекта
                                    string targetDir       = targetProjDir + relativefiledir;                                         //Полный путь папки-назначения
                                    if (!Directory.Exists(targetDir))
                                    {
                                        Directory.CreateDirectory(targetDir);
                                    }
                                    try
                                    {
                                        var size = new FileInfo(SrcFile).Length;
                                        CONSTS.AddNewLine(tblog, filesCount.ToString() + "). " + "New :> " + SrcFile +
                                                          "\t(" + ((double)size / 1000) + "kbit)");
                                        CONSTS.AddToTempLine(tblog, "   Copy  :> " + SrcFile + " ==>" + DstFile);
                                        System.IO.File.Copy(SrcFile, DstFile, true);
                                        CONSTS.AddNewLine(tblog, "   Copied  :> " + DstFile);
                                        nNew++;
                                    }
                                    catch (Exception ex)
                                    {
                                        errorCopy++;
                                        CONSTS.AddNewLine(tblog,
                                                          "err:>\t" + DstFile + "\t" + ex.Message);
                                    }
                                }    //end IF Else
                                CONSTS.invokeProgress(progressBar1, (int)(filesCount * 100 / cTotal));
                                tmr.Stop(ID); ID++;
                            } //конец перебора файлов назначения
                        }     //конец перебора исходных файлов

                        CONSTS.AddNewLine(tblog, "--------------------------------");
                        CONSTS.AddNewLine(tblog, project.Name + " синхронизирован.");
                        CONSTS.AddNewLine(tblog, "Новых файлов(new files): \t\t" + nNew.ToString());
                        CONSTS.AddNewLine(tblog, "Обновлено файлов(updated files):  \t" + nUpd.ToString());
                        CONSTS.AddNewLine(tblog, "Всего исходных файлов(total source):\t" + cTotal.ToString());
                        CONSTS.AddNewLine(tblog, "Всего скопировано(copied): \t" + cTotal.ToString());
                        CONSTS.AddNewLine(tblog, "Ошибок копирования(errors):\t" + errorCopy.ToString());
                        CONSTS.EnableButton(button1);
                        // Projects = cfg.ReadAllProjects();
                    }
                }
                finally
                {
                    CONSTS.EnableButton(button1);
                    SetSyncStatus(false);
                }
            }


                                    );
            SyncThread.Start();
        }