Exemple #1
0
        /// <summary>
        /// Create An iFolder Entry
        /// </summary>
        /// <param name="c"></param>
        /// <param name="parent"></param>
        /// <param name="type"></param>
        /// <param name="entryName"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        internal static Node CreateEntry(Collection c, Node parent,
                                         iFolderEntryType type, string entryName, out string path, bool DontCheckPolicies)
        {
            Node result = null;

            // NOTE: a new entry off the iFolder is not allowed, it must be off the root directory node or lower
            if ((parent == null) || (c.ID.Equals(parent.ID)))
            {
                throw new EntryDoesNotExistException(parent.ID);
            }

            // NOTE: only directories can have children
            if (!parent.IsBaseType(NodeTypes.DirNodeType))
            {
                throw new DirectoryEntryRequiredException(parent.ID);
            }

            // check the name
            CheckName(entryName);

            // create new path
            DirNode parentDirNode = (DirNode)parent;

            path = parentDirNode.GetFullPath(c);
            path = System.IO.Path.Combine(path, entryName);

            // check for existing entry (case insensitive test)
            if (SyncFile.DoesNodeExist(c, parentDirNode, entryName))
            {
                throw new EntryAlreadyExistException(entryName);
            }

            // directory
            if (type == iFolderEntryType.Directory)
            {
                result = new DirNode(c, parentDirNode, entryName);
            }
            // file
            else
            {
                if (DontCheckPolicies == false)
                {
                    // check file type policy
                    FileTypeFilter filter = FileTypeFilter.Get(c);
                    if (!filter.Allowed(entryName))
                    {
                        throw new FileTypeException(entryName);
                    }
                }

                result = new FileNode(c, parentDirNode, entryName);
            }

            return(result);
        }
        private void btnBackup_Click(object sender, EventArgs e)
        {
            if (lstName.CheckedItems.Count == 0)
            {
                MessageBox.Show("Not selected anything.", "Information", MessageBoxButtons.OK);
                return;
            }

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

            using (new CWaitCursor(this, btnBackup))
            {
                for (int i = 0; i < lstName.CheckedItems.Count; i++)
                {
                    string NameCur = (string)lstName.CheckedItems[i];

                    SInfoBackup InfoIs;
                    string      ErrMsgIs;
                    if (!IsValidForBackup(NameCur, out InfoIs, out ErrMsgIs))
                    {
                        MessageBox.Show(ErrMsgIs, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                        return;
                    }

                    CSyncFile SyncFile = null;
                    if (InfoIs.FtpInfo == null)
                    {
                        SyncFile = new CSyncFile(this.maFullPathFromCmd, InfoIs.RootFolderSrc, new string[] { InfoIs.RootFolderDest }, SyncTypes.AfterSrcTime, InfoIs.MinifyJs, InfoIs.aFullPathReferencingJs, InfoIs.aJsFullPathRefered, DateTime.MinValue, InfoIs.LogFolder);
                    }
                    else
                    {
                        SyncFile = new CSyncFile(this.maFullPathFromCmd, InfoIs.RootFolderSrc, new CFtpInfoSync[] { InfoIs.FtpInfo }, SyncTypes.AfterSrcTime, InfoIs.MinifyJs, InfoIs.aFullPathReferencingJs, InfoIs.aJsFullPathRefered, DateTime.MinValue, InfoIs.LogFolder);
                    }

                    //선택한 파일은 무조건 복사해야 해서 주석
                    //SyncFile.DisallowedExt = InfoIs.DisallowedExt.Split(';');
                    //if (InfoIs.DisallowedFolder != "")
                    //{
                    //    SyncFile.DisallowedFolder = InfoIs.DisallowedFolder.Split(';');
                    //}
                    SyncFile.CopyAll();

                    if (SyncFile.CountFailed > 0)
                    {
                        aMsg.Add(string.Format("There's {0} count failed from {1}", SyncFile.CountFailed, NameCur));
                    }
                }
            }

            aMsg.Add("Completed.");
            MessageBox.Show(string.Join("\r\n\r\n", aMsg.ToArray()), "Information", MessageBoxButtons.OK);
        }
Exemple #3
0
        /// <summary>
        /// Check for a valid name.
        /// </summary>
        /// <param name="name"></param>
        public static void CheckName(string name)
        {
            // check for invalid characters
            if (!SyncFile.IsNameValid(name) || (name.IndexOf('/') != -1))
            {
                throw new EntryInvalidCharactersException(name);
            }

            // check for invalid names
            if ((name == ".") || (name == ".."))
            {
                throw new EntryInvalidNameException(name);
            }
        }
        /// <summary>
        /// Removes file
        /// </summary>
        /// <param name="file">sync object</param>
        /// <param name="secureDeleting">if true - does ovewrites file with zeros</param>
        void RemoveAllFilesAtFolder(SyncFile file, bool secureDeleting)
        {
            _log.ProcedureCall("RemoveAllFilesAtFolder", secureDeleting.ToString());

            file.Dispose();

            if (secureDeleting)
            {
                OverWriteFileWithZeros(file.FileName);
            }

            _log.WriteLine(LoggingEvent.Debug, "X " + file.FileName);

            if (!string.IsNullOrEmpty(file.FileName))
            {
                try
                {
                    File.Delete(file.FileName);
                }
                catch (DirectoryNotFoundException e)
                {
                    _log.WriteLine(LoggingEvent.Warning,
                                   string.Format(CultureInfo.CurrentCulture, _couldNotDeleteFileFormatString, file.FileName, e.Message));
                }
                catch (PathTooLongException e)
                {
                    _log.WriteLine(LoggingEvent.Warning,
                                   string.Format(CultureInfo.CurrentCulture, _couldNotDeleteFileFormatString, file.FileName, e.Message));
                }
                catch (FileNotFoundException e)
                {
                    _log.WriteLine(LoggingEvent.Warning,
                                   string.Format(CultureInfo.CurrentCulture, _couldNotDeleteFileFormatString, file.FileName, e.Message));
                }
                catch (UnauthorizedAccessException e)
                {
                    _log.WriteLine(LoggingEvent.Warning,
                                   string.Format(CultureInfo.CurrentCulture, _couldNotDeleteFileFormatString, file.FileName, e.Message));
                }
                catch (IOException e)
                {
                    _log.WriteLine(LoggingEvent.Warning,
                                   string.Format(CultureInfo.CurrentCulture, _couldNotDeleteFileFormatString, file.FileName, e.Message));
                }
            }
            else
            {
                _log.WriteLine(LoggingEvent.Debug, "empty file");
            }
        }
Exemple #5
0
        public void InitializeTest()
        {
            // создаём тестовый набор данных:
            var file1Path = @"C:\some_folder\some_file1.csv";
            var file1Meta = new FileMetadata {
                ByteSize = _file1ByteSize, LastModified = _file1LastModified
            };

            var filesRepo = new SortedList <string, FileMetadata>
            {
                { file1Path, file1Meta }
            };

            // делаем иньекцию тестового менеджера файловой системы
            _injectedManager = new MockFileSystemManager(filesRepo);
            _file1           = new SyncFile(file1Path, _injectedManager);
        }
        public void InitializeTest()
        {
            // создаём тестовый набор данных:

            // иньекция системного времени:
            SystemTime.Now = () => _testDateTimeNow;

            // файл номер 1
            var file1Path = @"C:\some_folder\some_file1.csv"; // путь
            var file1Meta = new FileMetadata {
                ByteSize = 10, LastModified = new DateTime(2013, 1, 5)
            };                                                                                         // свойства

            // файл номер 2, три файла(три пути) с одинаковыми свойствами
            var file2Path = @"D:\some_folder2\stuff\some_file1.csv";
            var file2WithDifferNamePath      = @"D:\some_folder2\stuff\some_file1_with_differ_name.csv";
            var file2WithDifferExtensionPath = @"D:\some_folder2\stuff\some_file1.with_differ_extension";
            var file2Meta = new FileMetadata {
                ByteSize = 15, LastModified = new DateTime(2013, 1, 7)
            };

            // создаем тестовый менеджер файловой системы
            _injectedManager = A.Fake <IFileSystemManager>();
            // прописываем какие свойства (матаданные) он должен возвращать по каждому файлу
            A.CallTo(() => _injectedManager.GetFileMetadata(file1Path)).Returns(file1Meta);
            A.CallTo(() => _injectedManager.GetFileMetadata(file2Path)).Returns(file2Meta);
            A.CallTo(() => _injectedManager.GetFileMetadata(file2WithDifferNamePath)).Returns(file2Meta);
            A.CallTo(() => _injectedManager.GetFileMetadata(file2WithDifferExtensionPath)).Returns(file2Meta);

            #region делаем иньекцию тестового менеджера файловой системы:

            // создаем объекты SyncFile для файлов:
            // объект SyncFile для файла номер 1, неактуальный (более старый)
            _nonActualFile = new SyncFile(file1Path, _injectedManager);
            // объект SyncFile для файла номер 2, актуальный (более новый)
            _actualFile = new SyncFile(file2Path, _injectedManager);

            //  объект SyncFile для файла номер 2, актуальный (более новый) с другим именем
            _actualFileWithDifferName = new SyncFile(file2WithDifferNamePath, _injectedManager);
            //  объект SyncFile для файла номер 2, актуальный (более новый) с другим расширением
            _actualFileWithDifferExtension = new SyncFile(file2WithDifferExtensionPath, _injectedManager);

            _sfp = new SyncFilesPair(_injectedManager);
            #endregion
        }
        public void ProcessRequest(HttpContext context)
        {
            var contentToSync = Content.Load(PortalContext.Current.ContextNodePath);
            var result        = new SyncFile(contentToSync).Sync();

            context.Response.Clear();
            context.Response.ClearHeaders();
            context.Response.ContentType  = "application/json";
            context.Response.BufferOutput = true;
            context.Response.Write(
                new JavaScriptSerializer().Serialize(new
            {
                result = result.Select(c => c.ContentPath + "\r\n")
            })
                );

            context.Response.End();
        }
Exemple #8
0
        public ActionResult ImportERP(HttpPostedFileBase file)
        {
            try
            {
                var syncs = new SyncFile(file.InputStream).ToSync();

                var db = new Context();

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


                //IsDeviceNet为true设备网
                if (GlobalData.IsDeviceNet)
                {
                    foreach (var sync in syncs)
                    {
                        var syncdb = db.SynchroTables.SingleOrDefault(x => x.taskNo == sync.taskNo);

                        if (syncdb != null)
                        {
                            //相同编号任务编号的同一版本不能重复导入
                            existSyncs.Add($"{syncdb.taskNo}({syncdb.partNo})");
                            continue;
                        }

                        syncdb = new SynchroTable
                        {
                            taskNo        = sync.taskNo,
                            partNo        = sync.partNo,
                            batchNo       = sync.batchNo,
                            seqNo         = sync.seqNo,
                            countNum      = sync.countNum,
                            facCode       = sync.facCode,
                            weldNo        = sync.weldNo,
                            welderNo      = sync.welderNo,
                            status        = sync.status,
                            startTime     = sync.startTime,
                            endTime       = sync.endTime,
                            realStartTime = sync.realStartTime,
                            realEndTime   = sync.realEndTime,
                            weldTime      = sync.weldTime
                        };

                        db.SynchroTables.Add(syncdb);
                        db.SaveChanges();
                    }
                }


                if (existSyncs.Any())
                {
                    return(Json(new { succeed = true, existSyncs }, "text/html"));
                }
                else
                {
                    return(Json(new { succeed = true }, "text/html"));
                }
            }
            catch (Exception e)
            {
                Log.Error(e.StackTrace);
                return(Json(new { succeed = false, error = e.Message }, "text/html"));
            }
        }
Exemple #9
0
 public ImageCreationJob(LogBase log, SyncFile imageFile, Collection <MetaRecord> metarecords)
 {
     _imageFile   = imageFile;
     _log         = log;
     _metarecords = metarecords;
 }
Exemple #10
0
        private void btnSyncNow_Click(object sender, EventArgs e)
        {
            using (new CWaitCursor(this, btnSyncNow))
            {
                SInfo  InfoIs;
                string ErrMsgIs;
                if (!IsValid(out InfoIs, out ErrMsgIs))
                {
                    MessageBox.Show(ErrMsgIs, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                    return;
                }

                CSyncFile SyncFile = null;
                if (InfoIs.FtpInfo == null)
                {
                    SyncFile = new CSyncFile(InfoIs.RootFolderSrc, InfoIs.aRootFolderDest, InfoIs.SyncType, InfoIs.MinifyJs, InfoIs.aFullPathReferencingJs, InfoIs.aJsFullPathRefered, InfoIs.DateTimeAfter, InfoIs.LogFolder);
                }
                else
                {
                    SyncFile = new CSyncFile(InfoIs.RootFolderSrc, new CFtpInfoSync[] { InfoIs.FtpInfo }, InfoIs.SyncType, InfoIs.MinifyJs, InfoIs.aFullPathReferencingJs, InfoIs.aJsFullPathRefered, InfoIs.DateTimeAfter, InfoIs.LogFolder);
                }

                if (radDisallowedExt.Checked)
                {
                    SyncFile.DisallowedExt = InfoIs.DisallowedExt.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                }
                else
                {
                    SyncFile.AllowedOnlyExt = InfoIs.AllowedOnlyExt.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                }

                if (radDisallowedFolder.Checked)
                {
                    SyncFile.DisallowedFolder = InfoIs.DisallowedFolder.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                }
                else
                {
                    SyncFile.AllowedOnlyFolder = InfoIs.AllowedOnlyFolder.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                }

                SyncFile.CopyAll();

                if (InfoIs.EmptyFolderHasNoFile)
                {
                    foreach (string RootFolderDest in InfoIs.aRootFolderDest)
                    {
                        CFile.EmptyFolderHasNoFile(RootFolderDest);
                    }
                }

                if (SyncFile.CountFailed > 0)
                {
                    MessageBox.Show(string.Format("{0} count of file failed.", SyncFile.CountFailed), "Information", MessageBoxButtons.OK);
                    return;
                }

                if (InfoIs.SyncType == SyncTypes.AfterSrcTime)
                {
                    //다음번에 이 시간을 기준할 수 있게 함.
                    DataTable        dt  = GetTable();
                    DataGridViewCell dgv = grvList.SelectedCells[0];
                    dt.Rows[dgv.OwningRow.Index]["DateTimeAfter"] = DateTime.Now;
                    tlsbtnSave.PerformClick();
                }
                sttlblMsg.Text = "Synchronization completed at " + DateTime.Now.ToString();
            }
        }
Exemple #11
0
        static void Main(string[] args)
        {
            var syncPairs = new List <SyncFilesPair>();
            var backupDir = System.Environment.CurrentDirectory + "\\backup";

            FileSystemManager.Instance.CreateDirIfNotExist(backupDir);

            try
            {
                var xDoc   = XDocument.Load(System.Environment.CurrentDirectory + "\\beaverSync.xml");
                var xPairs = xDoc.Root.Elements("SyncFilesPair");

                foreach (var xPair in xPairs)
                {
                    var pair = new SyncFilesPair {
                        BackupDirPath = backupDir, NeedBackup = true
                    };
                    var file1 = new SyncFile(xPair.Element("FirstFilePath").Value);
                    var file2 = new SyncFile(xPair.Element("SecondFilePath").Value);
                    pair.SetFirstFile(file1);
                    pair.SetSecondFile(file2);

                    syncPairs.Add(pair);
                }
            }
            catch (Exception exc)
            {
                Console.WriteLine("Неверный файл конфигурации. Невозможно считать синхропары.", exc);
            }

            int i = 1;

            foreach (var pair in syncPairs)
            {
                Console.WriteLine("|SyncPair #{0}", i++);
                Console.WriteLine("|");
                Console.WriteLine("|   1. {0}", pair.FirstFile.FullPath);
                Console.WriteLine("|\t {0}", pair.FirstFile.RetrieveFileMetadata());
                Console.WriteLine("|");
                Console.WriteLine("|   2. {0}", pair.SecondFile.FullPath);
                Console.WriteLine("|\t {0}", pair.SecondFile.RetrieveFileMetadata());
                Console.WriteLine();
            }

            //Console.WriteLine("Press <enter> for continue a synchronization process...");
            //Console.ReadKey();

            i = 1;
            foreach (var pair in syncPairs)
            {
                try
                {
                    Console.WriteLine("Try to synchronize a SyncPair #{0}...", i);
                    pair.Sync();
                    Console.WriteLine("SyncPair #{0} synchronized success.", i);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("SyncPair #{0} synchronization failed :(", i);
                    Console.WriteLine(ex);
                }

                Console.WriteLine();
                i++;
            }

            i = 1;
            foreach (var pair in syncPairs)
            {
                Console.WriteLine("|SyncPair #{0}", i++);
                Console.WriteLine("|");
                Console.WriteLine("|   1. {0}", pair.FirstFile.FullPath);
                Console.WriteLine("|\t {0}", pair.FirstFile.RetrieveFileMetadata());
                Console.WriteLine("|");
                Console.WriteLine("|   2. {0}", pair.SecondFile.FullPath);
                Console.WriteLine("|\t {0}", pair.SecondFile.RetrieveFileMetadata());
                Console.WriteLine();
            }

            Console.WriteLine("Press <enter> for exit...");
            Console.ReadKey();
        }
Exemple #12
0
        void Write(ISync local, SyncFolder lfolder, ISync remote, SyncFolder rfolder, string filterFolder, string filterFile, bool useMd5)
        {
            if (rfolder == null || lfolder == null)
            {
                return;
            }

            // Folder
            foreach (SyncFolder f in rfolder.Folders)
            {
                SyncFolder esta = null;
                foreach (SyncFolder f2 in lfolder.Folders)
                {
                    if (f2.Name == f.Name)
                    {
                        f2.Checked = true;
                        esta       = f2;
                        break;
                    }
                }

                if (!StringHelper.Like(filterFile, f.Name))
                {
                    continue;
                }

                try
                {
                    if (esta == null)
                    {
                        esta = new SyncFolder(lfolder)
                        {
                            Name = f.Name
                        };
                        local.CreateFolder(esta);
                        WriteInfo("Creating folder: " + esta.GetFullPath('/'));
                    }

                    // Esta, hacerlo recursivo
                    Write(local, esta, remote, f, filterFolder, filterFile, useMd5);
                }
                catch (Exception e)
                {
                    WriteError(e.Message);
                }
            }

            // Files
            foreach (SyncFile f in rfolder.Files)
            {
                SyncFile esta = null;
                foreach (SyncFile f2 in lfolder.Files)
                {
                    if (f2.Name == f.Name)
                    {
                        f2.Checked = true;
                        esta       = f2;
                        break;
                    }
                }

                if (!StringHelper.Like(filterFile, f.Name))
                {
                    continue;
                }

                try
                {
                    if (esta != null)
                    {
                        // Compare
                        if (f.Length == esta.Length)
                        {
                            // Same file
                            if (useMd5)
                            {
                                if (local.GetMd5(f) == remote.GetMd5(esta))
                                {
                                    continue;
                                }
                            }
                            else
                            {
                                continue;
                            }

                            // Delete
                            local.DeleteFile(esta);
                            WriteInfo("Deleting file: " + esta.GetFullPath('/'));
                        }
                    }

                    // Write
                    using (Stream stream = remote.GetFile(f))
                    {
                        SyncFile put = new SyncFile(lfolder)
                        {
                            Name = f.Name
                        };
                        local.WriteFile(put, stream);

                        WriteInfo("Writing file: " + put.GetFullPath('/'));
                    }
                }
                catch (Exception e)
                {
                    WriteError(e.Message);
                }
            }
        }