public void PastingInLine() { string original = "foo=function"; PasteInfo paste = new PasteInfo("(x,y,z) end", 12, 0); string expected = "foo=function( x, y, z ) end"; PasteTest(original, paste, expected); }
public void Basic() { string original = ""; PasteInfo paste = new PasteInfo("foo=function(x) end", 0, 0); string expected = "foo = function ( x ) end"; PasteTest(original, paste, expected); }
public void EmptyPasteOnEmptyBuffer() { string original = ""; PasteInfo paste = new PasteInfo("", 0, 0); string expected = ""; PasteTest(original, paste, expected); }
internal static string FormatOnPaste(string original, PasteInfo pasteInfo) { var buffer = host.CreateTextBuffer(original); var prePastSnapshot = buffer.CurrentSnapshot; var bufferEdit = buffer.CreateEdit(); bufferEdit.Replace(pasteInfo.Start, pasteInfo.Length, pasteInfo.PasteString); var bufferApplied = bufferEdit.Apply(); SnapshotSpan? span = EditorUtilities.GetPasteSpan(prePastSnapshot, bufferApplied); if (span != null) { SnapshotSpan newSpan = (SnapshotSpan)span; var featureContainer = new LuaFeatureContainer(); SourceText sourceText = new SourceText(bufferApplied.GetText()); Range range = new Range(newSpan.Start.Position, newSpan.Length); List<TextEditInfo> edits = featureContainer.Formatter.Format(sourceText, range, new FormattingOptions(new List<DisableableRules>(), 4, 4, false)); var pastedBufferEdit = buffer.CreateEdit(); foreach (TextEditInfo edit in edits) { pastedBufferEdit.Replace(edit.Start, edit.Length, edit.ReplacingWith); } var pasteApplied = pastedBufferEdit.Apply(); return pasteApplied.GetText(); } return original; }
internal static string FormatOnPaste(string original, PasteInfo pasteInfo) { var buffer = host.CreateTextBuffer(original); var prePastSnapshot = buffer.CurrentSnapshot; var bufferEdit = buffer.CreateEdit(); bufferEdit.Replace(pasteInfo.Start, pasteInfo.Length, pasteInfo.PasteString); var bufferApplied = bufferEdit.Apply(); SnapshotSpan?span = EditorUtilities.GetPasteSpan(prePastSnapshot, bufferApplied); if (span != null) { SnapshotSpan newSpan = (SnapshotSpan)span; var featureContainer = new LuaFeatureContainer(); SourceText sourceText = new SourceText(bufferApplied.GetText()); Range range = new Range(newSpan.Start.Position, newSpan.Length); List <TextEditInfo> edits = featureContainer.Formatter.Format(sourceText, range, new FormattingOptions(new List <DisableableRules>(), 4, 4, false)); var pastedBufferEdit = buffer.CreateEdit(); foreach (TextEditInfo edit in edits) { pastedBufferEdit.Replace(edit.Start, edit.Length, edit.ReplacingWith); } var pasteApplied = pastedBufferEdit.Apply(); return(pasteApplied.GetText()); } return(original); }
public async Task <PasteInfo> GetAsync(string id) { PasteInfo response = await this.Pastebin.GetAsync(id); response.Content = this.DecompressString(response.Content); return(response); }
public void PasteInBetweenLetters() { string original = "xy"; PasteInfo paste = new PasteInfo("= x/y *", 1, 0); string expected = "x= x / y * y"; PasteTest(original, paste, expected); }
public void PasteOverMultipleLines() { string original = @"x = 10 y = 30 z = x + y"; PasteInfo paste = new PasteInfo("print(\"hello world\")", 0, original.Length); string expected = "print ( \"hello world\" )"; PasteTest(original, paste, expected); }
public void PasteMultipleLines() { string original = @"foo= "; PasteInfo paste = new PasteInfo(@"x+1 x=y+1", 6, 0); string expected = @"foo= x + 1 x = y + 1"; PasteTest(original, paste, expected); }
public void PasteMultipleLinesOverMultipleLines() { string original = @"x = 10 y = 30 z=x+y"; PasteInfo paste = new PasteInfo(@"x = x+y y = y + x", 0, 14); string expected = @"x = x + y y = y + x z=x+y"; PasteTest(original, paste, expected); }
public async Task <ViewResult> Index(string id = null, bool raw = false) { // fresh page if (string.IsNullOrWhiteSpace(id)) { return(this.View("Index", this.GetModel(id))); } // log page PasteInfo paste = await this.GetAsync(id); ParsedLog log = paste.Success ? new LogParser().Parse(paste.Content) : new ParsedLog { IsValid = false, Error = "Pastebin error: " + paste.Error }; return(this.View("Index", this.GetModel(id).SetResult(log, raw))); }
/// <summary> /// Delete user`s paste /// </summary> /// <param name="pasteInfo">Paste info. Require field <seealso cref="PasteInfo.Key"/></param> public async Task <string> DeletePaste(PasteInfo pasteInfo) { var url = new Uri("https://pastebin.com/api/api_post.php"); var content = new FormUrlEncodedContent(new[] { new KeyValuePair <string, string>("api_option", "delete"), new KeyValuePair <string, string>("api_user_key", UserApiKey), new KeyValuePair <string, string>("api_dev_key", DeveloperApiKey), new KeyValuePair <string, string>("api_paste_key", pasteInfo.Key) }); var result = WebAgent.Execute(url, content).Result; if (result.IsSuccessStatusCode) { return(await result.Content.ReadAsStringAsync().ConfigureAwait(false)); } throw new HttpRequestException("Something went wrong"); }
/// <summary> /// Create new paste as user /// </summary> /// <param name="pasteInfo">Paste information. Required fields: <seealso cref="PasteInfo.Private"/>, <see cref="PasteInfo.Name"/>, /// <seealso cref="PasteInfo.ExpireDate"/>, <seealso cref="PasteInfo.Language"/>, <seealso cref="PasteInfo.Code"/></param> /// <returns>Paste information <seealso cref="PasteInfo"/></returns> public async Task <PasteInfo> CreateNewPasteAsUserAsync(PasteInfo pasteInfo, string userApiKey) { var baseAddress = new Uri("https://pastebin.com/api/api_post.php"); var content = new FormUrlEncodedContent(new[] { new KeyValuePair <string, string>("api_option", "paste"), new KeyValuePair <string, string>("api_user_key", userApiKey), new KeyValuePair <string, string>("api_paste_private", ((int)pasteInfo.Private).ToString()), new KeyValuePair <string, string>("api_paste_name", pasteInfo.Name), new KeyValuePair <string, string>("api_paste_expire_date", ConvertPasteExpireDateToString(pasteInfo.ExpireDate)), new KeyValuePair <string, string>("api_paste_format", Enum.GetName(typeof(PasteLanguage), pasteInfo.Language)), new KeyValuePair <string, string>("api_dev_key", DeveloperApiKey), new KeyValuePair <string, string>("api_paste_code", pasteInfo.Code) }); var result = WebAgent.Execute(baseAddress, content).Result; if (result.IsSuccessStatusCode) { pasteInfo.Link = await result.Content.ReadAsStringAsync().ConfigureAwait(false); } return(pasteInfo); }
/// <inheritdoc /> public async Task <StoredFileInfo> GetAsync(string id, bool renew) { // fetch from blob storage if (Guid.TryParseExact(id, "N", out Guid _)) { // Azure Blob storage if (this.HasAzure) { try { // get client BlobClient blob = this.GetAzureBlobClient(id); // extend expiry if (renew) { await blob.SetMetadataAsync(new Dictionary <string, string> { ["expiryRenewed"] = DateTime.UtcNow.ToString("O") }); // change the blob's last-modified date (the specific property set doesn't matter) } // fetch file Response <BlobDownloadInfo> response = await blob.DownloadAsync(); using BlobDownloadInfo result = response.Value; using StreamReader reader = new StreamReader(result.Content); DateTimeOffset expiry = result.Details.LastModified + TimeSpan.FromDays(this.ExpiryDays); string content = this.GzipHelper.DecompressString(reader.ReadToEnd()); // build model return(new StoredFileInfo { Success = true, Content = content, Expiry = expiry.UtcDateTime }); } catch (RequestFailedException ex) { return(new StoredFileInfo { Error = ex.ErrorCode == "BlobNotFound" ? "There's no file with that ID." : $"Could not fetch that file from storage ({ex.ErrorCode}: {ex.Message})." }); } } // local filesystem for testing else { // get file FileInfo file = new FileInfo(this.GetDevFilePath(id)); if (file.Exists && file.LastWriteTimeUtc.AddDays(this.ExpiryDays) < DateTime.UtcNow) // expired { file.Delete(); } if (!file.Exists) { return(new StoredFileInfo { Error = "There's no file with that ID." }); } // renew if (renew) { File.SetLastWriteTimeUtc(file.FullName, DateTime.UtcNow); file.Refresh(); } // build model return(new StoredFileInfo { Success = true, Content = File.ReadAllText(file.FullName), Expiry = DateTime.UtcNow.AddDays(this.ExpiryDays), Warning = "This file was saved temporarily to the local computer. This should only happen in a local development environment." }); } } // get from Pastebin else { PasteInfo response = await this.Pastebin.GetAsync(id); response.Content = this.GzipHelper.DecompressString(response.Content); return(new StoredFileInfo { Success = response.Success, Content = response.Content, Error = response.Error }); } }
/// <summary> /// Create new paste as guest /// </summary> /// <param name="pasteInfo">Paste information. Required fields: <seealso cref="PasteInfo.Private"/>, <see cref="PasteInfo.Name"/>, /// <seealso cref="PasteInfo.ExpireDate"/>, <seealso cref="PasteInfo.Language"/>, <seealso cref="PasteInfo.Code"/></param> /// <returns>Paste information <seealso cref="PasteInfo"/></returns> public async Task <PasteInfo> CreateNewPasteAsGuestAsync(PasteInfo pasteInfo) { return(await CreateNewPasteAsUserAsync(pasteInfo, "").ConfigureAwait(false)); }
private static void PasteTest(string original, PasteInfo pasteInfo, string expected) { string actual = Tester.FormatOnPaste(original, pasteInfo); Assert.Equal(expected, actual); }
/// <summary>Fetch raw text from storage.</summary> /// <param name="id">The storage ID returned by <see cref="SaveAsync"/>.</param> public async Task <StoredFileInfo> GetAsync(string id) { // fetch from blob storage if (Guid.TryParseExact(id, "N", out Guid _)) { // Azure Blob storage if (this.HasAzure) { try { BlobClient blob = this.GetAzureBlobClient(id); Response <BlobDownloadInfo> response = await blob.DownloadAsync(); using BlobDownloadInfo result = response.Value; using StreamReader reader = new StreamReader(result.Content); DateTimeOffset expiry = result.Details.LastModified + TimeSpan.FromDays(this.ExpiryDays); string content = this.GzipHelper.DecompressString(reader.ReadToEnd()); return(new StoredFileInfo { Success = true, Content = content, Expiry = expiry.UtcDateTime }); } catch (RequestFailedException ex) { return(new StoredFileInfo { Error = ex.ErrorCode == "BlobNotFound" ? "There's no file with that ID." : $"Could not fetch that file from storage ({ex.ErrorCode}: {ex.Message})." }); } } // local filesystem for testing else { FileInfo file = new FileInfo(this.GetDevFilePath(id)); if (file.Exists) { if (file.LastWriteTimeUtc.AddDays(this.ExpiryDays) < DateTime.UtcNow) { file.Delete(); } else { return(new StoredFileInfo { Success = true, Content = File.ReadAllText(file.FullName), Expiry = DateTime.UtcNow.AddDays(this.ExpiryDays), Warning = "This file was saved temporarily to the local computer. This should only happen in a local development environment." }); } } return(new StoredFileInfo { Error = "There's no file with that ID." }); } } // get from Pastebin else { PasteInfo response = await this.Pastebin.GetAsync(id); response.Content = this.GzipHelper.DecompressString(response.Content); return(new StoredFileInfo { Success = response.Success, Content = response.Content, Error = response.Error }); } }
public async Task <ViewResult> Index(string schemaName = null, string id = null) { schemaName = this.NormalizeSchemaName(schemaName); var result = new JsonValidatorModel(this.SectionUrl, id, schemaName, this.SchemaFormats); if (string.IsNullOrWhiteSpace(id)) { return(this.View("Index", result)); } // fetch raw JSON PasteInfo paste = await this.GetAsync(id); if (string.IsNullOrWhiteSpace(paste.Content)) { return(this.View("Index", result.SetUploadError("The JSON file seems to be empty."))); } result.SetContent(paste.Content); // parse JSON JToken parsed; try { parsed = JToken.Parse(paste.Content, new JsonLoadSettings { DuplicatePropertyNameHandling = DuplicatePropertyNameHandling.Error }); } catch (JsonReaderException ex) { return(this.View("Index", result.AddErrors(new JsonValidatorErrorModel(ex.LineNumber, ex.Path, ex.Message, ErrorType.None)))); } // format JSON result.SetContent(parsed.ToString(Formatting.Indented)); // skip if no schema selected if (schemaName == "none") { return(this.View("Index", result)); } // load schema JSchema schema; { FileInfo schemaFile = this.FindSchemaFile(schemaName); if (schemaFile == null) { return(this.View("Index", result.SetParseError($"Invalid schema '{schemaName}'."))); } schema = JSchema.Parse(System.IO.File.ReadAllText(schemaFile.FullName)); } // get format doc URL result.FormatUrl = this.GetExtensionField <string>(schema, "@documentationUrl"); // validate JSON parsed.IsValid(schema, out IList <ValidationError> rawErrors); var errors = rawErrors .SelectMany(this.GetErrorModels) .ToArray(); return(this.View("Index", result.AddErrors(errors))); }