private static void NoCompilerErrors(IReadOnlyList <ImmutableArray <Diagnostic> > diagnostics, IReadOnlyList <string> allowedIds, AllowedDiagnostics allowedDiagnostics) { var introducedDiagnostics = diagnostics .SelectMany(x => x) .Where(x => IsIncluded(x, allowedDiagnostics)) .Where(x => !IsExcluded(x)) .ToArray(); if (introducedDiagnostics.Select(x => x.Id) .Except(allowedIds ?? Enumerable.Empty <string>()) .Any()) { var error = StringBuilderPool.Borrow(); error.AppendLine($"Found error{(introducedDiagnostics.Length > 1 ? "s" : string.Empty)}."); foreach (var introducedDiagnostic in introducedDiagnostics) { error.AppendLine($"{introducedDiagnostic.ToErrorString()}"); } throw new AssertException(StringBuilderPool.Return(error)); } bool IsExcluded(Diagnostic diagnostic) { if (allowedIds.Contains(diagnostic.Id)) { return(true); } return(diagnostic.Id switch { "CS1061" when diagnostic.GetMessage(CultureInfo.InvariantCulture).Contains("does not contain a definition for 'InitializeComponent' and no accessible extension method 'InitializeComponent' accepting a first argument of type") => true, _ => false, }); }
private static string GetInnerException(Exception exception, int remainingLength, int remainingAllowedRecursionDepth) { if (remainingAllowedRecursionDepth < 1) { return(null); } StringBuilder sb = StringBuilderPool.Take(); try { using (StringWriter stringWriter = new StringWriter(sb, CultureInfo.CurrentCulture)) { using (XmlWriter xml = XmlWriter.Create(stringWriter)) { if (!WriteStartElement(xml, DiagnosticStrings.InnerExceptionTag, ref remainingLength)) { return(null); } WriteExceptionToTraceString(xml, exception.InnerException, remainingLength, remainingAllowedRecursionDepth); xml.WriteEndElement(); xml.Flush(); stringWriter.Flush(); return(sb.ToString()); } } } finally { StringBuilderPool.Return(sb); } }
/// <summary>Gets a text content of the specified file</summary> /// <param name="virtualPath">The path to the virtual file</param> /// <returns>Text content</returns> public string GetFileTextContent(string virtualPath) { StringBuilderPool shared = StringBuilderPool.Shared; StringBuilder builder = shared.Rent(); try { using (StreamReader streamReader = new StreamReader(BundleTable.VirtualPathProvider.GetFile(virtualPath).Open())) { while (streamReader.Peek() >= 0) { builder.AppendLine(streamReader.ReadLine()); } } return(builder.ToString()); } catch (FileNotFoundException ex) { throw new FileNotFoundException(string.Format(Strings.Common_FileNotExist, (object)virtualPath), virtualPath, (Exception)ex); } finally { shared.Return(builder); } }
public static ICharIterator ColorFormat( ICharIterator input, BitmapFont font, bool keepSequences, byte baseAlpha, IReferenceList <Color?> output) { if (input == null) { throw new ArgumentNullException(nameof(input)); } if (font == null) { throw new ArgumentNullException(nameof(font)); } if (input.Length == 0) { return(input); } var builder = StringBuilderPool.Rent(input.Length); ColorFormat(input, builder, font, keepSequences, baseAlpha, output); var iterator = CharIteratorPool.Rent(builder, 0, builder.Length); StringBuilderPool.Return(builder); return(iterator); }
public void TextTest(string input) { StringBuilder sb = StringBuilderPool.Rent(input); Assert.Equal(input, sb.ToString()); StringBuilderPool.Return(sb); }
protected override string CombineAssetContent(IList <IAsset> assets) { StringBuilderPool shared = StringBuilderPool.Shared; StringBuilder stringBuilder = shared.Rent(); int count = assets.Count; int num = count - 1; for (int index = 0; index < count; ++index) { IAsset asset = assets[index]; string str = asset.Content.TrimEnd(); if (this.EnableTracing) { stringBuilder.AppendFormatLine("//#region URL: {0}", (object)asset.Url); } stringBuilder.Append(str); if (!str.EndsWith(";")) { stringBuilder.Append(";"); } if (this.EnableTracing) { stringBuilder.AppendLine(); stringBuilder.AppendLine("//#endregion"); } if (index != num) { stringBuilder.AppendLine(); } } string str1 = stringBuilder.ToString(); shared.Return(stringBuilder); return(str1); }
/// <summary>Displays trace information</summary> /// <param name="context">Object BundleContext</param> /// <param name="response">Object BundleResponse</param> public void Process(BundleContext context, BundleResponse response) { StringBuilderPool shared = StringBuilderPool.Shared; StringBuilder stringBuilder = shared.Rent(); stringBuilder.AppendLine("*************************************************************************************"); stringBuilder.AppendLine("* BUNDLE RESPONSE *"); stringBuilder.AppendLine("*************************************************************************************"); foreach (BundleFile file in response.Files) { stringBuilder.AppendLine(" " + file.IncludedVirtualPath); } stringBuilder.AppendLine(); stringBuilder.AppendLine("*************************************************************************************"); stringBuilder.AppendLine("* BUNDLE COLLECTION *"); stringBuilder.AppendLine("*************************************************************************************"); foreach (Bundle bundle in (IEnumerable <Bundle>)context.BundleCollection) { stringBuilder.AppendFormatLine("-= {0} =-", (object)bundle.Path); foreach (BundleFile enumerateFile in bundle.EnumerateFiles(context)) { stringBuilder.AppendLine(" " + enumerateFile.IncludedVirtualPath); } stringBuilder.AppendLine(); } string str = stringBuilder.ToString(); shared.Return(stringBuilder); response.ContentType = "text/plain"; response.Content = str; }
/// <summary> /// Check the solution for compiler errors and warnings, uses: /// </summary> public static async Task NoCompilerErrorsAsync(Solution solution, IReadOnlyList <string> allowedIds, AllowedDiagnostics allowedDiagnostics) { var diagnostics = await Analyze.GetDiagnosticsAsync(solution).ConfigureAwait(false); var introducedDiagnostics = diagnostics .SelectMany(x => x) .Where(x => IsIncluded(x, allowedDiagnostics)) .ToArray(); if (introducedDiagnostics.Select(x => x.Id) .Except(allowedIds ?? Enumerable.Empty <string>()) .Any()) { var error = StringBuilderPool.Borrow(); error.AppendLine($"Found error{(introducedDiagnostics.Length > 1 ? "s" : string.Empty)}."); foreach (var introducedDiagnostic in introducedDiagnostics) { var errorInfo = await introducedDiagnostic.ToStringAsync(solution).ConfigureAwait(false); error.AppendLine($"{errorInfo}"); } throw AssertException.Create(StringBuilderPool.Return(error)); } }
public async Task <string> ReadLineAsync() { if (!hasCheckedForPreamble) { await ReadPreambleAsync().ConfigureAwait(false); } var builder = StringBuilderPool.Get(); while (await ReadNextCharsAsync().ConfigureAwait(false)) { if (ProcessCharsForLine(builder)) { break; } } if (charBuffer == null && builder.Length == 0) { StringBuilderPool.Return(builder); return(null); } return(ProcessLine(StringBuilderPool.GetStringAndReturn(builder))); }
protected override TextSegment.GlyphCallbackResult GlyphCallback(ICharIterator source) { if (_isObscured) { return(new TextSegment.GlyphCallbackResult(_obscureChar.ToRepeatingIterator(source.Length), leaveOpen: false)); } if (!_isMultiLined) { var builder = StringBuilderPool.Rent(source.Length); for (int i = 0; i < source.Length; i++) { char current = source.GetCharacter16(i); if (current != '\n') { builder.Append(current); } } var iter = builder.ToIterator(); StringBuilderPool.Return(builder); return(new TextSegment.GlyphCallbackResult(iter, leaveOpen: false)); } return(base.GlyphCallback(source)); }
public string ToString(string format, IFormatProvider formatProvider) { var request = Context.Request; switch (format) { case "all": var buffer = StringBuilderPool.GetOut(); buffer.Append(request.HttpMethod); buffer.Append(" "); buffer.Append(request.Url); buffer.Append(" "); buffer.AppendLine(request.RequestType); var headers = request.Headers; foreach (var key in headers.AllKeys) { foreach (var value in headers.GetValues(key)) { buffer.Append(key); buffer.Append(":"); buffer.AppendLine(value); } } buffer.AppendLine(); buffer.Append((request.ContentType.GetEncoding() ?? Encoding.Default).GetString(Body)); return(StringBuilderPool.Return(buffer)); case "body": case null: default: return((request.ContentType.GetEncoding() ?? Encoding.Default).GetString(Body)); } }
static string GetExceptionData(Exception exception) { StringBuilder sb = StringBuilderPool.Take(); try { using (StringWriter stringWriter = new StringWriter(sb, CultureInfo.CurrentCulture)) { using (XmlTextWriter xml = new XmlTextWriter(stringWriter)) { xml.WriteStartElement(DiagnosticStrings.DataItemsTag); foreach (object dataItem in exception.Data.Keys) { xml.WriteStartElement(DiagnosticStrings.DataTag); xml.WriteElementString(DiagnosticStrings.KeyTag, XmlEncode(dataItem.ToString())); xml.WriteElementString(DiagnosticStrings.ValueTag, XmlEncode(exception.Data[dataItem].ToString())); xml.WriteEndElement(); } xml.WriteEndElement(); xml.Flush(); stringWriter.Flush(); return(sb.ToString()); } } } finally { StringBuilderPool.Return(sb); } }
public string GetString() { if (_sprites == null) { throw new System.Exception(); } if (_cachedString == null) { var builder = StringBuilderPool.Rent(Length); Span <char> charBuffer = stackalloc char[2]; for (int i = 0; i < Length; i++) { int utf32 = _sprites[i].Character; int count = TextFormat.ConvertFromUtf32(utf32, charBuffer); for (int j = 0; j < count; j++) { builder.Append(charBuffer[j]); } } _cachedString = builder.ToString(); StringBuilderPool.Return(builder); } return(_cachedString); }
public static string HashPath(string path) { var md5 = new MD5CryptoServiceProvider(); var ret = md5.ComputeHash(Encoding.UTF8.GetBytes(path)); var builder = StringBuilderPool.Get(); foreach (var b in ret) { builder.Append(b.ToString("x2")); } var str = builder.ToString(); StringBuilderPool.Return(builder); builder = StringBuilderPool.Get(); builder.Append(str.Substring(0, 2)); builder.Append("/"); builder.Append(str.Substring(2, 2)); builder.Append("/"); builder.Append(str); var hashed = builder.ToString(); StringBuilderPool.Return(builder); return(hashed); }
public void CapacityTest(int capacity) { StringBuilder sb = StringBuilderPool.Rent(capacity); Assert.True(sb.Capacity >= capacity); StringBuilderPool.Return(sb); }
public static string GetPathFrom(Transform t, Transform root) { if (t == null) { return(null); } if (t == root) { return(""); } string path = null; StringBuilder b = null; try { b = GetPathFrom(t, root, b); path = b.ToString(); } finally { if (b != null) { StringBuilderPool.Return(b); } } return(path); }
/// <summary> /// Gets the path for a Transform from the root, e.g. '/root/parent/mytransform' /// </summary> public static string GetPath(Transform t) { if (t == null) { return(null); } string path = null; StringBuilder b = null; try { b = StringBuilderPool.Get(); b = GetPathFrom(t, null, b); if (b[0] != '/') { b.Insert(0, "/"); } path = b.ToString(); } finally { if (b != null) { StringBuilderPool.Return(b); } } return(path); }
public string ToString(string format, IFormatProvider formatProvider) { var request = OwinContext.Request; switch (format) { case "all": var buffer = StringBuilderPool.GetOut(); buffer.Append(request.Method); buffer.Append(" "); buffer.Append(request.Uri); buffer.Append(" "); buffer.AppendLine(request.Protocol); foreach (var header in request.Headers) { foreach (var value in header.Value) { buffer.Append(header.Key); buffer.Append(":"); buffer.AppendLine(value); } } buffer.AppendLine(); buffer.Append((request.ContentType.GetEncoding() ?? Encoding.Default).GetString(Body)); return(StringBuilderPool.Return(buffer)); case "body": case null: default: return((request.ContentType.GetEncoding() ?? Encoding.Default).GetString(Body)); } }
public void ValidTest() { StringBuilder sb = StringBuilderPool.Rent(); Assert.NotNull(sb); Assert.True(sb.Length == 0); StringBuilderPool.Return(sb); }
private void ProcessRemoval(StringBuilder builder, int removals) { if (removals > 0) { using (var iter = builder.ToIterator()) SetText(_font, iter, _usedColorFormat); StringBuilderPool.Return(builder); } }
public void RenderMainText(BitmapFont font, Color color, Vector2 scale, int maxWidthInChars) { var builder = StringBuilderPool.Rent(Data.Title.Length + 5); DivideTextIntoLines(Data.Title, builder, maxWidthInChars); CachedMainText.Clear(); MainTextSize = font.GetGlyphSprites( CachedMainText, builder, Vector2.Zero, color, 0, Vector2.Zero, scale, 0, null); StringBuilderPool.Return(builder); }
/// <summary> /// Gets the line indicated by <paramref name="position"/> and inserts ↓ before the character. /// </summary> /// <param name="code">The code to parse.</param> /// <param name="position">The error position.</param> /// <returns>A string with the line with error indicated.</returns> public static string GetLineWithErrorIndicated(string code, LinePosition position) { var builder = StringBuilderPool.Borrow(); var line = 0; var character = 0; foreach (var c in code) { if (c == '\r') { continue; } if (c == '\n') { if (!builder.IsEmpty) { return(builder.Return()); } line++; character = 0; continue; } if (line == position.Line) { if (character == position.Character) { builder.Append('↓'); } builder.Append(c); } character++; } if (!builder.IsEmpty) { if (position.Character == builder.Length) { builder.Append('↓'); } return(builder.Return()); } StringBuilderPool.Return(builder); return($"Code dod not have position {position}"); }
/// <summary> /// Build CSS class string from boolean properties of objects in arguments, from strings in arguments. /// </summary> public static string CssClass(params object[] args) { var builder = StringBuilderPool.Get(); try { var _1st = true; foreach (var arg in args) { if (arg is string s) { if (!_1st) { builder.Append(' '); } _1st = false; builder.Append(s); } else if (arg is Enum e) { if (!_1st) { builder.Append(' '); } _1st = false; builder.Append(GetHyphenatedName(e.ToString())); } else { foreach (var(name, getter) in GetPropEntriesFromCache(arg)) { if ((bool)getter.Invoke(arg, null)) { if (!_1st) { builder.Append(' '); } _1st = false; builder.Append(name); } } } } return(builder.ToString()); } finally { StringBuilderPool.Return(builder); } }
public static string ToHex(this Color color) { var builder = StringBuilderPool.Rent(8); builder.AppendFormat("{0:x2}", color.R); builder.AppendFormat("{0:x2}", color.G); builder.AppendFormat("{0:x2}", color.B); builder.AppendFormat("{0:x2}", color.A); string result = builder.ToString(); StringBuilderPool.Return(builder); return(result); }
public string GetString() { AssertIsInUse(); if (_cachedString == null) { var builder = StringBuilderPool.Rent(Length); builder.AppendIterator(this); _cachedString = builder.ToString(); StringBuilderPool.Return(builder); } return(_cachedString); }
public TracePayload GetSerializedPayload(object source, TraceRecord traceRecord, Exception exception, bool getServiceReference) { string eventSource = null; string extendedData = null; string serializedException = null; if (source != null) { eventSource = CreateSourceString(source); } if (traceRecord != null) { StringBuilder sb = StringBuilderPool.Take(); try { using (StringWriter stringWriter = new StringWriter(sb, CultureInfo.CurrentCulture)) { using (XmlTextWriter writer = new XmlTextWriter(stringWriter)) { writer.WriteStartElement(DiagnosticStrings.ExtendedDataTag); traceRecord.WriteTo(writer); writer.WriteEndElement(); writer.Flush(); stringWriter.Flush(); extendedData = sb.ToString(); } } } finally { StringBuilderPool.Return(sb); } } if (exception != null) { // We want to keep the ETW trace message to under 32k. So we keep the serialized exception to under 28k bytes. serializedException = ExceptionToTraceString(exception, MaxExceptionStringLength); } if (getServiceReference && (EtwDiagnosticTrace.traceAnnotation != null)) { return(new TracePayload(serializedException, eventSource, DiagnosticTraceBase.AppDomainFriendlyName, extendedData, EtwDiagnosticTrace.traceAnnotation())); } return(new TracePayload(serializedException, eventSource, DiagnosticTraceBase.AppDomainFriendlyName, extendedData, string.Empty)); }
/// <inheritdoc/> public override byte[] Serialize <T>(T value) { var serializer = _cache.GetSerializer(value.GetType()); var buffer = StringBuilderPool.Lease(); using (var stringWriter = new StringWriter(buffer)) { var writer = new SimpleJsonWriter(stringWriter); serializer.Serialize(value, writer); var bytes = Encoding.UTF8.GetBytes(buffer.ToString()); StringBuilderPool.Return(buffer); return(bytes); } }
static string BuildTrace(ref EventDescriptor eventDescriptor, string description, TracePayload payload, string msdnTraceCode) { StringBuilder sb = StringBuilderPool.Take(); try { using (StringWriter stringWriter = new StringWriter(sb, CultureInfo.CurrentCulture)) { using (XmlTextWriter writer = new XmlTextWriter(stringWriter)) { writer.WriteStartElement(DiagnosticStrings.TraceRecordTag); writer.WriteAttributeString(DiagnosticStrings.NamespaceTag, EtwDiagnosticTrace.TraceRecordVersion); writer.WriteAttributeString(DiagnosticStrings.SeverityTag, TraceLevelHelper.LookupSeverity((TraceEventLevel)eventDescriptor.Level, (TraceEventOpcode)eventDescriptor.Opcode)); writer.WriteAttributeString(DiagnosticStrings.ChannelTag, EtwDiagnosticTrace.LookupChannel((TraceChannel)eventDescriptor.Channel)); writer.WriteElementString(DiagnosticStrings.TraceCodeTag, msdnTraceCode); writer.WriteElementString(DiagnosticStrings.DescriptionTag, description); writer.WriteElementString(DiagnosticStrings.AppDomain, payload.AppDomainFriendlyName); if (!string.IsNullOrEmpty(payload.EventSource)) { writer.WriteElementString(DiagnosticStrings.SourceTag, payload.EventSource); } if (!string.IsNullOrEmpty(payload.ExtendedData)) { writer.WriteRaw(payload.ExtendedData); } if (!string.IsNullOrEmpty(payload.SerializedException)) { writer.WriteRaw(payload.SerializedException); } writer.WriteEndElement(); writer.Flush(); stringWriter.Flush(); return(sb.ToString()); } } } finally { StringBuilderPool.Return(sb); } }
private static CodeAction FindAction(IReadOnlyList <CodeAction> actions, string fixTitle) { if (fixTitle == null) { if (actions.TrySingle(out var action)) { return(action); } if (actions.Count == 0) { throw new AssertException("Expected one code fix, was 0."); } throw new AssertException($"Expected only one code fix, found {actions.Count}:\r\n" + $"{string.Join("\r\n", actions.Select(x => x.Title))}\r\n" + "Use the overload that specifies title."); } else { if (actions.TrySingle(x => x.Title == fixTitle, out var action)) { return(action); } if (actions.All(x => x.Title != fixTitle)) { var errorBuilder = StringBuilderPool.Borrow(); errorBuilder.AppendLine($"Did not find a code fix with title {fixTitle}.").AppendLine("Found:"); foreach (var codeAction in actions) { errorBuilder.AppendLine(codeAction.Title); } throw new AssertException(StringBuilderPool.Return(errorBuilder)); } if (actions.Count(x => x.Title == fixTitle) == 0) { throw new AssertException("Expected one code fix, was 0."); } throw new AssertException($"Expected only one code fix, found {actions.Count}:\r\n" + $"{string.Join("\r\n", actions.Select(x => x.Title))}\r\n" + "Use the overload that specifies title."); } }
protected override void LoadAssetAtPathInternal(string path, Type type) { var resPath = PathUtility.RelativeProjectPathToRelativeResourcesPath(path); var sb = StringBuilderPool.Get(); sb.Append(Path.GetDirectoryName(resPath)); sb.Append("/"); sb.Append(Path.GetFileNameWithoutExtension(resPath)); _request = Resources.LoadAsync(sb.ToString(), type); if (_request == null) { throw new BundleAssetLoadFailedException( string.Format("Cannot load asset {0} from resources: ", sb)); } StringBuilderPool.Return(sb); }