예제 #1
0
        private void AddDirectory(RestorePlanSourceEntry entry)
        {
            IFileVersion version = entry.Version == null ? null : new FileVersion {
                Version = entry.Version
            };

            AddDirectory(entry.PathNode, version);
        }
 public ShowVersionOfFileEventArgs(IFileWithHistory file, IFileVersion version)
 {
     if (file == null || version == null) {
         throw new ArgumentNullException ("File and version must not be null");
     }
     File = file;
     Version = version;
 }
예제 #3
0
        private BackupPlanTreeNode AddFileVersionNode(BackupPlanPathNode pathNode, IFileVersion version)
        {
            Assert.AreEqual(EntryType.FILE, pathNode.Type);
            BackupPlanTreeNode node = BackupPlanTreeNode.CreateFileVersionNode(pathNode, version);

            Nodes.Add(node);
            return(node);
        }
 public string CreateTempFileFromVersion(IFileWithHistory file, IFileVersion version)
 {
     var temp = Path.GetTempFileName ();
     var content = file.GetBinaryContentForVersion (version);
     WriteContentToTempFile (content, temp);
     var completeTempFileName = AppendOriginalFileEnding (temp, ReadOriginalFileEnding (file.PathInRepository));
     File.Move (temp, completeTempFileName);
     return completeTempFileName;
 }
예제 #5
0
        private string BuildNodeKey(BackupPlanTreeNodeData data, IFileVersion version)
        {
            switch (data.Type)
            {
            default: return(data.Path);

            case TypeEnum.FILE_VERSION: return(data.Path + (version == null ? string.Empty : "#" + version.Version));
            }
        }
예제 #6
0
 public IEnumerable <ParsedWord> Parse(IFileVersion fileVersion, Encoding encoding = null)
 {
     using (var reader = GetStreamReader(fileVersion, encoding))
     {
         foreach (var parsedWord in Parse(fileVersion, reader))
         {
             yield return(parsedWord);
         }
     }
 }
예제 #7
0
        private static ParsedWord NewParsedWord(IFileVersion fileVersion, StringBuilder word, int position, int lineNumber)
        {
            var wordPosition = position - word.Length;
            var wordString   = word.TrimEndingPunctuationChars().ToString();

            return(new ParsedWord(
                       wordString,
                       new WordEntry(fileVersion, wordPosition, lineNumber)
                       ));
        }
        public void Add(IFileVersion fileVersion, IEnumerable <ParsedWord> words)
        {
            var setOfWords = new HashSet <string>();

            using (_lock.Exclusive())
            {
                _directIndex.Add(fileVersion, setOfWords);
            }

            foreach (var word in words)
            {
                setOfWords.Add(word.Word);
                _searchIndex.Add(word.Word, word.Entry);
            }
        }
예제 #9
0
        /// <summary>
        /// Создаёт объект с реплицируемым файлов по версии файла.
        /// </summary>
        /// <param name="version"></param>
        /// <returns></returns>
        public static WcfRemoteFile FromFileVersion(IFileVersion version)
        {
            if (version == null)
            {
                throw new ArgumentNullException("version");
            }

            return(new WcfRemoteFile
            {
                Name = version.Name,
                Stream = version.Open(),
                TimeCreated = version.TimeCreated,
                UniqueID = version.File.UniqueID,
                VersionID = version.UniqueID
            });
        }
예제 #10
0
        // Convert from
        //	[<drive>:\][<directories>\][<filename>]
        // To
        //	[<RemoteRootDirectory>/][<drive>:/][<directories>/][<filename>:/<version>/][<filename>]
        public override string BuildVersionedRemotePath(string localPath, IFileVersion version)
        {
            PathComponents comps = new PathComponents(localPath);

            string result = "";

            if (!string.IsNullOrEmpty(RemoteRootDirectory))
            {
                // <RootDirectory>/
                if (RemoteRootDirectory.EndsWith("/"))
                {
                    result += RemoteRootDirectory;
                }
                else
                {
                    result += RemoteRootDirectory + RemoteDirectorySeparatorChar;
                }
            }

            if (comps.HasDrive)
            {
                // <drive>:/
                result += comps.Drive + RemoteVersionPostfixChar + RemoteDirectorySeparatorChar;
            }

            if (comps.HasDirectories)
            {
                // <directories>/
                result += string.Join(RemoteDirectorySeparatorChar.ToString(), comps.Directories) + RemoteDirectorySeparatorChar;
            }

            if (comps.HasFileName)
            {
                if (version != null)
                {
                    result += comps.FileName                                    // <filename>
                              + RemoteVersionPostfixChar                        // <filename>:
                              + RemoteDirectorySeparatorChar                    // <filename>:/
                              + version.Version                                 // <filename>:/<version>
                              + RemoteDirectorySeparatorChar;                   // <filename>:/<version>/
                }
                result += comps.FileName;                                       // [<filename>:/<version>/]<filename>
            }

            return(result);            // [<RootDirectory>/][<drive>:/][<directories>/][<filename>:/<version>/][<filename>]
        }
예제 #11
0
        public HistoryEntry(ApplicationLogic appLogic, IFileWithHistory file, IFileVersion version)
        {
            Version = version;
            File = file;
            applicationLogic = appLogic;
            this.Build ();

            openButton.Clicked += HandleOpenButtonClicked;

            dateLabel.Text = Version.CreationAt.ToString ();

            commentTextview.Buffer.Text = Version.Commit.Comment;

            BorderWidth = 5;

            Show ();
        }
예제 #12
0
 public string GetFile(IFileWithHistory file, IFileVersion version)
 {
     if (file == null || version == null) {
         throw new ArgumentNullException ("file and version must not be null");
     }
     string cachedFile;
     var key = new CacheKey (file, version);
     if (Cache.ContainsKey (key)) {
         cachedFile = Cache[key];
     }
     else {
         var tempFile = creator.CreateTempFileFromVersion (file, version);
         Cache[key] = tempFile;
         cachedFile = tempFile;
     }
     return cachedFile;
 }
예제 #13
0
        private void IndexFile(string filePath, IFileVersion version)
        {
            try
            {
                _eventReactor.React(EngineEvent.FileIndexingStarted, filePath);

                var encoding = FileEncoding.DetectFileEncoding(filePath);
                var words    = _parserProvider.Provide(filePath).Parse(version, encoding);
                _index.Add(version, words);

                _eventReactor.React(EngineEvent.FileIndexingEnded, filePath);
            }
            catch (Exception exception)
            {
                _eventReactor.React(EngineEvent.FileIndexingEnded, filePath, exception);
            }
        }
예제 #14
0
        private void AddFileVersion(BackupPlanPathNode node, IFileVersion version)
        {
            CancellationToken.ThrowIfCancellationRequested();

            BackupedFile f = null;

            // If `version` is not not informed, then find the file's latest version
            // that has completed transfer.
            if (version == null)
            {
                f = node.PlanFile.Versions.LastOrDefault(v => v.TransferStatus == TransferStatus.COMPLETED);

                IFileVersion latestFileVersion = f != null && f.Id.HasValue
                                        ? new FileVersion {
                    Name = f.VersionName, Version = f.Version
                }
                                        : null;
                version = latestFileVersion;
            }
            else
            {
                f = node.PlanFile.Versions.First(
                    p => p.Version.Equals(version.Version, StringComparison.InvariantCulture));
            }

            if (f == null || !f.Id.HasValue)
            {
                return;
            }

            var item = new CustomVersionedFile
            {
                Path             = node.Path,
                Size             = f.FileSize,
                LastWriteTimeUtc = f.FileLastWrittenAt,
                UserData         = f,         // Reference the original `BackupedFile`.
                Version          = version,
            };

            Results.Files.AddLast(item);

            if (FileAdded != null)
            {
                FileAdded(this, item);
            }
        }
예제 #15
0
        /// <summary>
        /// Возвращает содержимое версии файла.
        /// </summary>
        /// <param name="folderUrl">Адрес папки.</param>
        /// <param name="fileUniqueID">Уникальный идентификатор файла.</param>
        /// <param name="versionUniqueID">Уникальный идентификатор версии файла.</param>
        /// <returns></returns>
        public byte[] GetFileVersionContent(string folderUrl, Guid fileUniqueID, Guid versionUniqueID)
        {
            byte[] content = null;

            try
            {
                this.Authorize();

                if (string.IsNullOrEmpty(folderUrl))
                {
                    throw new ArgumentNullException("folderUrl");
                }

                if (fileUniqueID == Guid.Empty)
                {
                    throw new ArgumentNullException("fileUniqueID");
                }

                if (versionUniqueID == Guid.Empty)
                {
                    throw new ArgumentNullException("versionUniqueID");
                }

                this.Logger.WriteFormatMessage("GetFileVersionContent:Начало получения содержимого файла, folderUrl: {0}, fileUniqueID: {1}, versionUniqueID: {2}", folderUrl, fileUniqueID, versionUniqueID);

                using (IFile file = this.Storage.GetFile(folderUrl, fileUniqueID))
                {
                    using (IFileVersion version = file.GetVersion(versionUniqueID))
                    {
                        this.VerifyBufferSize(version.Size);
                        content = version.Content;
                    }
                }
                this.Logger.WriteFormatMessage("GetFileVersionContent:Начало получения содержимого файла, folderUrl: {0}, fileUniqueID: {1}, versionUniqueID: {2}", folderUrl, fileUniqueID, versionUniqueID);
            }
            catch (Exception ex)
            {
                this.Logger.WriteFormatMessage("GetFileVersionContent:Ошибка выполенения операции, текст ошибки: {0}", ex);
                throw ex;
            }

            return(content);
        }
예제 #16
0
        /// <summary>
        /// Возвращает сессионную ссылку на версию файла.
        /// </summary>
        /// <param name="fileUrl">Адрес файла.</param>
        /// <param name="versionUniqueID">Уникальный идентификатор версии.</param>
        /// <param name="userIdentity">Строка, идентифицирующая пользователя.</param>
        /// <returns></returns>
        public string GetSessionFileLink(string fileUrl, Guid versionUniqueID, string userIdentity)
        {
            if (string.IsNullOrEmpty(fileUrl))
            {
                throw new ArgumentNullException("fileUrl");
            }

            if (versionUniqueID == Guid.Empty)
            {
                throw new ArgumentNullException("versionUniqueID");
            }

            this.Logger.WriteFormatMessage("GetSessionFileLink:Начало генерации сессионной ссылки, fileUrl: {0}, versionUniqueID: {1}", fileUrl, versionUniqueID);

            File         file        = this.GetFileInternal(fileUrl);
            IFileVersion version     = file.GetVersion(versionUniqueID);
            string       sessionLink = this.GetSessionFileLinkInternal(version, userIdentity);

            this.Logger.WriteFormatMessage("GetSessionFileLink:Окончание генерации сессионной ссылки, fileUrl: {0}, versionUniqueID: {1}", fileUrl, versionUniqueID);

            return(sessionLink);
        }
예제 #17
0
파일: File.cs 프로젝트: soroush01110011/MVP
        /// <summary>
        /// Возвращает версию файла.
        /// </summary>
        /// <param name="versionUniqueID">Уникальный идентификатор версии.</param>
        /// <param name="throwIfNotexists">Выбросить исключение, если версии не существует?</param>
        /// <returns></returns>
        public IFileVersion GetVersion(Guid versionUniqueID, bool throwIfNotexists = true)
        {
            if (versionUniqueID == Guid.Empty)
            {
                throw new ArgumentNullException("versionUniqueID");
            }

            IFileVersion version = null;

            if (this.VersionsByID.ContainsKey(versionUniqueID))
            {
                version = this.VersionsByID[versionUniqueID];
            }

            if (throwIfNotexists && version == null)
            {
                throw new Exception(string.Format("Не удалось найти версию с идентификатором {0}",
                                                  versionUniqueID));
            }

            return(version);
        }
예제 #18
0
        /// <summary>
        /// Возвращает транспортный объект файла для передачи клиенту.
        /// </summary>
        /// <param name="file">Файл.</param>
        /// <param name="loadOptions">Опции загрузки.</param>
        /// <returns></returns>
        public static WcfFileVersionInfo FromFileVersion(IFileVersion fileVersion, GetFileOptions loadOptions = null)
        {
            if (fileVersion == null)
            {
                throw new ArgumentNullException("fileVersion");
            }

            WcfFileVersionInfo wcfFile = new WcfFileVersionInfo()
            {
                UniqueID         = fileVersion.UniqueID,
                Name             = fileVersion.Name,
                TimeCreated      = fileVersion.TimeCreated,
                Size             = fileVersion.Size,
                CreatedStorageID = fileVersion.CreatedStorageID
            };

            if (loadOptions != null && loadOptions.LoadContent)
            {
                wcfFile.Content = fileVersion.Content;
            }

            return(wcfFile);
        }
예제 #19
0
 public void AddVersionStrategy(IFileVersion strategy)
 {
     _versionStrategies.Add(strategy);
 }
예제 #20
0
        public async Task Process(HttpListenerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            this.Logger.WriteMessage("Process:Начало отдачи содержимого по сессионной ссылке");

            Stream sourceStream  = null;
            string fileName      = null;
            bool   isInline      = false;
            long   contentLength = 0;

            string url = context.Request.Url.AbsoluteUri;

            this.Logger.WriteMessage(String.Format("Process:url: {0}", url));

            try
            {
                this.Authorize(context);

                HttpParamsReader parametersReader = new HttpParamsReader(url);
                isInline = parametersReader.GetBooleanParameterValue("inline");

                using (IFileVersion version = this.Engine.ResolveSessionLink(url, context.User.Identity))
                {
                    this.Logger.WriteMessage(String.Format("Process:url: {0}, version.Name: {1}, version.UniqueID: {2}", url, version.Name, version.UniqueID));

                    contentLength = version.Size;
                    fileName      = version.Name;
                    sourceStream  = version.Open();
                }
            }
            catch (Exception ex)
            {
                string responseString = string.Format("Ошибка при обработке ссылки {0}. Текст ошибки: {1}",
                                                      url,
                                                      ex);
                fileName = "error.txt";

                byte[] content = Encoding.UTF8.GetBytes(responseString);
                contentLength = content.Length;
                sourceStream  = new MemoryStream(content);
                context.Response.ContentEncoding = Encoding.UTF8;

                this.Logger.WriteMessage(String.Format("Process:{0}", responseString), LogLevel.Error);
            }
            finally
            {
                try
                {
                    string title = string.Format(string.Format("filename*=UTF-8''{0}", Uri.EscapeDataString(fileName)));

                    context.Response.ContentLength64 = contentLength;
                    context.Response.ContentType     = "application/octet-stream";
                    string fileDisposition = isInline ? "inline" : "attachment";
                    context.Response.Headers.Add("Content-Disposition", string.Format("{0}; {1}", fileDisposition, title));
                    context.Response.StatusCode = (int)HttpStatusCode.OK;

                    using (sourceStream)
                    {
                        byte[] buffer = new byte[1024 * 1024];
                        int    read   = 0;
                        while ((read = sourceStream.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            context.Response.OutputStream.Write(buffer, 0, read);
                        }
                    }
                    this.Logger.WriteMessage(
                        String.Format("Process:Окончание отдачи содержимого по сессионной ссылке, url: {0}", url));
                }
                catch (Exception innerEx)
                {
                    this.Logger.WriteMessage(
                        String.Format("Process:Ошибка отдачи содержимого клиенту, текст ошибки: {0}", innerEx),
                        LogLevel.Error);
                }
            }
        }
예제 #21
0
 private void AddFile(BackupPlanPathNode node, IFileVersion version)
 {
     AddFileVersion(node, version);
 }
예제 #22
0
 public EntryInfo(TypeEnum type, string name, string path, IFileVersion version)
     : this(type, name, path)
 {
     Version = version;
 }
 public WordEntry(IFileVersion fileVersion, int position, int lineNumber)
 {
     FileVersion = fileVersion;
     Position    = position;
     LineNumber  = lineNumber;
 }
예제 #24
0
 private static StreamReader GetStreamReader(IFileVersion fileVersion, Encoding encoding)
 {
     return(encoding == null
         ? new StreamReader(fileVersion.Path)
         : new StreamReader(fileVersion.Path, encoding));
 }
 public NoVersionInfoException(IFileVersion file) {
     File = file;
 }
예제 #26
0
 abstract public void DeleteVersionedFile(string sourcePath, IFileVersion version, object userData);
예제 #27
0
 private string GetSessionFileLinkInternal(IFileVersion version)
 {
     return(this.GetSessionFileLinkInternal(version, null));
 }
예제 #28
0
 public abstract string BuildVersionedRemotePath(string localPath, IFileVersion version);
 public void SetUp()
 {
     myMockery = new Mockery ();
     file1 = myMockery.NewMock <IFileWithHistory> ();
     version1 = myMockery.NewMock<IFileVersion> ();
     provider = myMockery.NewMock<IHistoryProvider> ();
 }
 public byte[] GetBinaryContentForVersion(IFileVersion version)
 {
     throw new System.NotImplementedException ();
 }
예제 #31
0
 public void DeleteVersionedFile(string sourcePath, IFileVersion version, object identifier)
 {
     TransferAgent.DeleteVersionedFile(sourcePath, version, identifier);
 }
예제 #32
0
        public static BackupPlanTreeNode CreateFileVersionNode(BackupPlanPathNode pathNode, IFileVersion version)
        {
            Assert.AreEqual(EntryType.FILE, pathNode.Type);
            BackupPlanTreeNode node = new BackupPlanTreeNode(version.Name, 0, 0);

            node.ImageKey = "file_version";
            EntryInfo info = new EntryInfo(TypeEnum.FILE_VERSION, pathNode.Name, pathNode.Path, version);

            node.Data.InfoObject = info;
            node.Data.UserObject = pathNode;
            return(node);
        }
예제 #33
0
 public CacheKey(IFileWithHistory file, IFileVersion version)
 {
     File = file;
     Version = version;
 }