/// <summary> /// Verify upload file part asynchronously /// </summary> /// <param name="uploadRequest">UploadRequest</param> /// <returns>Verification reponse</returns> private async Task <VerifyUploadResponse> VerifyUploadFileAsync(IUploadRequest uploadRequest) { try { var request = await GenerateFileStreamRequest(uploadRequest.File, uploadRequest.Ticket, verifyOnly : true) .ConfigureAwait(false); var response = await request.ExecuteRequestAsync().ConfigureAwait(false); var verify = new VerifyUploadResponse(); CheckStatusCodeError(uploadRequest, response, "Error verifying file upload.", (HttpStatusCode)308); // ReSharper disable once ConvertIfStatementToSwitchStatement if (response.StatusCode == HttpStatusCode.OK) { verify.BytesWritten = uploadRequest.FileLength; verify.Status = UploadStatusEnum.Completed; } else if (response.StatusCode == (HttpStatusCode)308) { verify.Status = UploadStatusEnum.InProgress; if (!response.Headers.Contains("Range")) { return(verify); } var match = RangeRegex.Match(response.Headers.GetValues("Range").First()); // ReSharper disable once InvertIf if (match.Success && long.TryParse(match.Groups["start"].Value, out var startIndex) && long.TryParse(match.Groups["end"].Value, out var endIndex)) { verify.BytesWritten = endIndex - startIndex; uploadRequest.BytesWritten = verify.BytesWritten; if (verify.BytesWritten == uploadRequest.FileLength) { verify.Status = UploadStatusEnum.Completed; } } } else { verify.Status = UploadStatusEnum.NotFound; } return(verify); } catch (Exception ex) { if (ex is VimeoApiException) { throw; } throw new VimeoUploadException("Error verifying file upload.", uploadRequest, ex); } }
public void HandleFile(HttpListenerContext context) { try { var request = context.Request; var response = context.Response; var outputStream = response.OutputStream; var fileInfo = new FileInfo(ToLocal(request.Url.LocalPath, _folderRoot)); //Get info about the requested file. using (var fileStream = fileInfo.Open(FileMode.Open, FileAccess.Read, FileShare.Read)) //Open the file for reading, and allow other programs to also read the file { var fileLength = fileStream.Length; // Get the length of the file. var match = RangeRegex.Match(request.Headers["Range"] ?? string.Empty); // Get the Range header, var start = match.Groups["start"].Success ? long.Parse(match.Groups["start"].Value, NumberStyles.Integer) : 0L; var finish = match.Groups["end"].Success ? long.Parse(match.Groups["end"].Value, NumberStyles.Integer) + 1 : fileLength; var length = finish - start; response.KeepAlive = false; response.Headers.Add("Content-Type", MimeTypeMap.GetMimeType(fileInfo.Extension)); //Use MimeTypeMap to get the file's mime type. response.Headers.Add("Content-Disposition", $"inline; filename={fileInfo.Name}"); response.Headers.Add("Date", $"{DateTime.Now:R}"); response.Headers.Add("Last-Modified", $"{fileInfo.LastWriteTime:R}"); response.Headers.Add("Accept-Ranges", "bytes"); response.Headers.Add("Content-Range", $"bytes {start}-{finish - 1}/{fileLength}"); response.ContentLength64 = length; if (start >= 0 && finish <= fileLength) //If the requested range is not possible, return status code 416 (Requested Range not Satisfiable). { response.StatusCode = (start == 0 && finish == fileLength) ? 200 : 206; //If the range is the same as the file size, the status code is 200 (OK), else the status is 206 (Partial Content). fileStream.Seek(start, SeekOrigin.Begin); //Start the filestream reading at the requested start. var buffer = new byte[BufferSize]; //Make the buffer the same size as the buffer size constant. for (var i = 0; i < length; i += BufferSize) { outputStream.Write(buffer, 0, fileStream.Read(buffer, 0, (int)Math.Min(length - i, BufferSize))); // Read then Write the maximum of the buffer size. } } else { response.StatusCode = 416; } } outputStream.Flush(); response.Close(); } catch (HttpListenerException) { context.Response.Abort(); } catch (Exception e) { Log($"[Error] {e.Message}"); context.Response.Abort(); } }
/// <summary> /// Verify upload file part asynchronously /// </summary> /// <param name="uploadRequest">UploadRequest</param> /// <returns>Verification reponse</returns> public async Task <VerifyUploadResponse> VerifyUploadFileAsync(IUploadRequest uploadRequest) { try { IApiRequest request = await GenerateFileStreamRequest(uploadRequest.File, uploadRequest.Ticket, verifyOnly : true); IRestResponse response = await request.ExecuteRequestAsync(); var verify = new VerifyUploadResponse(); CheckStatusCodeError(uploadRequest, response, "Error verifying file upload.", (HttpStatusCode)308); if (response.StatusCode == HttpStatusCode.OK) { verify.BytesWritten = uploadRequest.FileLength; verify.Status = UploadStatusEnum.Completed; } else if (response.StatusCode == (HttpStatusCode)308) { verify.Status = UploadStatusEnum.InProgress; int startIndex = 0; int endIndex = 0; Parameter rangeHeader = response.Headers.FirstOrDefault(h => string.Compare(h.Name, "Range", true) == 0); if (rangeHeader != null && rangeHeader.Value != null) { Match match = RangeRegex.Match(rangeHeader.Value as string); if (match.Success && int.TryParse(match.Groups["start"].Value, out startIndex) && int.TryParse(match.Groups["end"].Value, out endIndex)) { verify.BytesWritten = endIndex - startIndex; if (verify.BytesWritten == uploadRequest.FileLength) { verify.Status = UploadStatusEnum.Completed; } } } } else { verify.Status = UploadStatusEnum.NotFound; } return(verify); } catch (Exception ex) { if (ex is VimeoApiException) { throw; } throw new VimeoUploadException("Error verifying file upload.", uploadRequest, ex); } }
static bool CheckPageRange(string p_pageRange) { if (!string.IsNullOrEmpty(p_pageRange)) { string[] strArray = p_pageRange.Split(new char[] { ',' }); if (strArray.Length <= 0) { return(false); } for (int i = 0; i < strArray.Length; i++) { string input = strArray[i].Trim(); if (!RangeRegex.IsMatch(input)) { return(false); } } } return(true); }
public static Range FromString(string input) { var match = RangeRegex.Match(input); return(new Range(Limit(match.Groups[1]), Limit(match.Groups[2]))); }
internal string GetNewTitle(Solution solution, string pattern, SettingsSet cfg) { Document activeDocument = null; Window activeWindow = null; try { activeDocument = Globals.DTE.ActiveDocument; } catch { // Do nothing } try { activeWindow = Globals.DTE.ActiveWindow; } catch { // Do nothing } var solutionFp = solution?.FullName; if (activeDocument == null && string.IsNullOrEmpty(solutionFp)) { if (activeWindow == null || activeWindow.Caption == Globals.DTE.MainWindow.Caption) { return(this.IDEName); } } string path; var documentName = Globals.GetActiveDocumentNameOrEmpty(activeDocument); var documentPath = Globals.GetActiveDocumentPathOrEmpty(activeDocument); var windowName = Globals.GetActiveWindowNameOrEmpty(activeWindow); if (!string.IsNullOrEmpty(solutionFp)) { path = solutionFp; } else { path = documentPath; } var pathParts = this.SplitPath(path); if (!string.IsNullOrEmpty(path)) { pathParts[0] = Path.GetPathRoot(path).Replace("\\", ""); } var documentPathParts = this.SplitPath(documentPath); if (!string.IsNullOrEmpty(documentPath)) { documentPathParts[0] = Path.GetPathRoot(documentPath).Replace("\\", ""); } pattern = this.TagRegex.Replace(pattern, match => { try { var tag = match.Groups[1].Value; try { switch (tag) { case "configurationName": return(Globals.GetActiveConfigurationNameOrEmpty(solution)); case "platformName": return(Globals.GetPlatformNameOrEmpty(solution)); case "projectName": return(Globals.GetActiveProjectNameOrEmpty()); case "solutionName": return(cfg.SolutionName ?? string.Empty); case "gitBranchName": Globals.UpdateGitExecFp(this.GlobalSettings.GitDirectory); // there is likely a better way to adjust the git path return(Globals.GetGitBranchNameOrEmpty(solution)); case "workspaceName": return(Globals.GetWorkspaceNameOrEmpty(solution)); case "workspaceOwnerName": return(Globals.GetWorkspaceOwnerNameOrEmpty(solution)); case "documentName": return(string.IsNullOrEmpty(documentName) ? windowName : documentName); case "documentProjectName": return(Globals.GetActiveDocumentProjectNameOrEmpty(activeDocument: activeDocument)); case "documentProjectFileName": return(Globals.GetActiveDocumentProjectFileNameOrEmpty(activeDocument: activeDocument)); case "documentPath": return(string.IsNullOrEmpty(documentName) ? windowName : documentPath); case "vsMajorVersion": return(Globals.VsMajorVersion.ToString(CultureInfo.InvariantCulture)); case "vsMajorVersionYear": return(Globals.VsMajorVersionYear.ToString(CultureInfo.InvariantCulture)); case "ideName": return(this.IDEName ?? string.Empty); case "path": return(string.IsNullOrEmpty(path) ? windowName : path); case "parentPath": return(GetParentPath(pathParts, cfg?.ClosestParentDepth ?? this.GlobalSettings.ClosestParentDepth, cfg?.FarthestParentDepth ?? this.GlobalSettings.FarthestParentDepth) ?? string.Empty); default: if (tag.StartsWith("parent")) { var m = RangeRegex.Match(tag.Substring("parent".Length)); if (m.Success) { if (!pathParts.Any()) { return(string.Empty); } var startIndex = Math.Min(pathParts.Length - 1, Math.Max(0, int.Parse(m.Groups["startIndex"].Value, CultureInfo.InvariantCulture))); var endIndex = Math.Min(pathParts.Length - 1, Math.Max(0, int.Parse(m.Groups["endIndex"].Value, CultureInfo.InvariantCulture))); var pathRange = pathParts.GetRange(startIndex: pathParts.Length - 1 - startIndex, endIndex: pathParts.Length - 1 - endIndex).ToArray(); return(GetPathForTitle(pathRange)); } m = IndexRegex.Match(tag.Substring("parent".Length)); if (m.Success) { if (!pathParts.Any()) { return(string.Empty); } var index = Math.Min(pathParts.Length - 1, Math.Max(0, int.Parse(m.Groups["index"].Value, CultureInfo.InvariantCulture))); return(pathParts[pathParts.Length - 1 - index]); } } if (tag.StartsWith("path")) { var m = RangeRegex.Match(tag.Substring("path".Length)); if (m.Success) { if (!pathParts.Any()) { return(string.Empty); } var startIndex = Math.Min(pathParts.Length - 1, Math.Max(0, int.Parse(m.Groups["startIndex"].Value, CultureInfo.InvariantCulture))); var endIndex = Math.Min(pathParts.Length - 1, Math.Max(0, int.Parse(m.Groups["endIndex"].Value, CultureInfo.InvariantCulture))); var pathRange = pathParts.GetRange(startIndex: startIndex, endIndex: endIndex).ToArray(); return(GetPathForTitle(pathRange)); } m = IndexRegex.Match(tag.Substring("path".Length)); if (m.Success) { if (!pathParts.Any()) { return(string.Empty); } var index = Math.Min(pathParts.Length - 1, Math.Max(0, int.Parse(m.Groups["index"].Value, CultureInfo.InvariantCulture))); return(pathParts[index]); } } if (tag.StartsWith("documentPath")) { var m = RangeRegex.Match(tag.Substring("documentPath".Length)); if (m.Success) { if (!documentPathParts.Any()) { return(string.Empty); } var startIndex = Math.Min(documentPathParts.Length - 1, Math.Max(0, int.Parse(m.Groups["startIndex"].Value, CultureInfo.InvariantCulture))); var endIndex = Math.Min(documentPathParts.Length - 1, Math.Max(0, int.Parse(m.Groups["endIndex"].Value, CultureInfo.InvariantCulture))); var pathRange = documentPathParts.GetRange(startIndex: startIndex, endIndex: endIndex).ToArray(); return(GetPathForTitle(pathRange)); } m = IndexRegex.Match(tag.Substring("documentPath".Length)); if (m.Success) { if (!documentPathParts.Any()) { return(string.Empty); } var index = Math.Min(documentPathParts.Length - 1, Math.Max(0, int.Parse(m.Groups["index"].Value, CultureInfo.InvariantCulture))); return(documentPathParts[index]); } } if (tag.StartsWith("documentParentPath")) { var m = RangeRegex.Match(tag.Substring("documentParentPath".Length)); if (m.Success) { if (!documentPathParts.Any()) { return(string.Empty); } var startIndex = Math.Min(documentPathParts.Length - 1, Math.Max(0, int.Parse(m.Groups["startIndex"].Value, CultureInfo.InvariantCulture))); var endIndex = Math.Min(documentPathParts.Length - 1, Math.Max(0, int.Parse(m.Groups["endIndex"].Value, CultureInfo.InvariantCulture))); var pathRange = documentPathParts.GetRange(startIndex: documentPathParts.Length - 1 - startIndex, endIndex: documentPathParts.Length - 1 - endIndex).ToArray(); return(GetPathForTitle(pathRange)); } m = IndexRegex.Match(tag.Substring("documentParentPath".Length)); if (m.Success) { if (!documentPathParts.Any()) { return(string.Empty); } var index = Math.Min(documentPathParts.Length - 1, Math.Max(0, int.Parse(m.Groups["index"].Value, CultureInfo.InvariantCulture))); return(documentPathParts[documentPathParts.Length - 1 - index]); } } break; } return(match.Value); } catch (Exception ex) { if (this.GlobalSettings.EnableDebugMode) { WriteOutput("ReplaceTag (" + tag + ") failed: " + ex); } throw; } } catch { return(""); } }); var appendedString = cfg?.AppendedString ?? this.GlobalSettings.AppendedString; return(pattern + " " + appendedString); }
/// <summary> /// 获取PrintInfo中设置的页面范围 /// </summary> /// <returns></returns> List <int> GetPageRange() { string pageRange = _info.PageRange; if (string.IsNullOrEmpty(pageRange)) { return(null); } if (!CheckPageRange(pageRange)) { return(null); } List <int> list = new List <int>(); string[] strArray = pageRange.Split(new char[] { ',' }); for (int i = 0; i < strArray.Length; i++) { string str = strArray[i].Trim(); if (string.IsNullOrEmpty(str)) { continue; } Match match = RangeRegex.Match(str); int start = -1; int end = -1; if (match.Groups[_rangeRegexStart].Success && !string.IsNullOrEmpty(match.Groups[_rangeRegexStart].Value)) { try { start = int.Parse(match.Groups[_rangeRegexStart].Value); } catch { continue; } } if (match.Groups[_rangeRegexEnd].Success && !string.IsNullOrEmpty(match.Groups[_rangeRegexEnd].Value)) { try { end = int.Parse(match.Groups[_rangeRegexEnd].Value); } catch { continue; } } if (str.IndexOf('-') >= 0) { int num4 = (end >= start) ? 1 : -1; for (int j = start; j != end; j += num4) { list.Add(j); } list.Add(end); } else if (start > 0) { list.Add(start); } } return(list); }