private async Task RunCommandAsync(FormatFlags formatFlags, params string[] args) { // Validation. ArgUtil.NotNull(args, nameof(args)); ArgUtil.NotNull(ExecutionContext, nameof(ExecutionContext)); // Invoke tf. using (var processInvoker = HostContext.CreateService <IProcessInvoker>()) { var outputLock = new object(); processInvoker.OutputDataReceived += (object sender, DataReceivedEventArgs e) => { lock (outputLock) { ExecutionContext.Output(e.Data); } }; processInvoker.ErrorDataReceived += (object sender, DataReceivedEventArgs e) => { lock (outputLock) { ExecutionContext.Output(e.Data); } }; string arguments = FormatArguments(formatFlags, args); ExecutionContext.Command($@"{_tf} {arguments}"); await processInvoker.ExecuteAsync( workingDirectory : IOUtil.GetWorkPath(HostContext), fileName : _tf, arguments : arguments, environment : null, requireExitCodeZero : true, cancellationToken : CancellationToken); } }
protected override void Parse(Stream s) { BinaryReader br = new BinaryReader(s); string tag = FOURCC(br.ReadUInt32()); if (checking && tag != Tag) { throw new InvalidDataException(string.Format("Invalid Tag read: '{0}'; expected: '{1}'; at 0x{2:X8}", tag, Tag, s.Position)); } mVersion = br.ReadUInt32(); mFlags = (FormatFlags)br.ReadUInt32(); mDisplayListUsage = br.ReadUInt32(); bool is32Bit = (mFlags & FormatFlags.Uses32BitIndices) != 0; mBuffer = new Int32[(s.Length - s.Position) / (is32Bit ? 4 : 2)]; Int32 last = 0; for (int i = 0; i < mBuffer.Length; i++) { Int32 cur = is32Bit ? br.ReadInt32() : br.ReadInt16(); if ((mFlags & FormatFlags.DifferencedIndices) != 0) { cur += last; } mBuffer[i] = cur; last = cur; } }
public void SetFlagAt(int startIndex, int length, FormatFlags flag) { for (int i = startIndex; i < startIndex + length && i < FormatMask.Count; i++) { SetFlagAt(i, flag); } }
protected virtual void AppendFormat(string content, StringBuilder sb, FormatFlags flags, double r = 0.0, double g = 0.0, double b = 0.0) { if (flags == FormatFlags.None) { sb.Append(content); return; } sb.Append("<span"); if ((flags & FormatFlags.Bold) != 0) { sb.Append(" weight='bold'"); } if ((flags & FormatFlags.Italic) != 0) { sb.Append(" font_style='italic'"); } if ((flags & FormatFlags.Underline) != 0) { sb.Append(" underline='single'"); } if ((flags & FormatFlags.Color) != 0) { sb.Append(string.Format(" color='#{0:x2}{1:x2}{2:x2}'", (int)(r * 255.0), (int)(g * 255.0), (int)(b * 255.0))); } sb.Append('>').Append(content).Append("</span>"); }
/// <summary> /// Formats a property value for display purposes /// </summary> /// <param name="value">The property value to format</param> /// <param name="flags">Additional <see cref="FormatFlags"/> with formatting instructions.</param> /// <returns>A string containing the property's value in a suitably formatted structure</returns> public string FormatForDisplay(PropVariant value, FormatFlags flags) { string sFormatted; _propDescription.FormatForDisplay(value.MarshalledPointer, (PROPDESC_FORMAT_FLAGS)flags, out sFormatted); return(sFormatted); }
public VBUF(int APIversion, EventHandler handler, uint version, FormatFlags flags, GenericRCOLResource.ChunkReference swizzleInfo, byte[] buffer) : this(APIversion, handler) { mVersion = version; mFlags = flags; mSwizzleInfo = swizzleInfo; mBuffer = buffer; }
public IBUF(int APIversion, EventHandler handler, uint version, FormatFlags flags, uint displayListUsage, Int32[] buffer) : base(APIversion, handler, null) { mVersion = version; mFlags = flags; mDisplayListUsage = displayListUsage; mBuffer = buffer; }
private static extern int FormatMessage( FormatFlags dwFlags, IntPtr lpSource, int dwMessageId, int dwLanguageId, out IntPtr lpBuffer, int nSize, IntPtr Arguments );
internal static extern int FormatMessage( FormatFlags dwFlags, IntPtr lpSource, uint dwMessageId, int dwLanguageId, out SafeLocalAllocHandle lpBuffer, int nSize, IntPtr Arguments );
/// <summary> /// Creates a new <see cref="ConfigurationCell"/> from serialization parameters. /// </summary> /// <param name="info">The <see cref="SerializationInfo"/> with populated with data.</param> /// <param name="context">The source <see cref="StreamingContext"/> for this deserialization.</param> protected ConfigurationCell(SerializationInfo info, StreamingContext context) : base(info, context) { // Deserialize configuration cell m_sectionEntry = info.GetString("sectionEntry"); m_formatFlags = (FormatFlags)info.GetValue("formatFlags", typeof(FormatFlags)); m_offset = info.GetUInt16("offset"); m_reserved = info.GetUInt16("reserved"); }
public override bool Equals(object obj) { return((obj is StringFormat f) && FormatFlags.Equals(f.FormatFlags) && HotkeyPrefix.Equals(f.HotkeyPrefix) && measurableCharacterRanges == f.measurableCharacterRanges && Alignment.Equals(f.Alignment) && LineAlignment.Equals(f.LineAlignment) && Trimming.Equals(f.Trimming)); }
private string FormatArguments(FormatFlags formatFlags, params string[] args) { // Validation. ArgUtil.NotNull(args, nameof(args)); ArgUtil.NotNull(Endpoint, nameof(Endpoint)); ArgUtil.NotNull(Endpoint.Authorization, nameof(Endpoint.Authorization)); ArgUtil.NotNull(Endpoint.Authorization.Parameters, nameof(Endpoint.Authorization.Parameters)); ArgUtil.Equal(EndpointAuthorizationSchemes.OAuth, Endpoint.Authorization.Scheme, nameof(Endpoint.Authorization.Scheme)); string accessToken = Endpoint.Authorization.Parameters.TryGetValue(EndpointAuthorizationParameters.AccessToken, out accessToken) ? accessToken : null; ArgUtil.NotNullOrEmpty(accessToken, EndpointAuthorizationParameters.AccessToken); ArgUtil.NotNull(Endpoint.Url, nameof(Endpoint.Url)); // Format each arg. var formattedArgs = new List <string>(); foreach (string arg in args ?? new string[0]) { // Validate the arg. if (!string.IsNullOrEmpty(arg) && arg.IndexOfAny(new char[] { '"', '\r', '\n' }) >= 0) { throw new Exception(StringUtil.Loc("InvalidCommandArg", arg)); } // Add the arg. formattedArgs.Add(arg != null && arg.Contains(" ") ? $@"""{arg}""" : $"{arg}"); } // Add the common parameters. if (!formatFlags.HasFlag(FormatFlags.OmitCollectionUrl)) { formattedArgs.Add($"{Switch}collection:{Endpoint.Url.AbsoluteUri}"); } if (!formatFlags.HasFlag(FormatFlags.OmitLogin)) { if (Features.HasFlag(TfsVCFeatures.LoginType)) { formattedArgs.Add($"{Switch}loginType:OAuth"); formattedArgs.Add($"{Switch}login:.,{accessToken}"); } else { formattedArgs.Add($"{Switch}jwt:{accessToken}"); } } if (!formatFlags.HasFlag(FormatFlags.OmitNoPrompt)) { formattedArgs.Add($"{Switch}noprompt"); } return(string.Join(" ", formattedArgs)); }
public override JObject SaveToJsonObject(StiJsonSaveMode mode) { var jObject = base.SaveToJsonObject(mode); jObject.Add(new JProperty("IsGeneric", IsGeneric)); jObject.Add(new JProperty("Alignment", Alignment.ToString())); jObject.Add(new JProperty("FormatFlags", FormatFlags.ToString())); jObject.Add(new JProperty("HotkeyPrefix", HotkeyPrefix.ToString())); jObject.Add(new JProperty("LineAlignment", LineAlignment.ToString())); jObject.Add(new JProperty("Trimming", Trimming.ToString())); return(jObject); }
private async Task <string> RunPorcelainCommandAsync(FormatFlags formatFlags, params string[] args) { // Validation. ArgUtil.NotNull(args, nameof(args)); ArgUtil.NotNull(ExecutionContext, nameof(ExecutionContext)); // Invoke tf. using (var processInvoker = HostContext.CreateService <IProcessInvoker>()) { var output = new List <string>(); var outputLock = new object(); processInvoker.OutputDataReceived += (object sender, DataReceivedEventArgs e) => { lock (outputLock) { ExecutionContext.Debug(e.Data); output.Add(e.Data); } }; processInvoker.ErrorDataReceived += (object sender, DataReceivedEventArgs e) => { lock (outputLock) { ExecutionContext.Debug(e.Data); output.Add(e.Data); } }; string arguments = FormatArguments(formatFlags, args); ExecutionContext.Debug($@"{_tf} {arguments}"); // TODO: Test whether the output encoding needs to be specified on a non-Latin OS. try { await processInvoker.ExecuteAsync( workingDirectory : IOUtil.GetWorkPath(HostContext), fileName : _tf, arguments : arguments, environment : null, requireExitCodeZero : true, cancellationToken : CancellationToken); } catch (ProcessExitCodeException) { // The command failed. Dump the output and throw. output.ForEach(x => ExecutionContext.Output(x ?? string.Empty)); throw; } // Note, string.join gracefully handles a null element within the IEnumerable<string>. return(string.Join(Environment.NewLine, output)); } }
protected override void Parse(Stream s) { BinaryReader br = new BinaryReader(s); string tag = FOURCC(br.ReadUInt32()); if (checking && tag != Tag) { throw new InvalidDataException(string.Format("Invalid Tag read: '{0}'; expected: '{1}'; at 0x{2:X8}", tag, Tag, s.Position)); } mVersion = br.ReadUInt32(); mFlags = (FormatFlags)br.ReadUInt32(); mSwizzleInfo = new GenericRCOLResource.ChunkReference(0, handler, s); mBuffer = new Byte[s.Length - s.Position]; s.Read(mBuffer, 0, mBuffer.Length); }
public override Stream UnParse() { MemoryStream s = new MemoryStream(); BinaryWriter bw = new BinaryWriter(s); if (mBuffer == null) { mBuffer = new Int32[0]; } bool is32Bit = mBuffer.Length > UInt16.MaxValue; if (is32Bit) { mFlags |= FormatFlags.Uses32BitIndices; } else { mFlags &= (FormatFlags)UInt32.MaxValue ^ FormatFlags.Uses32BitIndices; } bw.Write((UInt32)FOURCC(Tag)); bw.Write(mVersion); bw.Write((UInt32)mFlags); bw.Write(mDisplayListUsage); bool isDifferenced = (mFlags & FormatFlags.DifferencedIndices) != 0; Int32 last = 0; for (int i = 0; i < mBuffer.Length; i++) { Int32 cur = mBuffer[i]; if (isDifferenced) { cur -= last; last = mBuffer[i]; } if (is32Bit) { bw.Write(cur); } else { bw.Write((UInt16)cur); } } return(s); }
protected async Task <string> RunPorcelainCommandAsync(FormatFlags formatFlags, bool ignoreStderr, params string[] args) { // Run the command. TfsVCPorcelainCommandResult result = await TryRunPorcelainCommandAsync(formatFlags, ignoreStderr, args); ArgUtil.NotNull(result, nameof(result)); if (result.Exception != null) { // The command failed. Dump the output and throw. result.Output?.ForEach(x => ExecutionContext.Output(x ?? string.Empty)); throw result.Exception; } // Return the output. // Note, string.join gracefully handles a null element within the IEnumerable<string>. return(string.Join(Environment.NewLine, result.Output ?? new List <string>())); }
private void CheckClosed() { CheckDisposed(); if (!_nestedTokens.Top.Closed) { _writer.Write('>'); FormatFlags flags = GetFlagsForTagName(_nestedTokens.Top.Name); if (0 != (FormatFlags.BeginNewLine & flags)) { _writer.WriteLine(); } _nestedTokens.Top.Closed = true; } }
static IEnumerable <CanvasAlphaMode> GetAlphaModes(FormatFlags flags) { if ((flags & FormatFlags.PremultipliedAlpha) != 0) { yield return(CanvasAlphaMode.Premultiplied); } if ((flags & FormatFlags.IgnoreAlpha) != 0) { yield return(CanvasAlphaMode.Ignore); } if ((flags & FormatFlags.StraightAlpha) != 0) { yield return(CanvasAlphaMode.Straight); } }
/// <summary> /// Writes the end element (closing tag). /// </summary> /// <remarks>The implementation of <see cref="HtmlWriter"/> should /// maintain a stack of elements (tags) written. The implementation of /// this method should use this stak to retrieve the closing tag. /// </remarks> /// <seealso cref="WriteStartElement"/> public override void WriteEndElement() { CheckClosed(); _writer.Write("</"); _writer.Write(_nestedTokens.Top.Name); _writer.Write('>'); FormatFlags flags = GetFlagsForTagName(_nestedTokens.Top.Name); if (0 != (FormatFlags.EndNewLine & flags)) { _writer.WriteLine(); } _nestedTokens.Pop(); }
public FormatConverter(XmlNode node) : base(node) { format = node.ReadStr("@format"); flags = node.ReadEnum("@flags", FormatFlags.NeedArguments); needValue = (flags & FormatFlags.NeedValue) != 0; String[] args = node.ReadStr("@arguments", null).SplitStandard(); if (args != null && args.Length > 0) { arguments = new FormatArgument[args.Length]; for (int i = 0; i < args.Length; i++) { arguments[i] = createArgument(args[i]); } } }
private bool FormatFormulaAt(int rStart, string text) { var objUndo = this.Application.UndoRecord; objUndo.StartCustomRecord("Format Formula"); try { FormatString fstring = helper.FormatInput(text); for (int i = 0; i < fstring.FormatMask.Count; i++) { Word.Range rng = this.Application.ActiveDocument.Range(rStart + i, rStart + i + 1); rng.Text = fstring.Content[i].ToString(); FormatFlags x = fstring.FormatMask[i]; switch (x) { case FormatFlags.None: break; case FormatFlags.Subscript: rng.Font.Subscript = 1; break; case FormatFlags.Superscript: rng.Font.Superscript = 1; break; default: break; } } } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); return(false); } finally { objUndo.EndCustomRecord(); } return(true); }
protected async Task <int> RunCommandAsync(FormatFlags formatFlags, bool quiet, bool failOnNonZeroExitCode, params string[] args) { // Validation. ArgUtil.NotNull(args, nameof(args)); ArgUtil.NotNull(ExecutionContext, nameof(ExecutionContext)); // Invoke tf. using (var processInvoker = new ProcessInvoker(ExecutionContext)) { var outputLock = new object(); processInvoker.OutputDataReceived += (object sender, ProcessDataReceivedEventArgs e) => { lock (outputLock) { if (quiet) { ExecutionContext.Debug(e.Data); } else { ExecutionContext.Output(e.Data); } } }; processInvoker.ErrorDataReceived += (object sender, ProcessDataReceivedEventArgs e) => { lock (outputLock) { ExecutionContext.Output(e.Data); } }; string arguments = FormatArguments(formatFlags, args); ExecutionContext.Command($@"tf {arguments}"); return(await processInvoker.ExecuteAsync( workingDirectory : SourcesDirectory, fileName : "tf", arguments : arguments, environment : AdditionalEnvironmentVariables, requireExitCodeZero : failOnNonZeroExitCode, outputEncoding : OutputEncoding, cancellationToken : CancellationToken)); } }
/// <summary> /// Parses the binary header image. /// </summary> /// <param name="buffer">Binary image to parse.</param> /// <param name="startIndex">Start index into <paramref name="buffer"/> to begin parsing.</param> /// <param name="length">Length of valid data within <paramref name="buffer"/>.</param> /// <returns>The length of the data that was parsed.</returns> protected override int ParseHeaderImage(byte[] buffer, int startIndex, int length) { IConfigurationCellParsingState state = State; int index = startIndex; // Parse out station name index += base.ParseHeaderImage(buffer, startIndex, length); IDCode = BigEndian.ToUInt16(buffer, index); m_formatFlags = (FormatFlags)BigEndian.ToUInt16(buffer, index + 2); // Parse out total phasors, analogs and digitals defined for this device state.PhasorCount = BigEndian.ToUInt16(buffer, index + 4); state.AnalogCount = BigEndian.ToUInt16(buffer, index + 6); state.DigitalCount = BigEndian.ToUInt16(buffer, index + 8); index += 10; return(index - startIndex); }
/// <summary> /// Write an element to the output stream. /// </summary> /// <param name="name">The element's name.</param> /// <param name="value">The element's value.</param> /// <remarks>This method is suitable for writing simple tags.</remarks> public override void WriteElement(string name, string value) { CheckClosed(); _writer.Write('<'); _writer.Write(name); _writer.Write('>'); InternalWriteText(value); _writer.Write("</"); _writer.Write(name); _writer.Write('>'); FormatFlags flags = GetFlagsForTagName(_nestedTokens.Top.Name); if (0 != (FormatFlags.BeginNewLine & flags)) { _writer.WriteLine(); } }
public FormatInfo( LoadedRegex headRe, LoadedRegex bodyRe, string encoding, FieldsProcessor.InitializationParams fieldsParams, MessagesReaderExtensions.XmlInitializationParams extensionsInitData, DejitteringParams?dejitteringParams, TextStreamPositioningParams textStreamPositioningParams, FormatFlags flags, RotationParams rotationParams ) : base(extensionsInitData) { this.HeadRe = headRe; this.BodyRe = bodyRe; this.Encoding = encoding; this.FieldsProcessorParams = fieldsParams; this.DejitteringParams = dejitteringParams; this.TextStreamPositioningParams = textStreamPositioningParams; this.Flags = flags; this.RotationParams = rotationParams; }
protected async Task RunCommandAsync(FormatFlags formatFlags, bool quiet, int retriesOnFailure, params string[] args) { for (int attempt = 0; attempt < retriesOnFailure; attempt++) { int exitCode = await RunCommandAsync(formatFlags, quiet, false, args); if (exitCode == 0) { return; } int sleep = Math.Min(200 * (int)Math.Pow(5, attempt), 30000); ExecutionContext.Output($"Sleeping for {sleep} ms"); await Task.Delay(sleep); // Use attempt+2 since we're using 0 based indexing and we're displaying this for the next attempt. ExecutionContext.Output($@"Retrying. Attempt ${attempt+2}/${retriesOnFailure}"); } // Perform one last try and fail on non-zero exit code await RunCommandAsync(formatFlags, quiet, true, args); }
/// <summary> /// Creates a new <see cref="ConfigurationCell3"/> from serialization parameters. /// </summary> /// <param name="info">The <see cref="SerializationInfo"/> with populated with data.</param> /// <param name="context">The source <see cref="StreamingContext"/> for this deserialization.</param> private ConfigurationCell3(SerializationInfo info, StreamingContext context) : base(info, context) { float getSingle(string name) { return(!(info.GetValue(name, typeof(string)) is string element) || element == "INF" ? float.PositiveInfinity : float.Parse(element)); } // Deserialize configuration cell m_formatFlags = (FormatFlags)info.GetValue("formatFlags", typeof(FormatFlags)); GlobalID = Guid.TryParse(info.GetOrDefault("globalID", Guid.Empty.ToString()), out Guid globalID) ? globalID : Guid.Empty; // Decode PMU_LAT, PMU_LON, PMU_ELEV, SVC_CLASS, WINDOW, GRP_DLY values Latitude = getSingle("latitude"); Longitude = getSingle("longitude"); Elevation = getSingle("elevation"); ServiceClass = info.GetChar("serviceClass"); Window = info.GetInt32("window"); GroupDelay = info.GetInt32("groupDelay"); DataModified = info.GetBoolean("dataModified"); }
protected async Task RunCommandAsync(FormatFlags formatFlags, params string[] args) { // Validation. ArgUtil.NotNull(args, nameof(args)); ArgUtil.NotNull(ExecutionContext, nameof(ExecutionContext)); // Invoke tf. using (var processInvoker = HostContext.CreateService <IProcessInvoker>()) { var outputLock = new object(); processInvoker.OutputDataReceived += (object sender, ProcessDataReceivedEventArgs e) => { lock (outputLock) { ExecutionContext.Output(e.Data); } }; processInvoker.ErrorDataReceived += (object sender, ProcessDataReceivedEventArgs e) => { lock (outputLock) { ExecutionContext.Output(e.Data); } }; string arguments = FormatArguments(formatFlags, args); ExecutionContext.Command($@"tf {arguments}"); await processInvoker.ExecuteAsync( workingDirectory : SourcesDirectory, fileName : FilePath, arguments : arguments, environment : AdditionalEnvironmentVariables, requireExitCodeZero : true, outputEncoding : OutputEncoding, cancellationToken : CancellationToken); } }
private void CheckBadFlags(FormatFlags bad) { foreach ( FormatFlags f in Enum.GetValues(typeof(FormatFlags))) if ((bad & f & _flags) != 0 ) FailMismatch(f,_conversion); }
protected async Task RunCommandAsync(FormatFlags formatFlags, params string[] args) { // Validation. ArgUtil.NotNull(args, nameof(args)); ArgUtil.NotNull(ExecutionContext, nameof(ExecutionContext)); // Invoke tf. using(var processInvoker = HostContext.CreateService<IProcessInvoker>()) { var outputLock = new object(); processInvoker.OutputDataReceived += (object sender, ProcessDataReceivedEventArgs e) => { lock (outputLock) { ExecutionContext.Output(e.Data); } }; processInvoker.ErrorDataReceived += (object sender, ProcessDataReceivedEventArgs e) => { lock (outputLock) { ExecutionContext.Output(e.Data); } }; string arguments = FormatArguments(formatFlags, args); ExecutionContext.Command($@"{TF} {arguments}"); await processInvoker.ExecuteAsync( workingDirectory: SourcesDirectory, fileName: TF, arguments: arguments, environment: null, requireExitCodeZero: true, cancellationToken: CancellationToken); } }
protected override void AppendFormat (string content, StringBuilder sb, FormatFlags flags, double r = 0, double g = 0, double b = 0) { sb.Append (content); //base.AppendFormat (content, sb, flags, r, g, b); }
protected virtual void AppendFormat(string content, StringBuilder sb, FormatFlags flags, double r = 0.0, double g = 0.0, double b = 0.0) { if (flags == FormatFlags.None) { sb.Append(content); return; } sb.Append("<span"); if ((flags & FormatFlags.Bold) != 0) sb.Append(" weight='bold'"); if ((flags & FormatFlags.Italic) != 0) sb.Append(" font_style='italic'"); if ((flags & FormatFlags.Underline) != 0) sb.Append(" underline='single'"); if ((flags & FormatFlags.Color) != 0) { sb.Append(string.Format(" color='#{0:x2}{1:x2}{2:x2}'", (int)(r * 255.0), (int)(g * 255.0), (int)(b * 255.0))); } sb.Append('>').Append(content).Append("</span>"); }
private static string FormatChar (char c, char surrogate, string cStr, UriSchemes scheme, UriKind uriKind, UriComponents component, UriFormat uriFormat, FormatFlags formatFlags) { var isEscaped = cStr.Length != 1; var userEscaped = (formatFlags & FormatFlags.UserEscaped) != 0; if (!isEscaped && !userEscaped && NeedToEscape (c, scheme, component, uriKind, uriFormat, formatFlags)) return HexEscapeMultiByte (c); if (isEscaped && ( (userEscaped && c < 0xFF) || !NeedToUnescape (c, scheme, component, uriKind, uriFormat, formatFlags))) { if (IriParsing && (c == '<' || c == '>' || c == '^' || c == '{' || c == '|' || c == '}' || c > 0x7F) && (formatFlags & FormatFlags.HasUriCharactersToNormalize) != 0) return cStr.ToUpperInvariant (); //Upper case escape return cStr; //Keep original case } if ((formatFlags & FormatFlags.NoSlashReplace) == 0 && c == '\\' && component == UriComponents.Path) { if (!IriParsing && uriFormat != UriFormat.UriEscaped && SchemeContains (scheme, UriSchemes.Http | UriSchemes.Https)) return "/"; if (SchemeContains (scheme, UriSchemes.Http | UriSchemes.Https | UriSchemes.Ftp | UriSchemes.CustomWithHost)) return (isEscaped && uriFormat != UriFormat.UriEscaped) ? "\\" : "/"; if (SchemeContains (scheme, UriSchemes.NetPipe | UriSchemes.NetTcp | UriSchemes.File)) return "/"; if (SchemeContains (scheme, UriSchemes.Custom) && (formatFlags & FormatFlags.HasWindowsPath) == 0) return "/"; } var ret = c.ToString (CultureInfo.InvariantCulture); if (surrogate != char.MinValue) ret += surrogate.ToString (CultureInfo.InvariantCulture); return ret; }
private void ComputeFlags(Group group) { _flags = ParseFlags(group.Value); if ((_flags & FormatFlags.Previous) != 0) _index = PREV_ARG_INDEX; }
/// <summary> /// Creates a new <see cref="ConfigurationCell"/> from serialization parameters. /// </summary> /// <param name="info">The <see cref="SerializationInfo"/> with populated with data.</param> /// <param name="context">The source <see cref="StreamingContext"/> for this deserialization.</param> protected ConfigurationCell(SerializationInfo info, StreamingContext context) : base(info, context) { // Deserialize configuration cell m_formatFlags = (FormatFlags)info.GetValue("formatFlags", typeof(FormatFlags)); }
private static string FormatString (string str, UriSchemes scheme, UriKind uriKind, UriComponents component, UriFormat uriFormat, FormatFlags formatFlags) { var s = new StringBuilder (); int len = str.Length; for (int i = 0; i < len; i++) { char c = str [i]; if (c == '%') { int iStart = i; char surrogate; bool invalidUnescape; char x = Uri.HexUnescapeMultiByte (str, ref i, out surrogate, out invalidUnescape); if (invalidUnescape ) { s.Append (c); i = iStart; continue; } string cStr = str.Substring (iStart, i-iStart); s.Append (FormatChar (x, surrogate, cStr, scheme, uriKind, component, uriFormat, formatFlags)); i--; } else s.Append (FormatChar (c, char.MinValue, "" + c, scheme, uriKind, component, uriFormat, formatFlags)); } return s.ToString (); }
/// <summary> /// Parses the binary header image. /// </summary> /// <param name="binaryImage">Binary image to parse.</param> /// <param name="startIndex">Start index into <paramref name="binaryImage"/> to begin parsing.</param> /// <param name="length">Length of valid data within <paramref name="binaryImage"/>.</param> /// <returns>The length of the data that was parsed.</returns> protected override int ParseHeaderImage(byte[] binaryImage, int startIndex, int length) { IConfigurationCellParsingState state = State; int index = startIndex; // Parse out station name index += base.ParseHeaderImage(binaryImage, startIndex, length); IDCode = EndianOrder.BigEndian.ToUInt16(binaryImage, index); m_formatFlags = (FormatFlags)EndianOrder.BigEndian.ToUInt16(binaryImage, index + 2); // Parse out total phasors, analogs and digitals defined for this device state.PhasorCount = EndianOrder.BigEndian.ToUInt16(binaryImage, index + 4); state.AnalogCount = EndianOrder.BigEndian.ToUInt16(binaryImage, index + 6); state.DigitalCount = EndianOrder.BigEndian.ToUInt16(binaryImage, index + 8); index += 10; return (index - startIndex); }
static IEnumerable<CanvasAlphaMode> GetAlphaModes(FormatFlags flags) { if ((flags & FormatFlags.PremultipliedAlpha) != 0) yield return CanvasAlphaMode.Premultiplied; if ((flags & FormatFlags.IgnoreAlpha) != 0) yield return CanvasAlphaMode.Ignore; if ((flags & FormatFlags.StraightAlpha) != 0) yield return CanvasAlphaMode.Straight; }
private void ComputeConversion(Group group) { _conversion = group.Value[0]; if (!_isDateTime) { if (!ConversionAux.IsValid(_conversion)) throw new UnknownFormatConversionException(group.Value); if (Char.IsUpper(_conversion)) _flags |= FormatFlags.UpperCase; _conversion = Char.ToLower(_conversion); if (ConversionAux.IsText(_conversion)) _index = FIXED_TEXT_INDEX; } }
private static bool NeedToUnescape (char c, UriSchemes scheme, UriComponents component, UriKind uriKind, UriFormat uriFormat, FormatFlags formatFlags) { if ((formatFlags & FormatFlags.IPv6Host) != 0) return false; if (uriFormat == UriFormat.Unescaped) return true; UriSchemes sDecoders = UriSchemes.NetPipe | UriSchemes.NetTcp; if (!IriParsing) sDecoders |= UriSchemes.Http | UriSchemes.Https; if (c == '/' || c == '\\') { if (!IriParsing && uriKind == UriKind.Absolute && uriFormat != UriFormat.UriEscaped && uriFormat != UriFormat.SafeUnescaped) return true; if (SchemeContains (scheme, UriSchemes.File)) { return component != UriComponents.Fragment && (component != UriComponents.Query || !IriParsing); } return component != UriComponents.Query && component != UriComponents.Fragment && SchemeContains (scheme, sDecoders); } if (c == '?') { //Avoid creating new query if (SupportsQuery (scheme) && component == UriComponents.Path) return false; if (!IriParsing && uriFormat == ToStringUnescape) { if (SupportsQuery (scheme)) return component == UriComponents.Query || component == UriComponents.Fragment; return component == UriComponents.Fragment; } return false; } if (c == '#') return false; if (uriFormat == ToStringUnescape && !IriParsing) { if (uriKind == UriKind.Relative) return false; switch (c) { case '$': case '&': case '+': case ',': case ';': case '=': case '@': return true; } if (c < 0x20 || c == 0x7f) return true; } if (uriFormat == UriFormat.SafeUnescaped || uriFormat == ToStringUnescape) { switch (c) { case '-': case '.': case '_': case '~': return true; case ' ': case '!': case '"': case '\'': case '(': case ')': case '*': case '<': case '>': case '^': case '`': case '{': case '}': case '|': return uriKind != UriKind.Relative || (IriParsing && (formatFlags & FormatFlags.HasUriCharactersToNormalize) != 0); case ':': case '[': case ']': return uriKind != UriKind.Relative; } if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')) return true; if (c > 0x7f) return true; return false; } if (uriFormat == UriFormat.UriEscaped) { if (!IriParsing) { if (c == '.') { if (SchemeContains (scheme, UriSchemes.File)) return component != UriComponents.Fragment; return component != UriComponents.Query && component != UriComponents.Fragment && SchemeContains (scheme, sDecoders); } return false; } switch (c) { case '-': case '.': case '_': case '~': return true; } if ((formatFlags & FormatFlags.HasUriCharactersToNormalize) != 0) { switch (c) { case '!': case '\'': case '(': case ')': case '*': case ':': case '[': case ']': return true; } } if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')) return true; return false; } return false; }
private void ComputeDt(Group group) { _isDateTime = false; if (group.Success) { _isDateTime = true; if (group.Value.Equals("T")) _flags |= FormatFlags.UpperCase; } }
private static bool NeedToEscape (char c, UriSchemes scheme, UriComponents component, UriKind uriKind, UriFormat uriFormat, FormatFlags formatFlags) { if ((formatFlags & FormatFlags.IPv6Host) != 0) return false; if (c == '?') { if (uriFormat == UriFormat.Unescaped) return false; if (!SupportsQuery (scheme)) return component != UriComponents.Fragment; return false; } if (c == '#') { //Avoid removing fragment if (component == UriComponents.Path || component == UriComponents.Query) return false; if (component == UriComponents.Fragment && (uriFormat == ToStringUnescape || uriFormat == UriFormat.SafeUnescaped) && (formatFlags & FormatFlags.HasFragmentPercentage) != 0) return true; return false; } if (uriFormat == UriFormat.SafeUnescaped || uriFormat == ToStringUnescape) { if (c == '%') return uriKind != UriKind.Relative; } if (uriFormat == UriFormat.SafeUnescaped) { if (c < 0x20 || c == 0x7F) return true; } if (uriFormat == UriFormat.UriEscaped) { if (c < 0x20 || c >= 0x7F) return component != UriComponents.Host; switch (c) { case ' ': case '"': case '%': case '<': case '>': case '^': case '`': case '{': case '}': case '|': return true; case '[': case ']': return !IriParsing; case '\\': return component != UriComponents.Path || SchemeContains (scheme, UriSchemes.Gopher | UriSchemes.Ldap | UriSchemes.Mailto | UriSchemes.Nntp | UriSchemes.Telnet | UriSchemes.News | UriSchemes.Custom); } } return false; }
private void FailMismatch(FormatFlags flags,char conv) { throw new FormatFlagsConversionMismatchException(FormatFlagsToString(flags),conv); }
public override Stream UnParse() { MemoryStream s = new MemoryStream(); BinaryWriter bw = new BinaryWriter(s); if (mBuffer == null) mBuffer = new Int32[0]; bool is32Bit = mBuffer.Length > UInt16.MaxValue; if (is32Bit) { mFlags |= FormatFlags.Uses32BitIndices; } else { mFlags &= (FormatFlags)UInt32.MaxValue ^ FormatFlags.Uses32BitIndices; } bw.Write((UInt32)FOURCC(Tag)); bw.Write(mVersion); bw.Write((UInt32)mFlags); bw.Write(mDisplayListUsage); bool isDifferenced = (mFlags & FormatFlags.DifferencedIndices) != 0; Int32 last = 0; for (int i = 0; i < mBuffer.Length; i++) { Int32 cur = mBuffer[i]; if (isDifferenced) { cur -= last; last = mBuffer[i]; } if (is32Bit) bw.Write(cur); else bw.Write((UInt16)cur); } return s; }
protected override void Parse(Stream s) { BinaryReader br = new BinaryReader(s); string tag = FOURCC(br.ReadUInt32()); if (checking && tag != Tag) { throw new InvalidDataException(string.Format("Invalid Tag read: '{0}'; expected: '{1}'; at 0x{2:X8}", tag, Tag, s.Position)); } mVersion = br.ReadUInt32(); mFlags = (FormatFlags)br.ReadUInt32(); mDisplayListUsage = br.ReadUInt32(); bool is32Bit = (mFlags & FormatFlags.Uses32BitIndices) != 0; mBuffer = new Int32[(s.Length-s.Position) / (is32Bit ? 4 : 2)]; Int32 last = 0; for (int i = 0; i < mBuffer.Length; i++) { Int32 cur = is32Bit ? br.ReadInt32() : br.ReadInt16(); if ((mFlags & FormatFlags.DifferencedIndices) != 0) { cur += last; } mBuffer[i] = cur; last = cur; } }
static string FormatFlagsToString(FormatFlags flags) { StringBuilder sb = new StringBuilder(); if ((flags & FormatFlags.LeftJustify) != 0) sb.Append('-'); if ((flags & FormatFlags.UpperCase) != 0) sb.Append('^'); if ((flags & FormatFlags.Alternate) != 0) sb.Append('#'); if ((flags & FormatFlags.Plus) != 0) sb.Append('+'); if ((flags & FormatFlags.LeadingSpace) != 0) sb.Append(' '); if ((flags & FormatFlags.ZeroPad) != 0) sb.Append('0'); if ((flags & FormatFlags.Group) != 0) sb.Append(','); if ((flags & FormatFlags.Parentheses) != 0) sb.Append('('); if ((flags & FormatFlags.Previous) != 0) sb.Append('<'); return sb.ToString(); }
internal static string FormatAbsolute (string str, string schemeName, UriComponents component, UriFormat uriFormat, FormatFlags formatFlags = FormatFlags.None) { return Format (str, schemeName, UriKind.Absolute, component, uriFormat, formatFlags); }
private string FormatArguments(FormatFlags formatFlags, params string[] args) { // Validation. ArgUtil.NotNull(args, nameof(args)); ArgUtil.NotNull(Endpoint, nameof(Endpoint)); ArgUtil.NotNull(Endpoint.Authorization, nameof(Endpoint.Authorization)); ArgUtil.NotNull(Endpoint.Authorization.Parameters, nameof(Endpoint.Authorization.Parameters)); ArgUtil.Equal(EndpointAuthorizationSchemes.OAuth, Endpoint.Authorization.Scheme, nameof(Endpoint.Authorization.Scheme)); string accessToken = Endpoint.Authorization.Parameters.TryGetValue(EndpointAuthorizationParameters.AccessToken, out accessToken) ? accessToken : null; ArgUtil.NotNullOrEmpty(accessToken, EndpointAuthorizationParameters.AccessToken); ArgUtil.NotNull(Endpoint.Url, nameof(Endpoint.Url)); // Format each arg. var formattedArgs = new List<string>(); foreach (string arg in args ?? new string[0]) { // Validate the arg. if (!string.IsNullOrEmpty(arg) && arg.IndexOfAny(new char[] { '"', '\r', '\n' }) >= 0) { throw new Exception(StringUtil.Loc("InvalidCommandArg", arg)); } // Add the arg. formattedArgs.Add(arg != null && arg.Contains(" ") ? $@"""{arg}""" : $"{arg}"); } // Add the common parameters. if (!formatFlags.HasFlag(FormatFlags.OmitCollectionUrl)) { formattedArgs.Add($"{Switch}collection:{Endpoint.Url.AbsoluteUri}"); } if (!formatFlags.HasFlag(FormatFlags.OmitLogin)) { if (Features.HasFlag(TfsVCFeatures.LoginType)) { formattedArgs.Add($"{Switch}loginType:OAuth"); formattedArgs.Add($"{Switch}login:.,{accessToken}"); } else { formattedArgs.Add($"{Switch}jwt:{accessToken}"); } } if (!formatFlags.HasFlag(FormatFlags.OmitNoPrompt)) { formattedArgs.Add($"{Switch}noprompt"); } return string.Join(" ", formattedArgs); }
protected async Task<string> RunPorcelainCommandAsync(FormatFlags formatFlags, params string[] args) { // Validation. ArgUtil.NotNull(args, nameof(args)); ArgUtil.NotNull(ExecutionContext, nameof(ExecutionContext)); // Invoke tf. using(var processInvoker = HostContext.CreateService<IProcessInvoker>()) { var output = new List<string>(); var outputLock = new object(); processInvoker.OutputDataReceived += (object sender, ProcessDataReceivedEventArgs e) => { lock (outputLock) { ExecutionContext.Debug(e.Data); output.Add(e.Data); } }; processInvoker.ErrorDataReceived += (object sender, ProcessDataReceivedEventArgs e) => { lock (outputLock) { ExecutionContext.Debug(e.Data); output.Add(e.Data); } }; string arguments = FormatArguments(formatFlags, args); ExecutionContext.Debug($@"{TF} {arguments}"); // TODO: Test whether the output encoding needs to be specified on a non-Latin OS. try { await processInvoker.ExecuteAsync( workingDirectory: SourcesDirectory, fileName: TF, arguments: arguments, environment: null, requireExitCodeZero: true, cancellationToken: CancellationToken); } catch (ProcessExitCodeException) { // The command failed. Dump the output and throw. output.ForEach(x => ExecutionContext.Output(x ?? string.Empty)); throw; } // Note, string.join gracefully handles a null element within the IEnumerable<string>. return string.Join(Environment.NewLine, output); } }
private static string Format (string str, string schemeName, UriKind uriKind, UriComponents component, UriFormat uriFormat, FormatFlags formatFlags) { if (string.IsNullOrEmpty (str)) return ""; if (UriHelper.HasCharactersToNormalize (str)) formatFlags |= UriHelper.FormatFlags.HasComponentCharactersToNormalize | FormatFlags.HasUriCharactersToNormalize; if (component == UriComponents.Fragment && UriHelper.HasPercentage (str)) formatFlags |= UriHelper.FormatFlags.HasFragmentPercentage; if (component == UriComponents.Host && str.Length > 1 && str [0] == '[' && str [str.Length - 1] == ']') formatFlags |= UriHelper.FormatFlags.IPv6Host; if (component == UriComponents.Path && str.Length >= 2 && str [1] != ':' && ('a' <= str [0] && str [0] <= 'z') || ('A' <= str [0] && str [0] <= 'Z')) formatFlags |= UriHelper.FormatFlags.HasWindowsPath; UriSchemes scheme = GetScheme (schemeName); if (scheme == UriSchemes.Custom && (formatFlags & FormatFlags.HasHost) != 0) scheme = UriSchemes.CustomWithHost; var reduceAfter = UriSchemes.Http | UriSchemes.Https | UriSchemes.File | UriSchemes.NetPipe | UriSchemes.NetTcp; if (IriParsing) { reduceAfter |= UriSchemes.Ftp; } else if (component == UriComponents.Path && (formatFlags & FormatFlags.NoSlashReplace) == 0) { if (scheme == UriSchemes.Ftp) str = Reduce (str.Replace ('\\', '/'), !IriParsing); if (scheme == UriSchemes.CustomWithHost) str = Reduce (str.Replace ('\\', '/'), false); } str = FormatString (str, scheme, uriKind, component, uriFormat, formatFlags); if (component == UriComponents.Path && (formatFlags & FormatFlags.NoReduce) == 0) { if (SchemeContains (scheme, reduceAfter)) str = Reduce (str, !IriParsing); if (IriParsing && scheme == UriSchemes.CustomWithHost) str = Reduce (str, false); } return str; }