/// <summary> /// Generates a string representation of the given <paramref name="obj"/> using the default /// <see href="FormatOptions" />. The output will contain one element for every readable /// property on <paramref name="obj"/> and process reference properties (other than strings) /// recursively. This method does not handle cyclic references - passing in such an object /// graph will cause an infinite loop. /// </summary> /// <param name="obj">The object to convert to XML.</param> /// <param name="options"></param> /// <returns>A string containing the generated XML data.</returns> public static string ToXml( this object obj, FormatOptions options ) { bool newLineAfterElement = (options & FormatOptions.NewLineAfterElement) == FormatOptions.NewLineAfterElement; string afterElement = newLineAfterElement ? Environment.NewLine : String.Empty; bool tabIndent = (options & FormatOptions.UseSpaces) != FormatOptions.UseSpaces; string indent = tabIndent ? "\t" : " "; bool addHeader = (options & FormatOptions.AddHeader) == FormatOptions.AddHeader; string header = addHeader ? "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + Environment.NewLine : string.Empty; return ToXml( obj, header, afterElement, indent, String.Empty ); }
public static StringBuilder LineWrap (this StringBuilder text, FormatOptions options) { if (text.Length == 0) return text; if (char.IsWhiteSpace (text[text.Length - 1])) { text.Insert (text.Length - 1, options.NewLine); } else { text.Append (options.NewLine); text.Append ('\t'); } return text; }
public static StringBuilder AppendFolded(this StringBuilder text, FormatOptions options, string value, ref int lineLength) { int wordIndex = 0; int lwspIndex; while (wordIndex < value.Length) { lwspIndex = wordIndex; if (value[wordIndex] == '"') { // quoted string; don't break these up... lwspIndex++; while (lwspIndex < value.Length && value[lwspIndex] != '"') { if (value[lwspIndex] == '\\') { lwspIndex++; if (lwspIndex < value.Length) lwspIndex++; } else { lwspIndex++; } } } else { // normal word while (lwspIndex < value.Length && !char.IsWhiteSpace (value[lwspIndex])) lwspIndex++; } int length = lwspIndex - wordIndex; if (lineLength > 1 && (lineLength + length) > options.MaxLineLength) { text.LineWrap (options); lineLength = 1; } text.Append (value, wordIndex, length); lineLength += length; wordIndex = lwspIndex; while (wordIndex < value.Length && char.IsWhiteSpace (value[wordIndex])) wordIndex++; if (wordIndex < value.Length && wordIndex > lwspIndex) { text.Append (' '); lineLength++; } } return text; }
/// <summary> /// The methods print number in a choose format. /// </summary> /// <param name="number">Integer - number.</param> /// <param name="format">FormatOptions - choose format.</param> public static void PrintAsNumber(object number, FormatOptions format) { switch (format) { case FormatOptions.FixedPoint: Console.WriteLine("{0:f2}", number); break; case FormatOptions.Percentage: Console.WriteLine("{0:p0}", number); break; case FormatOptions.AlignRight: Console.WriteLine("{0,8}", number); break; default: throw new ArgumentOutOfRangeException("Wrong formating otptions!"); } }
/// <summary> /// The method prints on the console a number in the chosen format. /// </summary> /// <param name="number">Input number passed for formatting.</param> /// <param name="format">Input string that specifies the type of formatting.</param> public static void PrintNumberWithSelectedFormatOption(object number, FormatOptions format) { switch (format) { case FormatOptions.RoundToSecondDigit: Console.WriteLine("{0:f2}", number); break; case FormatOptions.Percentage: Console.WriteLine("{0:p0}", number); break; case FormatOptions.RightAlignment: Console.WriteLine("{0,8}", number); break; default: throw new ArgumentException("Invalid formattiong option."); } }
public string Format(FormatOptions options) { var nl = Environment.NewLine; var sb = new StringBuilder(); var body = _methodDef.Body; var cfg = new ControlFlowGraph(body); SourceCodePosition lastSource = null; _dissassembly.Format = options; var embedSource = options.HasFlag(FormatOptions.EmbedSourceCode) || options.HasFlag(FormatOptions.EmbedSourcePositions); if (embedSource && _dissassembly.MethodEntry != null) { var pos = _mapFile.GetSourceCodePositions(_dissassembly.MethodEntry).FirstOrDefault(); if (pos != null) { sb.Append(" // ----- Source Code: "); sb.Append(pos.Document.Path); sb.Append(nl); } } foreach (var block in cfg) { if (options.HasFlag(FormatOptions.ShowControlFlow)) { sb.AppendFormat(" // ----- Entry [{0}] Exit [{1}]{2}", string.Join(", ", block.EntryBlocks.Select(x => _dissassembly.FormatAddress(x.Entry).Trim())), string.Join(", ", block.ExitBlocks.Select(x => _dissassembly.FormatAddress(x.Entry).Trim())), nl); } foreach (var i in block.Instructions) { if (embedSource) { var source = _dissassembly.FindSourceCode(i.Offset, false); if (source != null && lastSource != null && source.Document.Path != lastSource.Document.Path) { // print document name. sb.Append(" // ----- "); sb.Append(source.Document.Path); sb.Append(nl); lastSource = null; } if (source == null && lastSource != null) { sb.AppendLine(" // ----- (no source)"); } else if (source != null && (lastSource == null || !source.Position.EqualExceptOffset(lastSource.Position))) { if (options.HasFlag(FormatOptions.EmbedSourcePositions)) sb.AppendFormat(" // ----- Position: {0} - {1}{2}", source.Position.Start, source.Position.End, nl); if (options.HasFlag(FormatOptions.EmbedSourceCode)) { string[] lines = GetSourceCodeLines(source); if (lines != null) sb.AppendLine(" // " + string.Join(nl + " // ", lines)); } } lastSource = source; } sb.AppendLine(_dissassembly.FormatInstruction(i)); } } sb.AppendLine(); if (body.Exceptions.Any()) { sb.AppendLine("Exception handlers:"); foreach (var handler in body.Exceptions) { sb.AppendFormat("\t{0} - {1}{2}", _dissassembly.FormatAddress(handler.TryStart), _dissassembly.FormatAddress(handler.TryEnd), nl); foreach (var c in handler.Catches) { sb.AppendFormat("\t\t{0} => {1}{2}", c.Type, _dissassembly.FormatAddress(c.Instruction), nl); } if (handler.CatchAll != null) { sb.AppendFormat("\t\t{0} => {1}{2}", "<any>", _dissassembly.FormatAddress(handler.CatchAll), nl); } } sb.AppendLine(); } if (_mapFile != null) { var typeEntry = _mapFile.GetTypeByNewName(_methodDef.Owner.Fullname); if (typeEntry != null) { var methodEntry = typeEntry.FindDexMethod(_methodDef.Name, _methodDef.Prototype.ToSignature()); if (methodEntry != null) { _registersToVariableNames = new Dictionary<string, string>(); var validParameters = methodEntry.Parameters.Where(x => !string.IsNullOrEmpty(x.Name)).ToList(); if (validParameters.Any()) { sb.AppendLine("Parameters:"); foreach (var p in validParameters) { var registerName = _dissassembly.FormatRegister(p.Register); sb.AppendFormat("\t{0} (r{1}) -> {2}{3}", registerName, p.Register, p.Name, nl); if(!string.IsNullOrEmpty(p.Name)) _registersToVariableNames.Add(registerName, p.Name); } sb.AppendLine(); } var validVariables = methodEntry.Variables.Where(x => !string.IsNullOrEmpty(x.Name)).ToList(); if (validVariables.Any()) { sb.AppendLine("Variables:"); foreach (var p in validVariables) { var registerName = _dissassembly.FormatRegister(p.Register); sb.AppendFormat("\t{0} -> {1}{2}", registerName, p.Name, nl); if (!string.IsNullOrEmpty(p.Name)) _registersToVariableNames.Add(registerName, p.Name); } sb.AppendLine(); } sb.AppendLine("Source code positions:"); Document lastDocument = null; foreach (var row in _mapFile.GetSourceCodePositions(methodEntry)) { if (row.Document != lastDocument) { sb.AppendFormat("\t{0}{1}", row.Document.Path, nl); lastDocument = row.Document; } var pos = row.Position; sb.AppendFormat("\t{0}\t({1},{2}) - ({3},{4}){5}", MethodDisassembly.FormatOffset(pos.MethodOffset), pos.Start.Line, pos.Start.Column, pos.End.Line, pos.End.Column, nl); } } } } return sb.ToString(); }
private static unsafe void ConvertIntegerToString(byte *dest, ref int destIndex, int destLength, long value, FormatOptions options) { var basis = options.GetBase(); if (basis < 2 || basis > 36) { return; } // Calculate the full length (including zero padding) int length = 0; var tmp = value; do { tmp /= basis; length++; } while (tmp != 0); // Write the characters for the numbers to a temp buffer byte *tmpBuffer = stackalloc byte[length + 1]; tmp = value; int tmpIndex = length - 1; do { tmpBuffer[tmpIndex--] = ValueToIntegerChar((int)(tmp % basis), options.Uppercase); tmp /= basis; } while (tmp != 0); tmpBuffer[length] = 0; var numberBuffer = new NumberBuffer(NumberBufferKind.Integer, tmpBuffer, length, length, value < 0); FormatNumber(dest, ref destIndex, destLength, ref numberBuffer, options.Specifier, options); }
private static unsafe void FormatGeneral(byte *dest, ref int destIndex, int destLength, ref NumberBuffer number, int nMaxDigits, byte expChar) { int scale = number.Scale; int digPos = scale; bool scientific = false; // Don't switch to scientific notation if (digPos > nMaxDigits || digPos < -3) { digPos = 1; scientific = true; } byte *dig = number.GetDigitsPointer(); if (number.IsNegative) { if (destIndex >= destLength) { return; } dest[destIndex++] = (byte)'-'; } if (digPos > 0) { do { if (destIndex >= destLength) { return; } dest[destIndex++] = (*dig != 0) ? (byte)(*dig++) : (byte)'0'; } while (--digPos > 0); } else { if (destIndex >= destLength) { return; } dest[destIndex++] = (byte)'0'; } if (*dig != 0 || digPos < 0) { if (destIndex >= destLength) { return; } dest[destIndex++] = (byte)'.'; while (digPos < 0) { if (destIndex >= destLength) { return; } dest[destIndex++] = (byte)'0'; digPos++; } while (*dig != 0) { if (destIndex >= destLength) { return; } dest[destIndex++] = *dig++; } } if (scientific) { if (destIndex >= destLength) { return; } dest[destIndex++] = expChar; int exponent = number.Scale - 1; var exponentFormatOptions = new FormatOptions(NumberFormatKind.DecimalForceSigned, 0, 2, false); ConvertIntegerToString(dest, ref destIndex, destLength, exponent, exponentFormatOptions); } }
public IFormattedText FormatText(string text, FormatOptions formatOptions) { var colorStack = new Stack<Color>(); colorStack.Push(Color.White); var fontMetrics = m_registeredFonts[GetFontId(formatOptions.Font)]; var ansiFontMetrics = m_registeredFonts[GetFontId(formatOptions.AnsiFont)]; var ascentOffset = Math.Max(fontMetrics.m_ascentInPixels, ansiFontMetrics.m_ascentInPixels) - fontMetrics.m_ascentInPixels; var ansiAscentOffset = Math.Max(fontMetrics.m_ascentInPixels, ansiFontMetrics.m_ascentInPixels) - ansiFontMetrics.m_ascentInPixels; float currentX = 0; float currentY = 0; // ensures the last line string textCopy = text.EndsWith("\n") ? text : text + "\n"; var charArray = textCopy.ToArray(); var glyphs = new List<FormattedGlyph>(); var lines = new List<FormattedText.FormattedLine>(); var maxLineWidth = 0.0f; var lineHeight = Math.Max(fontMetrics.m_fontObject.Height, ansiFontMetrics.m_fontObject.Height); var lineSpacing = formatOptions.LineSpacing + lineHeight; for (int i = 0; i < charArray.Length; ++i) { var ch = charArray[i]; if (ch == ' ') { var fg = new FormattedGlyph { m_pos = new Vector2(currentX, IsAnsiChar(ch) ? ansiAscentOffset : ascentOffset), m_width = ansiFontMetrics.m_spaceWidth, m_color = colorStack.Peek(), m_glyph = ch, }; glyphs.Add(fg); currentX += fg.m_width; } else if (ch == '\x3000') { var fg = new FormattedGlyph { m_pos = new Vector2(currentX, IsAnsiChar(ch) ? ansiAscentOffset : ascentOffset), m_width = ansiFontMetrics.m_fullWidthSpaceWidth, m_color = colorStack.Peek(), m_glyph = ch, }; glyphs.Add(fg); currentX += fg.m_width; } else if (ch == '\t') { var fg = new FormattedGlyph { m_pos = new Vector2(currentX, IsAnsiChar(ch) ? ansiAscentOffset : ascentOffset), m_width = ansiFontMetrics.m_spaceWidth * formatOptions.TabSpaces, m_color = colorStack.Peek(), m_glyph = ch, }; glyphs.Add(fg); currentX += fg.m_width;; } else if (ch == '\n') { var line = new FormattedText.FormattedLine(); line.m_glyphs = glyphs.ToArray(); line.m_offset = new Vector2(0, currentY); var lineWidth = Math.Max(currentX - formatOptions.CharSpacing, 0); maxLineWidth = Math.Max(maxLineWidth, lineWidth); if (formatOptions.Alignment == Alignment.CenterTop || formatOptions.Alignment == Alignment.CenterMiddle || formatOptions.Alignment == Alignment.CenterBottom) { line.m_offset.X = -lineWidth * 0.5f; } else if (formatOptions.Alignment == Alignment.RightTop || formatOptions.Alignment == Alignment.RightMiddle || formatOptions.Alignment == Alignment.RightBottom) { line.m_offset.X = -lineWidth; } currentY += lineSpacing; currentX = 0; glyphs.Clear(); lines.Add(line); } else { if (!formatOptions.DisableRTF && ch == '[' && i + 1 < charArray.Length) { if (charArray[i + 1] != '[') { int j = i + 1; for (; j < charArray.Length; ++j) { if (charArray[j] == ']') { break; } } string token = new string(charArray, i + 1, j - i - 1); if (token.StartsWith("color:", StringComparison.InvariantCultureIgnoreCase)) { string colorCode = token.Substring(6); // use Style library color syntax var color = Style.Values.Color.Parse(colorCode); colorStack.Push(new Color(color.Red, color.Green, color.Blue, color.Alpha)); } else if (token == "/color" && colorStack.Count > 1) { colorStack.Pop(); } i = j; continue; } else { ++i; } } var glyphData = Load(ch, formatOptions); var fg = new FormattedGlyph { m_pos = new Vector2(currentX, IsAnsiChar(ch) ? ansiAscentOffset : ascentOffset), m_width = glyphData.m_glyphSize.Width, m_color = colorStack.Peek(), m_glyph = ch, }; glyphs.Add(fg); currentX += fg.m_width + formatOptions.CharSpacing; } } var offsetY = 0.0f; var textHeight = lines.Count > 0 ? lineSpacing * (lines.Count - 1) + lineHeight : 0; if (formatOptions.Alignment == Alignment.LeftMiddle || formatOptions.Alignment == Alignment.CenterMiddle || formatOptions.Alignment == Alignment.RightMiddle) { offsetY = -textHeight * 0.5f; } else if (formatOptions.Alignment == Alignment.LeftBottom || formatOptions.Alignment == Alignment.CenterBottom || formatOptions.Alignment == Alignment.RightBottom) { offsetY = -textHeight; } return new FormattedText { Text = text, FormatOptions = formatOptions, Offset = new Point(0, offsetY), Size = new Size(maxLineWidth, textHeight), RichTextFormat = !formatOptions.DisableRTF, m_lines = lines.ToArray() }; }
internal void Encode(FormatOptions options, StringBuilder builder, ref int lineLength) { builder.Append(';'); lineLength++; // try to put the entire result on 1 line var complete = ToString(); if (complete.Length + 1 < options.MaxLineLength) { // if it fits, it sits... if (lineLength + complete.Length + 1 > options.MaxLineLength) { builder.Append(options.NewLine); builder.Append('\t'); lineLength = 1; } else { builder.Append(' '); lineLength++; } lineLength += complete.Length; builder.Append(complete); return; } // Note: if we've made it this far, then we can't put everything on one line... var tokens = new List <string> (); tokens.Add(" "); if (Version.HasValue) { var version = Version.Value.ToString(CultureInfo.InvariantCulture); if (Method.Length + 1 + version.Length + 1 + Result.Length < options.MaxLineLength) { tokens.Add($"{Method}/{version}={Result}"); } else if (Method.Length + 1 + version.Length < options.MaxLineLength) { tokens.Add($"{Method}/{version}"); tokens.Add("="); tokens.Add(Result); } else { tokens.Add(Method); tokens.Add("/"); tokens.Add(version); tokens.Add("="); tokens.Add(Result); } } else { if (Method.Length + 1 + Result.Length < options.MaxLineLength) { tokens.Add($"{Method}={Result}"); } else { // we will have to break this up into individual tokens tokens.Add(Method); tokens.Add("="); tokens.Add(Result); } } if (!string.IsNullOrEmpty(ResultComment)) { tokens.Add(" "); tokens.Add($"({ResultComment})"); } if (!string.IsNullOrEmpty(Reason)) { var reason = MimeUtils.Quote(Reason); tokens.Add(" "); if ("reason=".Length + reason.Length < options.MaxLineLength) { tokens.Add($"reason={reason}"); } else { tokens.Add("reason="); tokens.Add(reason); } } for (int i = 0; i < Properties.Count; i++) { Properties[i].AppendTokens(options, tokens); } builder.AppendTokens(options, ref lineLength, tokens); }
static bool ShouldMergeWords (FormatOptions options, Encoding charset, IList<Word> words, Word word, int i) { Word next = words[i]; int lwspCount = next.StartIndex - (word.StartIndex + word.CharCount); int length = word.ByteCount + lwspCount + next.ByteCount; int encoded = word.EncodeCount + next.EncodeCount; int quoted = word.QuotedPairs + next.QuotedPairs; switch (word.Type) { case WordType.Atom: if (next.Type == WordType.EncodedWord) return false; return length + 1 < options.MaxLineLength; case WordType.QuotedString: if (next.Type == WordType.EncodedWord) return false; return length + quoted + 3 < options.MaxLineLength; case WordType.EncodedWord: if (next.Type == WordType.Atom) { // whether we merge or not is dependent upon: // 1. the number of atoms in a row after 'word' // 2. if there is another encoded-word after // the string of atoms. bool merge = false; int natoms = 0; for (int j = i + 1; j < words.Count && natoms < 3; j++) { if (words[j].Type != WordType.Atom) { merge = true; break; } natoms++; } // if all the words after the encoded-word are atoms, don't merge if (!merge) return false; } // avoid merging with qstrings if (next.Type == WordType.QuotedString) return false; switch (Math.Max (word.Encoding, next.Encoding)) { case 1: length = EstimateEncodedWordLength ("iso-8859-1", length, encoded); break; case 0: length = EstimateEncodedWordLength ("us-ascii", length, encoded); break; default: length = EstimateEncodedWordLength (charset, length, encoded); break; } return length + 1 < options.MaxLineLength; default: return false; } }
protected override Void AppendNameForNestedType(StringBuilder sb, DefType nestedType, DefType containingType, FormatOptions options) { if ((options & FormatOptions.NamespaceQualify) != 0) { AppendName(sb, containingType, options); sb.Append('+'); } sb.Append(nestedType.Name); return(Void.Value); }
public static StringBuilder AppendFolded(this StringBuilder text, FormatOptions options, string value, ref int lineLength) { int wordIndex = 0; int lwspIndex; while (wordIndex < value.Length) { lwspIndex = wordIndex; if (value[wordIndex] == '"') { // quoted string; don't break these up... lwspIndex++; while (lwspIndex < value.Length && value[lwspIndex] != '"') { if (value[lwspIndex] == '\\') { lwspIndex++; if (lwspIndex < value.Length) { lwspIndex++; } } else { lwspIndex++; } } } else { // normal word while (lwspIndex < value.Length && !char.IsWhiteSpace(value[lwspIndex])) { lwspIndex++; } } int length = lwspIndex - wordIndex; if (lineLength > 1 && (lineLength + length) > options.MaxLineLength) { text.LineWrap(options); lineLength = 1; } text.Append(value, wordIndex, length); lineLength += length; wordIndex = lwspIndex; while (wordIndex < value.Length && char.IsWhiteSpace(value[wordIndex])) { wordIndex++; } if (wordIndex < value.Length && wordIndex > lwspIndex) { text.Append(' '); lineLength++; } } return(text); }
public override Void AppendName(StringBuilder sb, GenericParameterDesc type, FormatOptions options) { sb.Append(type.Name); return(Void.Value); }
internal async Task <string> TestFormatWorkspaceAsync( string workspaceFilePath, string[] include, string[] exclude, bool includeGenerated, int expectedExitCode, int expectedFilesFormatted, int expectedFileCount, FixCategory fixCategory = FixCategory.Whitespace, DiagnosticSeverity codeStyleSeverity = DiagnosticSeverity.Error, DiagnosticSeverity analyzerSeverity = DiagnosticSeverity.Error, string[] diagnostics = null, bool noRestore = false, bool saveFormattedFiles = false) { var currentDirectory = Environment.CurrentDirectory; Environment.CurrentDirectory = TestProjectsPathHelper.GetProjectsDirectory(); var workspacePath = Path.GetFullPath(workspaceFilePath); WorkspaceType workspaceType; if (Directory.Exists(workspacePath)) { workspaceType = WorkspaceType.Folder; } else { workspaceType = workspacePath.EndsWith("proj") ? WorkspaceType.Project : WorkspaceType.Solution; } var logger = new TestLogger(); var msBuildPath = MSBuildRegistrar.RegisterInstance(); logger.LogTrace(Resources.Using_msbuildexe_located_in_0, msBuildPath); var fileMatcher = SourceFileMatcher.CreateMatcher(include, exclude); var formatOptions = new FormatOptions( workspacePath, workspaceType, noRestore, LogLevel.Trace, fixCategory, codeStyleSeverity, analyzerSeverity, diagnostics?.ToImmutableHashSet() ?? ImmutableHashSet <string> .Empty, saveFormattedFiles, ChangesAreErrors: false, fileMatcher, ReportPath: string.Empty, IncludeGeneratedFiles: includeGenerated, BinaryLogPath: null); var formatResult = await CodeFormatter.FormatWorkspaceAsync(formatOptions, logger, CancellationToken.None); Environment.CurrentDirectory = currentDirectory; var log = logger.GetLog(); try { Assert.Equal(expectedExitCode, formatResult.ExitCode); Assert.Equal(expectedFilesFormatted, formatResult.FilesFormatted); Assert.Equal(expectedFileCount, formatResult.FileCount); } catch { _output.WriteLine(log); throw; } return(log); }
public static IAsyncDownloader CreateDownloader(bool playlist, FileNameOptions fileName, FormatOptions format) { var downloader = new AsyncVideoDownloader(fileName, format); if (playlist) { return(new AsyncPlaylistDownloader(fileName, downloader)); } else { return(downloader); } }
/// <summary> /// Initializes a new instance of the <see cref="MailKit.Net.Imap.ImapCommand"/> class. /// </summary> /// <remarks> /// Creates a new <see cref="MailKit.Net.Imap.ImapCommand"/>. /// </remarks> /// <param name="engine">The IMAP engine that will be sending the command.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <param name="folder">The IMAP folder that the command operates on.</param> /// <param name="options">The formatting options.</param> /// <param name="format">The command format.</param> /// <param name="args">The command arguments.</param> public ImapCommand(ImapEngine engine, CancellationToken cancellationToken, ImapFolder folder, FormatOptions options, string format, params object[] args) { UntaggedHandlers = new Dictionary <string, ImapUntaggedHandler> (); Logout = format.Equals("LOGOUT\r\n", StringComparison.Ordinal); RespCodes = new List <ImapResponseCode> (); CancellationToken = cancellationToken; Response = ImapCommandResponse.None; Status = ImapCommandStatus.Created; Engine = engine; Folder = folder; using (var builder = new MemoryStream()) { int argc = 0; byte[] buf; string str; for (int i = 0; i < format.Length; i++) { if (format[i] == '%') { switch (format[++i]) { case '%': // a literal % builder.WriteByte((byte)'%'); break; case 'd': // an integer str = ((int)args[argc++]).ToString(CultureInfo.InvariantCulture); buf = Encoding.ASCII.GetBytes(str); builder.Write(buf, 0, buf.Length); break; case 'u': // an unsigned integer str = ((uint)args[argc++]).ToString(CultureInfo.InvariantCulture); buf = Encoding.ASCII.GetBytes(str); builder.Write(buf, 0, buf.Length); break; case 'F': // an ImapFolder var utf7 = ((ImapFolder)args[argc++]).EncodedName; AppendString(options, true, builder, utf7); break; case 'L': // a MimeMessage var literal = new ImapLiteral(options, (MimeMessage)args[argc++], UpdateProgress); var prefix = options.International ? UTF8LiteralTokenPrefix : LiteralTokenPrefix; var length = literal.Length; bool wait = true; builder.Write(prefix, 0, prefix.Length); buf = Encoding.ASCII.GetBytes(length.ToString(CultureInfo.InvariantCulture)); builder.Write(buf, 0, buf.Length); if (CanUseNonSynchronizedLiteral(length)) { builder.WriteByte((byte)'+'); wait = false; } builder.Write(LiteralTokenSuffix, 0, LiteralTokenSuffix.Length); totalSize += length; parts.Add(new ImapCommandPart(builder.ToArray(), literal, wait)); builder.SetLength(0); if (options.International) { builder.WriteByte((byte)')'); } break; case 'S': // a string which may need to be quoted or made into a literal AppendString(options, true, builder, (string)args[argc++]); break; case 'Q': // similar to %S but string must be quoted at a minimum AppendString(options, false, builder, (string)args[argc++]); break; default: throw new FormatException(); } } else { builder.WriteByte((byte)format[i]); } } parts.Add(new ImapCommandPart(builder.ToArray(), null)); } }
protected override Void AppendNameForInstantiatedType(StringBuilder sb, DefType type, FormatOptions options) { AppendName(sb, type.GetTypeDefinition(), options); FormatOptions parameterOptions = options & ~FormatOptions.AssemblyQualify; sb.Append('<'); for (int i = 0; i < type.Instantiation.Length; i++) { if (i != 0) { sb.Append(','); } AppendName(sb, type.Instantiation[i], parameterOptions); } sb.Append('>'); return(Void.Value); }
/// <summary> /// Encodes the unstructured text. /// </summary> /// <remarks> /// Encodes the unstructured text according to the rules of rfc2047 /// using the specified charset encoding and formatting options. /// </remarks> /// <returns>The encoded text.</returns> /// <param name="options">The formatting options</param> /// <param name="charset">The charset encoding.</param> /// <param name="text">The text to encode.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="options"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="charset"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="text"/> is <c>null</c>.</para> /// </exception> public static byte[] EncodeText (FormatOptions options, Encoding charset, string text) { if (options == null) throw new ArgumentNullException ("options"); if (charset == null) throw new ArgumentNullException ("charset"); if (text == null) throw new ArgumentNullException ("text"); return Encode (options, charset, text, false); }
/// <summary> /// 序列化对象为键值对 /// </summary> /// <param name="name">对象名称</param> /// <param name="obj">对象实例</param> /// <param name="options">选项</param> /// <returns></returns> public IEnumerable <KeyValuePair <string, string> > Serialize(string name, object obj, FormatOptions options) { if (obj == null) { return(Enumerable.Empty <KeyValuePair <string, string> >()); } if (options == null) { options = new FormatOptions(); } var setting = this.CreateSerializerSettings(options); var serializer = JsonSerializer.Create(setting); var keyValuesWriter = new KeyValuesWriter(name); serializer.Serialize(keyValuesWriter, obj); return(keyValuesWriter); }
public override Void AppendName(StringBuilder sb, SignatureTypeVariable type, FormatOptions options) { sb.Append("!"); sb.Append(type.Index); return(Void.Value); }
static bool ExceedsMaxLineLength (FormatOptions options, Encoding charset, Word word) { int length; switch (word.Type) { case WordType.EncodedWord: switch (word.Encoding) { case 1: length = EstimateEncodedWordLength ("iso-8859-1", word.ByteCount, word.EncodeCount); break; case 0: length = EstimateEncodedWordLength ("us-ascii", word.ByteCount, word.EncodeCount); break; default: length = EstimateEncodedWordLength (charset, word.ByteCount, word.EncodeCount); break; } break; case WordType.QuotedString: length = word.ByteCount + word.QuotedPairs + 2; break; default: length = word.ByteCount; break; } return length + 1 >= options.MaxLineLength; }
/// <summary> /// 序列化参数为键值对 /// </summary> /// <param name="parameter">参数</param> /// <param name="options">选项</param> /// <returns></returns> public IEnumerable <KeyValuePair <string, string> > Serialize(ApiParameterDescriptor parameter, FormatOptions options) { return(this.Serialize(parameter.Name, parameter.Value, options)); }
static byte[] Encode (FormatOptions options, Encoding charset, string text, bool phrase) { var mode = phrase ? QEncodeMode.Phrase : QEncodeMode.Text; var words = Merge (options, charset, GetRfc822Words (options, charset, text, phrase)); var str = new StringBuilder (); int start, length; Word prev = null; byte[] encoded; foreach (var word in words) { // append the correct number of spaces between words... if (prev != null && !(prev.Type == WordType.EncodedWord && word.Type == WordType.EncodedWord)) { start = prev.StartIndex + prev.CharCount; length = word.StartIndex - start; str.Append (text, start, length); } switch (word.Type) { case WordType.Atom: str.Append (text, word.StartIndex, word.CharCount); break; case WordType.QuotedString: AppendQuoted (str, text, word.StartIndex, word.CharCount); break; case WordType.EncodedWord: if (prev != null && prev.Type == WordType.EncodedWord) { // include the whitespace between these 2 words in the // resulting rfc2047 encoded-word. start = prev.StartIndex + prev.CharCount; length = (word.StartIndex + word.CharCount) - start; str.Append (phrase ? '\t' : ' '); } else { start = word.StartIndex; length = word.CharCount; } switch (word.Encoding) { case 0: // us-ascii AppendEncodedWord (str, Encoding.ASCII, text, start, length, mode); break; case 1: // iso-8859-1 AppendEncodedWord (str, CharsetUtils.Latin1, text, start, length, mode); break; default: // custom charset AppendEncodedWord (str, charset, text, start, length, mode); break; } break; } prev = word; } encoded = new byte[str.Length]; for (int i = 0; i < str.Length; i++) encoded[i] = (byte) str[i]; return encoded; }
/// <summary> /// Asynchronously send the specified message. /// </summary> /// <remarks> /// <para>Asynchronously sends the specified message.</para> /// <para>The sender address is determined by checking the following /// message headers (in order of precedence): Resent-Sender, /// Resent-From, Sender, and From.</para> /// <para>If either the Resent-Sender or Resent-From addresses are present, /// the recipients are collected from the Resent-To, Resent-Cc, and /// Resent-Bcc headers, otherwise the To, Cc, and Bcc headers are used.</para> /// </remarks> /// <returns>An asynchronous task context.</returns> /// <param name="options">The formatting options.</param> /// <param name="message">The message.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <param name="progress">The progress reporting mechanism.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="options"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="message"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ObjectDisposedException"> /// The <see cref="MailTransport"/> has been disposed. /// </exception> /// <exception cref="ServiceNotConnectedException"> /// The <see cref="MailTransport"/> is not connected. /// </exception> /// <exception cref="ServiceNotAuthenticatedException"> /// Authentication is required before sending a message. /// </exception> /// <exception cref="System.InvalidOperationException"> /// <para>A sender has not been specified.</para> /// <para>-or-</para> /// <para>No recipients have been specified.</para> /// </exception> /// <exception cref="System.OperationCanceledException"> /// The operation has been canceled. /// </exception> /// <exception cref="System.NotSupportedException"> /// <para>Internationalized formatting was requested but is not supported by the transport.</para> /// </exception> /// <exception cref="System.IO.IOException"> /// An I/O error occurred. /// </exception> /// <exception cref="CommandException"> /// The send command failed. /// </exception> /// <exception cref="ProtocolException"> /// A protocol exception occurred. /// </exception> public abstract Task SendAsync(FormatOptions options, MimeMessage message, CancellationToken cancellationToken = default(CancellationToken), ITransferProgress progress = null);
internal static byte[] FoldUnstructuredHeader (FormatOptions options, string field, byte[] text) { unsafe { fixed (byte* inbuf = text) { var tokens = TokenizeText (ParserOptions.Default, inbuf, 0, text.Length); return FoldTokens (options, tokens, field, text); } } }
/// <summary> /// Asynchronously send the specified message using the supplied sender and recipients. /// </summary> /// <remarks> /// Asynchronously sends the specified message using the supplied sender and recipients. /// </remarks> /// <returns>An asynchronous task context.</returns> /// <param name="options">The formatting options.</param> /// <param name="message">The message.</param> /// <param name="sender">The mailbox address to use for sending the message.</param> /// <param name="recipients">The mailbox addresses that should receive the message.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <param name="progress">The progress reporting mechanism.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="options"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="message"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="sender"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="recipients"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ObjectDisposedException"> /// The <see cref="MailTransport"/> has been disposed. /// </exception> /// <exception cref="ServiceNotConnectedException"> /// The <see cref="MailTransport"/> is not connected. /// </exception> /// <exception cref="ServiceNotAuthenticatedException"> /// Authentication is required before sending a message. /// </exception> /// <exception cref="System.InvalidOperationException"> /// <para>A sender has not been specified.</para> /// <para>-or-</para> /// <para>No recipients have been specified.</para> /// </exception> /// <exception cref="System.OperationCanceledException"> /// The operation has been canceled. /// </exception> /// <exception cref="System.NotSupportedException"> /// <para>Internationalized formatting was requested but is not supported by the transport.</para> /// </exception> /// <exception cref="System.IO.IOException"> /// An I/O error occurred. /// </exception> /// <exception cref="CommandException"> /// The send command failed. /// </exception> /// <exception cref="ProtocolException"> /// A protocol exception occurred. /// </exception> public abstract Task SendAsync(FormatOptions options, MimeMessage message, MailboxAddress sender, IEnumerable <MailboxAddress> recipients, CancellationToken cancellationToken = default(CancellationToken), ITransferProgress progress = null);
void DkimSign(FormatOptions options, MimeMessage message, IList <string> headers) { var value = new StringBuilder("v=1"); var t = GetTimestamp(); byte[] signature, hash; Header dkim; options = options.Clone(); options.NewLineFormat = NewLineFormat.Dos; options.EnsureNewLine = true; switch (SignatureAlgorithm) { case DkimSignatureAlgorithm.Ed25519Sha256: value.Append("; a=ed25519-sha256"); break; case DkimSignatureAlgorithm.RsaSha256: value.Append("; a=rsa-sha256"); break; default: value.Append("; a=rsa-sha1"); break; } value.AppendFormat("; d={0}; s={1}", Domain, Selector); value.AppendFormat("; c={0}/{1}", HeaderCanonicalizationAlgorithm.ToString().ToLowerInvariant(), BodyCanonicalizationAlgorithm.ToString().ToLowerInvariant()); if (!string.IsNullOrEmpty(QueryMethod)) { value.AppendFormat("; q={0}", QueryMethod); } if (!string.IsNullOrEmpty(AgentOrUserIdentifier)) { value.AppendFormat("; i={0}", AgentOrUserIdentifier); } value.AppendFormat("; t={0}", t); using (var stream = new DkimSignatureStream(CreateSigningContext())) { using (var filtered = new FilteredStream(stream)) { filtered.Add(options.CreateNewLineFilter()); // write the specified message headers DkimVerifierBase.WriteHeaders(options, message, headers, HeaderCanonicalizationAlgorithm, filtered); value.AppendFormat("; h={0}", string.Join(":", headers.ToArray())); hash = message.HashBody(options, SignatureAlgorithm, BodyCanonicalizationAlgorithm, -1); value.AppendFormat("; bh={0}", Convert.ToBase64String(hash)); value.Append("; b="); dkim = new Header(HeaderId.DkimSignature, value.ToString()); message.Headers.Insert(0, dkim); switch (HeaderCanonicalizationAlgorithm) { case DkimCanonicalizationAlgorithm.Relaxed: DkimVerifierBase.WriteHeaderRelaxed(options, filtered, dkim, true); break; default: DkimVerifierBase.WriteHeaderSimple(options, filtered, dkim, true); break; } filtered.Flush(); } signature = stream.GenerateSignature(); dkim.Value += Convert.ToBase64String(signature); } }
public MimeParserTests() { UnixFormatOptions = FormatOptions.Default.Clone(); UnixFormatOptions.NewLineFormat = NewLineFormat.Unix; }
internal void Encode(FormatOptions options, StringBuilder builder, int lineLength) { int space = 1; if (Instance.HasValue) { var i = Instance.Value.ToString(CultureInfo.InvariantCulture); builder.AppendFormat(" i={0};", i); lineLength += 4 + i.Length; } if (lineLength + space + AuthenticationServiceIdentifier.Length > options.MaxLineLength) { builder.Append(options.NewLine); builder.Append('\t'); lineLength = 1; space = 0; } if (space > 0) { builder.Append(' '); lineLength++; } builder.Append(AuthenticationServiceIdentifier); lineLength += AuthenticationServiceIdentifier.Length; if (Version.HasValue) { var version = Version.Value.ToString(CultureInfo.InvariantCulture); if (lineLength + 1 + version.Length > options.MaxLineLength) { builder.Append(options.NewLine); builder.Append('\t'); lineLength = 1; } else { builder.Append(' '); lineLength++; } lineLength += version.Length; builder.Append(version); } if (Results.Count > 0) { for (int i = 0; i < Results.Count; i++) { Results[i].Encode(options, builder, ref lineLength); } } else { builder.Append("; none"); } builder.Append(options.NewLine); }
public bool CanFormat(Type type, FormatOptions options) => !type.IsPrimitive && !type.IsValueType;
private static unsafe void FormatNumber(byte *dest, ref int destIndex, int destLength, ref NumberBuffer number, int nMaxDigits, FormatOptions options) { bool isCorrectlyRounded = (number.Kind == NumberBufferKind.Float); // If we have an integer, and the rendering is the default `G`, then use Decimal rendering which is faster if (number.Kind == NumberBufferKind.Integer && options.Kind == NumberFormatKind.General && options.Specifier == 0) { options.Kind = NumberFormatKind.Decimal; } int length; switch (options.Kind) { case NumberFormatKind.DecimalForceSigned: case NumberFormatKind.Decimal: case NumberFormatKind.Hexadecimal: length = number.DigitsCount; var zeroPadding = (int)options.Specifier; int actualZeroPadding = 0; if (length < zeroPadding) { actualZeroPadding = zeroPadding - length; length = zeroPadding; } bool outputPositiveSign = options.Kind == NumberFormatKind.DecimalForceSigned; length += number.IsNegative || outputPositiveSign ? 1 : 0; // Perform left align if (AlignLeft(dest, ref destIndex, destLength, options.AlignAndSize, length)) { return; } FormatDecimalOrHexadecimal(dest, ref destIndex, destLength, ref number, actualZeroPadding, outputPositiveSign); // Perform right align AlignRight(dest, ref destIndex, destLength, options.AlignAndSize, length); break; default: case NumberFormatKind.General: if (nMaxDigits < 1) { // This ensures that the PAL code pads out to the correct place even when we use the default precision nMaxDigits = number.DigitsCount; } RoundNumber(ref number, nMaxDigits, isCorrectlyRounded); // Calculate final rendering length length = GetLengthForFormatGeneral(ref number, nMaxDigits); // Perform left align if (AlignLeft(dest, ref destIndex, destLength, options.AlignAndSize, length)) { return; } // Format using general formatting FormatGeneral(dest, ref destIndex, destLength, ref number, nMaxDigits, options.Uppercase ? (byte)'E' : (byte)'e'); // Perform right align AlignRight(dest, ref destIndex, destLength, options.AlignAndSize, length); break; } }
/// <summary> /// Get double value parameter in ProjectUnits /// </summary> public static double AsProjectUnitTypeDouble( this Parameter param) { if (param.StorageType != StorageType.Double) { throw new NotSupportedException( "Parameter does not have double value"); } double imperialValue = param.AsDouble(); Document document = param.Element.Document; UnitType ut = ConvertParameterTypeToUnitType( param.Definition.ParameterType); //FormatOptions fo = document.ProjectUnit // 2013 // .get_FormatOptions(ut); //DisplayUnitType dut = fo.Units; // 2014 FormatOptions fo = document.GetUnits() // 2014 .GetFormatOptions(ut); DisplayUnitType dut = fo.DisplayUnits; // 2014 // Unit Converter // http://www.asknumbers.com switch (dut) { #region Length case DisplayUnitType.DUT_METERS: return(imperialValue * METERS_IN_FEET); //feet case DisplayUnitType.DUT_CENTIMETERS: return(imperialValue * METERS_IN_FEET * 100); case DisplayUnitType.DUT_DECIMAL_FEET: return(imperialValue); case DisplayUnitType.DUT_DECIMAL_INCHES: return(imperialValue * 12); case DisplayUnitType.DUT_FEET_FRACTIONAL_INCHES: NotSupported(dut); break; case DisplayUnitType.DUT_FRACTIONAL_INCHES: NotSupported(dut); break; case DisplayUnitType.DUT_METERS_CENTIMETERS: return(imperialValue * METERS_IN_FEET); //feet case DisplayUnitType.DUT_MILLIMETERS: return(imperialValue * METERS_IN_FEET * 1000); #endregion // Length #region Area case DisplayUnitType.DUT_SQUARE_FEET: return(imperialValue); case DisplayUnitType.DUT_ACRES: return(imperialValue * 1 / 43560.039); case DisplayUnitType.DUT_HECTARES: return(imperialValue * 1 / 107639.104); case DisplayUnitType.DUT_SQUARE_CENTIMETERS: return(imperialValue * Math.Pow(METERS_IN_FEET * 100, 2)); case DisplayUnitType.DUT_SQUARE_INCHES: return(imperialValue * Math.Pow(12, 2)); case DisplayUnitType.DUT_SQUARE_METERS: return(imperialValue * Math.Pow(METERS_IN_FEET, 2)); case DisplayUnitType.DUT_SQUARE_MILLIMETERS: return(imperialValue * Math.Pow(METERS_IN_FEET * 1000, 2)); #endregion // Area #region Volume case DisplayUnitType.DUT_CUBIC_FEET: return(imperialValue); case DisplayUnitType.DUT_CUBIC_CENTIMETERS: return(imperialValue * Math.Pow(METERS_IN_FEET * 100, 3)); case DisplayUnitType.DUT_CUBIC_INCHES: return(imperialValue * Math.Pow(12, 3)); case DisplayUnitType.DUT_CUBIC_METERS: return(imperialValue * Math.Pow(METERS_IN_FEET, 3)); case DisplayUnitType.DUT_CUBIC_MILLIMETERS: return(imperialValue * Math.Pow(METERS_IN_FEET * 1000, 3)); case DisplayUnitType.DUT_CUBIC_YARDS: return(imperialValue * 1 / Math.Pow(3, 3)); case DisplayUnitType.DUT_GALLONS_US: return(imperialValue * 7.5); case DisplayUnitType.DUT_LITERS: return(imperialValue * 28.31684); #endregion // Volume default: NotSupported(dut); break; } throw new NotSupportedException(); }
/// <summary> /// Initializes a new instance of the <see cref="MailKit.Net.Imap.ImapCommand"/> class. /// </summary> /// <remarks> /// Creates a new <see cref="MailKit.Net.Imap.ImapCommand"/>. /// </remarks> /// <param name="engine">The IMAP engine that will be sending the command.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <param name="folder">The IMAP folder that the command operates on.</param> /// <param name="options">The formatting options.</param> /// <param name="format">The command format.</param> /// <param name="args">The command arguments.</param> public ImapCommand(ImapEngine engine, CancellationToken cancellationToken, ImapFolder folder, FormatOptions options, string format, params object[] args) { UntaggedHandlers = new Dictionary <string, ImapUntaggedHandler> (); RespCodes = new List <ImapResponseCode> (); CancellationToken = cancellationToken; Response = ImapCommandResponse.None; Status = ImapCommandStatus.Created; Engine = engine; Folder = folder; using (var builder = new MemoryStream()) { var plus = (Engine.Capabilities & ImapCapabilities.LiteralPlus) != 0 ? "+" : string.Empty; int argc = 0; byte[] buf; string str; char c; for (int i = 0; i < format.Length; i++) { if (format[i] == '%') { switch (format[++i]) { case '%': // a literal % builder.WriteByte((byte)'%'); break; case 'c': // a character c = (char)args[argc++]; builder.WriteByte((byte)c); break; case 'd': // an integer str = ((int)args[argc++]).ToString(); buf = Encoding.ASCII.GetBytes(str); builder.Write(buf, 0, buf.Length); break; case 'u': // an unsigned integer str = ((uint)args[argc++]).ToString(); buf = Encoding.ASCII.GetBytes(str); builder.Write(buf, 0, buf.Length); break; case 'F': // an ImapFolder var utf7 = ((ImapFolder)args[argc++]).EncodedName; AppendString(options, true, builder, utf7); break; case 'L': var literal = new ImapLiteral(options, args[argc++], UpdateProgress); var length = literal.Length; totalSize += length; if (options.International) { str = "UTF8 (~{" + length + plus + "}\r\n"; } else { str = "{" + length + plus + "}\r\n"; } buf = Encoding.ASCII.GetBytes(str); builder.Write(buf, 0, buf.Length); parts.Add(new ImapCommandPart(builder.ToArray(), literal)); builder.SetLength(0); if (options.International) { builder.WriteByte((byte)')'); } break; case 'S': // a string which may need to be quoted or made into a literal AppendString(options, true, builder, (string)args[argc++]); break; case 'Q': // similar to %S but string must be quoted at a minimum AppendString(options, false, builder, (string)args[argc++]); break; case 's': // a safe atom string buf = Encoding.ASCII.GetBytes((string)args[argc++]); builder.Write(buf, 0, buf.Length); break; default: throw new FormatException(); } } else { builder.WriteByte((byte)format[i]); } } parts.Add(new ImapCommandPart(builder.ToArray(), null)); } }
public void DrawText(string text, FormatOptions formatOptions, Matrix transform) { DrawText(FormatText(text, formatOptions), transform, DrawOptions.Default); }
public static string FormatOperands(Instruction ins, MethodBody body, FormatOptions options = FormatOptions.Default) { StringBuilder ops = new StringBuilder(); bool fullTypeNames = options.HasFlag(FormatOptions.FullTypeNames); foreach (var r in ins.Registers) { if (ops.Length > 0) { ops.Append(","); Align(ops, 4); } ops.Append(FormatRegister(r, body)); } if (ops.Length == 0) ops.Append(" "); if (ins.Operand != null) { Align(ops, 12); if (ins.Operand is string) { ops.Append("\""); ops.Append(ins.Operand); ops.Append("\""); } else if (ins.Operand is sbyte) { FormatOperand_Integer(ops, (int)(byte)(sbyte)ins.Operand, "X2"); } else if (ins.Operand is short) { FormatOperand_Integer(ops, (int) (short) ins.Operand); } else if (ins.Operand is int) { FormatOperand_Integer(ops, (int) ins.Operand); } else if (ins.Operand is long) { var l = (long) ins.Operand; ops.Append(l); ops.Append(" (0x"); ops.Append(l.ToString("X8")); ops.Append(")"); } else if (ins.Operand is Instruction) { var target = (Instruction) ins.Operand; FormatOperand_Instruction(ops, ins, body, target, false); } else if (ins.Operand is ClassReference) { var m = (ClassReference) ins.Operand; ops.Append(fullTypeNames ? m.ToString() : m.Name); } else if (ins.Operand is MethodReference) { var m = (MethodReference) ins.Operand; var owner = fullTypeNames || !(m.Owner is ClassReference) ? m.ToString() : ((ClassReference) m.Owner).Name; ops.Append(owner + "::" + m.Name + m.Prototype); } else if (ins.Operand is FieldReference) { var m = (FieldReference) ins.Operand; ops.Append(fullTypeNames ? m.ToString() : m.Owner.Name + "::" + m.Name + " : " + m.Type); } else if (ins.Operand is PackedSwitchData) { var d = (PackedSwitchData) ins.Operand; FormatOperand_Integer(ops, d.FirstKey); ops.Append(":"); foreach (var target in d.Targets) { ops.Append(" "); FormatOperand_Instruction(ops, ins, body, target, true); } } else if (ins.Operand is SparseSwitchData) { var d = (SparseSwitchData) ins.Operand; bool isFirst = true; foreach (var target in d.Targets) { if (!isFirst) ops.Append(" "); ops.Append(target.Key); ops.Append(": "); FormatOperand_Instruction(ops, ins, body, target.Value, true); isFirst = false; } } else { ops.Append(ins.Operand); } if (options.HasFlag(FormatOptions.DebugOperandTypes)) ops.AppendFormat(" [{0}]", ins.Operand.GetType().Name); } var bstrOperands = ops.ToString(); return bstrOperands; }
public void DrawText(string text, FormatOptions formatOptions, Matrix transform, DrawOptions drawOptions) { DrawText(FormatText(text, formatOptions), transform, drawOptions); }
/// <summary> /// The methods prints an objects as a number using different format options /// </summary> /// <param name="number">the numeric objects</param> /// <param name="format">Enumeration of format options</param> public static void PrintAsNumber(object number, FormatOptions format) { switch (format) { case FormatOptions.FixedPoint: { Console.WriteLine("{0:f2}", number); return; } case FormatOptions.Percent: { Console.WriteLine("{0:p0}", number); return; } case FormatOptions.AlignRight: { Console.WriteLine("{0,8}", number); return; } default: throw new ArgumentException("Invalid format"); } }
// load one single glyph into the cache private GlyphData Load(char glyph, FormatOptions formatOptions) { int fontId = GetFontId(IsAnsiChar(glyph) ? formatOptions.AnsiFont : formatOptions.Font); var font = m_registeredFonts[fontId]; uint glyphId = ((uint)fontId << 16) + glyph; GlyphData glyphData; if (m_loadedGlyphs.TryGetValue(glyphId, out glyphData)) { glyphData.m_timeStamp = m_timeStamp; return glyphData; } var str = glyph.ToString(); var chRect = MeasureCharacter(glyph, m_registeredFonts[fontId].m_fontObject); chRect.Inflate(font.m_outlineThickness * 0.5f, font.m_outlineThickness * 0.5f); int width = Math.Max((int)Math.Ceiling(chRect.Width), 1); int height = Math.Max((int)Math.Ceiling(chRect.Height), 1); int pagesInX = (width - 1) / PageSize + 1; int pagesInY = (height - 1) / PageSize + 1; GlyphPage[] pages = new GlyphPage[pagesInX * pagesInY]; for (int i = 0; i < pages.Length; ++i) { pages[i].m_x = i % pagesInX; pages[i].m_y = i / pagesInX; pages[i].m_pageIndex = RequestPage(); } using (var bmp = new SystemDrawing.Bitmap(pagesInX * PageSize, pagesInY * PageSize)) using (var g = SystemDrawing.Graphics.FromImage(bmp)) using (var memStream = new MemoryStream()) { // draw text using GDI+ g.TextRenderingHint = SystemDrawing.Text.TextRenderingHint.AntiAliasGridFit; g.SmoothingMode = SystemDrawing.Drawing2D.SmoothingMode.AntiAlias; g.InterpolationMode = SystemDrawing.Drawing2D.InterpolationMode.HighQualityBicubic; if (font.m_outlineThickness > 0) { SystemDrawing.Pen outlinePen; if (!m_outlinePensWithWidths.TryGetValue(font.m_outlineThickness, out outlinePen)) { outlinePen = new SystemDrawing.Pen(SystemDrawing.Color.Gray, font.m_outlineThickness); outlinePen.MiterLimit = font.m_outlineThickness; m_outlinePensWithWidths.Add(font.m_outlineThickness, outlinePen); } // draw outline using (var outlinePath = new SystemDrawing.Drawing2D.GraphicsPath()) { outlinePath.AddString(str, font.m_fontObject.FontFamily, (int)font.m_fontObject.Style, g.DpiX * font.m_fontObject.SizeInPoints / 72, new SystemDrawing.PointF(-chRect.Left, -chRect.Top), SystemDrawing.StringFormat.GenericDefault); g.DrawPath(outlinePen, outlinePath); g.FillPath(m_whiteBrush, outlinePath); } } else { g.DrawString(str, font.m_fontObject, m_whiteBrush, new SystemDrawing.PointF(-chRect.Left, -chRect.Top)); } bmp.Save(memStream, System.Drawing.Imaging.ImageFormat.Png); using (var tmpTexture = Texture2D.FromStream(GameApp.Instance.GraphicsDevice, memStream)) { var device = GameApp.Instance.GraphicsDevice; device.DepthStencilState = DepthStencilState.None; device.RasterizerState = RasterizerState.CullCounterClockwise; device.Indices = null; m_effect.CurrentTechnique = m_techBlit; m_paramTexture.SetValue(tmpTexture); foreach (var batch in pages.GroupBy(page => page.m_pageIndex / PagesInOneCacheTexture)) { var textureId = batch.Key; device.SetRenderTarget(m_cacheTextures[textureId].m_physicalRTTexture); device.BlendState = m_channelMasks[textureId % 4]; var pagesInBatch = batch.ToArray(); var vertices = new VertexDataBlit[pagesInBatch.Length * 6]; for (int i = 0; i < pagesInBatch.Length; ++i) { var page = pagesInBatch[i]; var dstRectLeft = (page.m_pageIndex % PagesInOneCacheTexture) % PagesInOneRow * PageSize; var dstRectTop = (page.m_pageIndex % PagesInOneCacheTexture) / PagesInOneRow * PageSize; float posLeft = (dstRectLeft - 0.5f) / CacheTextureSize * 2 - 1; float posTop = 1 - (dstRectTop - 0.5f) / CacheTextureSize * 2; float posWidth = PageSize / (float)CacheTextureSize * 2; float posHeight = -PageSize / (float)CacheTextureSize * 2; float uvLeft = page.m_x / (float)pagesInX; float uvTop = page.m_y / (float)pagesInY; float uvWidth = 1.0f / pagesInX; float uvHeight = 1.0f / pagesInY; // left-top vertices[i * 6 + 0].pos = new Vector2(posLeft, posTop); vertices[i * 6 + 0].uv = new Vector2(uvLeft, uvTop); // right-top vertices[i * 6 + 1].pos = vertices[i * 6 + 4].pos = new Vector2(posLeft + posWidth, posTop); vertices[i * 6 + 1].uv = vertices[i * 6 + 4].uv = new Vector2(uvLeft + uvWidth, uvTop); // left-bottom vertices[i * 6 + 2].pos = vertices[i * 6 + 3].pos = new Vector2(posLeft, posTop + posHeight); vertices[i * 6 + 2].uv = vertices[i * 6 + 3].uv = new Vector2(uvLeft, uvTop + uvHeight); // right-bottom vertices[i * 6 + 5].pos = new Vector2(posLeft + posWidth, posTop + posHeight); vertices[i * 6 + 5].uv = new Vector2(uvLeft + uvWidth, uvTop + uvHeight); } foreach (var pass in m_techBlit.Passes) { pass.Apply(); device.DrawUserPrimitives(PrimitiveType.TriangleList, vertices, 0, pagesInBatch.Length * 2); } } device.SetRenderTarget(null); } } glyphData = new GlyphData(); glyphData.m_pageIndices = new int[pagesInX, pagesInY]; pages.ForEach(page => glyphData.m_pageIndices[page.m_x, page.m_y] = page.m_pageIndex); glyphData.m_glyphSize = chRect.Size; glyphData.m_timeStamp = m_timeStamp; m_loadedGlyphs.Add(glyphId, glyphData); return glyphData; }
Stream(ArrayList data, FormatOptions opt) { data.Add(new Snoop.Data.ClassSeparator(typeof(FormatOptions))); //data.Add( new Snoop.Data.String( "Name", opt.GetName() ) ); // 2015, jeremy: 'Autodesk.Revit.DB.FormatOptions.GetName()' is obsolete: 'This method is deprecated in Revit 2015. Use UnitUtils.GetTypeCatalogString(DisplayUnitType) instead.' data.Add( new Snoop.Data.String( "Name", UnitUtils.GetTypeCatalogString(opt.DisplayUnits) ) ); // 2016 data.Add(new Snoop.Data.Bool("Use default", opt.UseDefault)); if (!opt.UseDefault) { data.Add(new Snoop.Data.String("Units", opt.DisplayUnits.ToString())); data.Add(new Snoop.Data.String("Unit symbol", opt.UnitSymbol.ToString())); data.Add(new Snoop.Data.Double("Rounding", opt.Accuracy)); data.Add(new Snoop.Data.Bool("Suppress trailing zeros", opt.SuppressTrailingZeros)); data.Add(new Snoop.Data.Bool("Suppress leading zeros", opt.SuppressLeadingZeros)); data.Add(new Snoop.Data.Bool("Suppress spaces", opt.SuppressSpaces)); data.Add(new Snoop.Data.Bool("Use plus prefix", opt.UsePlusPrefix)); data.Add(new Snoop.Data.Bool("Use digit grouping", opt.UseDigitGrouping)); } }
/// <summary> /// Asynchronously generate an ARC-Authentication-Results header. /// </summary> /// <remarks> /// <para>Asynchronously generates an ARC-Authentication-Results header.</para> /// <para>If the returned <see cref="AuthenticationResults"/> contains a <see cref="AuthenticationMethodResult"/> /// with a <see cref="AuthenticationMethodResult.Method"/> equal to <c>"arc"</c>, then the /// <see cref="AuthenticationMethodResult.Result"/> will be used as the <c>cv=</c> tag value /// in the <c>ARC-Seal</c> header generated by the <see cref="ArcSigner"/>.</para> /// </remarks> /// <example> /// <code language="c#" source="Examples\ArcSignerExample.cs" /> /// </example> /// <param name="options">The format options.</param> /// <param name="message">The message to create the ARC-Authentication-Results header for.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The ARC-Authentication-Results header or <c>null</c> if the <see cref="ArcSigner"/> should not sign the message.</returns> protected abstract Task <AuthenticationResults> GenerateArcAuthenticationResultsAsync(FormatOptions options, MimeMessage message, CancellationToken cancellationToken);
async Task ArcSignAsync(FormatOptions options, MimeMessage message, IList <string> headers, bool doAsync, CancellationToken cancellationToken) { ArcVerifier.GetArcHeaderSets(message, true, out ArcHeaderSet[] sets, out int count); AuthenticationResults authres; int instance = count + 1; string cv; if (count > 0) { var parameters = sets[count - 1].ArcSealParameters; // do not sign if there is already a failed ARC-Seal. if (!parameters.TryGetValue("cv", out cv) || cv.Equals("fail", StringComparison.OrdinalIgnoreCase)) { return; } } options = options.Clone(); options.NewLineFormat = NewLineFormat.Dos; options.EnsureNewLine = true; if (doAsync) { authres = await GenerateArcAuthenticationResultsAsync(options, message, cancellationToken).ConfigureAwait(false); } else { authres = GenerateArcAuthenticationResults(options, message, cancellationToken); } if (authres == null) { return; } authres.Instance = instance; var aar = new Header(HeaderId.ArcAuthenticationResults, authres.ToString()); cv = "none"; if (count > 0) { cv = "pass"; foreach (var method in authres.Results) { if (method.Method.Equals("arc", StringComparison.OrdinalIgnoreCase)) { cv = method.Result; break; } } } var t = GetTimestamp(); var ams = GenerateArcMessageSignature(options, message, instance, t, headers); var seal = GenerateArcSeal(options, instance, cv, t, sets, count, aar, ams); message.Headers.Insert(0, aar); message.Headers.Insert(0, ams); message.Headers.Insert(0, seal); }
/// <summary> /// Digitally sign and seal a message using ARC. /// </summary> /// <remarks> /// Digitally signs and seals a message using ARC. /// </remarks> /// <example> /// <code language="c#" source="Examples\ArcSignerExample.cs" /> /// </example> /// <param name="options">The formatting options.</param> /// <param name="message">The message to sign.</param> /// <param name="headers">The list of header fields to sign.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="options"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="message"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="headers"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentException"> /// <para><paramref name="headers"/> does not contain the 'From' header.</para> /// <para>-or-</para> /// <para><paramref name="headers"/> contains one or more of the following headers: Return-Path, /// Received, Comments, Keywords, Bcc, Resent-Bcc, or DKIM-Signature.</para> /// </exception> /// <exception cref="System.FormatException"> /// One or more ARC headers either did not contain an instance tag or the instance tag was invalid. /// </exception> public void Sign(FormatOptions options, MimeMessage message, IList <HeaderId> headers, CancellationToken cancellationToken = default(CancellationToken)) { SignAsync(options, message, headers, false, cancellationToken).GetAwaiter().GetResult(); }
/// <summary> /// Creates or populates Revit elements based on the information contained in this class. /// </summary> /// <param name="doc">The document.</param> protected override void Create(Document doc) { Units documentUnits = new Units(doc.DisplayUnitSystem == DisplayUnit.METRIC ? UnitSystem.Metric : UnitSystem.Imperial); foreach (IFCUnit unit in UnitsInContext) { if (!IFCUnit.IsNullOrInvalid(unit)) { try { FormatOptions formatOptions = new FormatOptions(unit.UnitName); formatOptions.UnitSymbol = unit.UnitSymbol; documentUnits.SetFormatOptions(unit.UnitType, formatOptions); } catch (Exception ex) { Importer.TheLog.LogError(unit.Id, ex.Message, false); } } } doc.SetUnits(documentUnits); // We will randomize unused grid names so that they don't conflict with new entries with the same name. // This is only for relink. foreach (ElementId gridId in Importer.TheCache.GridNameToElementMap.Values) { Grid grid = doc.GetElement(gridId) as Grid; if (grid == null) continue; grid.Name = new Guid().ToString(); } base.Create(doc); // IfcProject usually won't create an element, as it contains no geometry. // If it doesn't, use the ProjectInfo element in the document to store its parameters. if (CreatedElementId == ElementId.InvalidElementId) CreatedElementId = Importer.TheCache.ProjectInformationId; }
/// <summary> /// Asynchronously digitally sign and seal a message using ARC. /// </summary> /// <remarks> /// Asynchronously digitally signs and seals a message using ARC. /// </remarks> /// <example> /// <code language="c#" source="Examples\ArcSignerExample.cs" /> /// </example> /// <returns>An awaitable task.</returns> /// <param name="options">The formatting options.</param> /// <param name="message">The message to sign.</param> /// <param name="headers">The list of header fields to sign.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="options"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="message"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="headers"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentException"> /// <para><paramref name="headers"/> does not contain the 'From' header.</para> /// <para>-or-</para> /// <para><paramref name="headers"/> contains one or more of the following headers: Return-Path, /// Received, Comments, Keywords, Bcc, Resent-Bcc, or DKIM-Signature.</para> /// </exception> /// <exception cref="System.FormatException"> /// One or more ARC headers either did not contain an instance tag or the instance tag was invalid. /// </exception> public Task SignAsync(FormatOptions options, MimeMessage message, IList <HeaderId> headers, CancellationToken cancellationToken = default(CancellationToken)) { return(SignAsync(options, message, headers, true, cancellationToken)); }
static IList<Word> GetRfc822Words (FormatOptions options, Encoding charset, string text, bool phrase) { var encoder = charset.GetEncoder (); var words = new List<Word> (); var chars = new char[2]; var saved = new Word (); var word = new Word (); int nchars, n, i = 0; char c; while (i < text.Length) { c = text[i++]; if (c < 256 && IsBlank (c)) { if (word.ByteCount > 0) { words.Add (word); word = new Word (); } word.StartIndex = i; } else { // save state in case adding this character exceeds the max line length word.CopyTo (saved); if (c < 127) { if (IsCtrl (c)) { word.Encoding = options.AllowMixedHeaderCharsets ? Math.Max (word.Encoding, 1) : 2; word.Type = WordType.EncodedWord; word.EncodeCount++; } else if (phrase && !IsAtom (c)) { // phrases can have quoted strings if (word.Type == WordType.Atom) word.Type = WordType.QuotedString; } if (c == '"' || c == '\\') word.QuotedPairs++; word.ByteCount++; word.CharCount++; nchars = 1; } else if (c < 256) { // iso-8859-1 word.Encoding = options.AllowMixedHeaderCharsets ? Math.Max (word.Encoding, 1) : 2; word.Type = WordType.EncodedWord; word.EncodeCount++; word.ByteCount++; word.CharCount++; nchars = 1; } else { if (char.IsSurrogatePair (text, i - 1)) { chars[1] = text[i++]; nchars = 2; } else { nchars = 1; } chars[0] = c; try { n = encoder.GetByteCount (chars, 0, nchars, true); } catch { n = 3; } word.Type = WordType.EncodedWord; word.CharCount += nchars; word.EncodeCount += n; word.ByteCount += n; word.Encoding = 2; } if (ExceedsMaxLineLength (options, charset, word)) { // restore our previous state saved.CopyTo (word); i -= nchars; // Note: if the word is longer than what we can fit on // one line, then we need to encode it. if (word.Type == WordType.Atom) { word.Type = WordType.EncodedWord; // in order to fit this long atom under MaxLineLength, we need to // account for the added length of =?us-ascii?q?...?= n = "us-ascii".Length + 7; word.CharCount -= n; word.ByteCount -= n; i -= n; } words.Add (word); saved.Type = word.Type; word = new Word (); // Note: the word-type needs to be preserved when breaking long words. word.Type = saved.Type; word.StartIndex = i; } } } if (word.ByteCount > 0) words.Add (word); return words; }
/// <summary> /// Reads data from an Xml source and loads pipe fitting families, creates segments, sizes, schedules, and routing preference rules from the xml data. /// </summary> /// <param name="xDoc">The Xml data source to read from</param> public void ParseAllPipingPoliciesFromXml(XDocument xDoc) { if (m_pipeTypes.Count() == 0) { throw new RoutingPreferenceDataException("No pipe pipes defined in this project. At least one must be defined."); } FormatOptions formatOptionPipeSize = m_document.GetUnits().GetFormatOptions(UnitType.UT_PipeSize); string docPipeSizeUnit = formatOptionPipeSize.DisplayUnits.ToString(); string xmlPipeSizeUnit = xDoc.Root.Attribute("pipeSizeUnits").Value; if (docPipeSizeUnit != xmlPipeSizeUnit) { throw new RoutingPreferenceDataException("Units from XML do not match current pipe size units."); } FormatOptions formatOptionRoughness = m_document.GetUnits().GetFormatOptions(UnitType.UT_Piping_Roughness); string docRoughnessUnit = formatOptionRoughness.DisplayUnits.ToString(); string xmlRoughnessUnit = xDoc.Root.Attribute("pipeRoughnessUnits").Value; if (docRoughnessUnit != xmlRoughnessUnit) { throw new RoutingPreferenceDataException("Units from XML do not match current pipe roughness units."); } Transaction loadFamilies = new Transaction(m_document, "Load Families"); loadFamilies.Start(); IEnumerable <XElement> families = xDoc.Root.Elements("Family"); FindFolderUtility findFolderUtility = new FindFolderUtility(m_document.Application); foreach (XElement xfamily in families) { try { ParseFamilyFromXml(xfamily, findFolderUtility); //Load families. } catch (Exception ex) { loadFamilies.RollBack(); throw ex; } } loadFamilies.Commit(); Transaction addPipeTypes = new Transaction(m_document, "Add PipeTypes"); addPipeTypes.Start(); IEnumerable <XElement> pipeTypes = xDoc.Root.Elements("PipeType"); foreach (XElement xpipeType in pipeTypes) { try { ParsePipeTypeFromXml(xpipeType); //Define new pipe types. } catch (Exception ex) { addPipeTypes.RollBack(); throw ex; } } addPipeTypes.Commit(); Transaction addPipeSchedules = new Transaction(m_document, "Add Pipe Schedule Types"); addPipeSchedules.Start(); IEnumerable <XElement> pipeScheduleTypes = xDoc.Root.Elements("PipeScheduleType"); foreach (XElement xpipeScheduleType in pipeScheduleTypes) { try { ParsePipeScheduleTypeFromXml(xpipeScheduleType); //Define new pipe schedule types. } catch (Exception ex) { addPipeSchedules.RollBack(); throw ex; } } addPipeSchedules.Commit(); //The code above have added some new pipe types, schedules, or fittings, so update the lists of all of these. UpdatePipeTypesList(); UpdatePipeTypeSchedulesList(); UpdateFittingsList(); Transaction addPipeSegments = new Transaction(m_document, "Add Pipe Segments"); addPipeSchedules.Start(); IEnumerable <XElement> pipeSegments = xDoc.Root.Elements("PipeSegment"); //Define new segments. foreach (XElement xpipeSegment in pipeSegments) { try { ParsePipeSegmentFromXML(xpipeSegment); } catch (Exception ex) { addPipeSchedules.RollBack(); throw ex; } } addPipeSchedules.Commit(); UpdateSegmentsList(); //More segments may have been created, so update the segment list. //Now that all of the various types that routing preferences use have been created or loaded, add all the routing preferences. Transaction addRoutingPreferences = new Transaction(m_document, "Add Routing Preferences"); addRoutingPreferences.Start(); IEnumerable <XElement> routingPreferenceManagers = xDoc.Root.Elements("RoutingPreferenceManager"); foreach (XElement xroutingPreferenceManager in routingPreferenceManagers) { try { ParseRoutingPreferenceManagerFromXML(xroutingPreferenceManager); } catch (Exception ex) { addRoutingPreferences.RollBack(); throw ex; } } addRoutingPreferences.Commit(); }
static IList<Word> Merge (FormatOptions options, Encoding charset, IList<Word> words) { if (words.Count < 2) return words; int lwspCount, encoding, encoded, quoted, byteCount, length; var merged = new List<Word> (); Word word, next; word = words[0]; merged.Add (word); // first pass: merge qstrings with adjacent qstrings and encoded-words with adjacent encoded-words for (int i = 1; i < words.Count; i++) { next = words[i]; if (word.Type != WordType.Atom && word.Type == next.Type) { lwspCount = next.StartIndex - (word.StartIndex + word.CharCount); byteCount = word.ByteCount + lwspCount + next.ByteCount; encoding = Math.Max (word.Encoding, next.Encoding); encoded = word.EncodeCount + next.EncodeCount; quoted = word.QuotedPairs + next.QuotedPairs; if (word.Type == WordType.EncodedWord) { switch (encoding) { case 1: length = EstimateEncodedWordLength ("iso-8859-1", byteCount, encoded); break; case 0: length = EstimateEncodedWordLength ("us-ascii", byteCount, encoded); break; default: length = EstimateEncodedWordLength (charset, byteCount, encoded); break; } } else { length = byteCount + quoted + 2; } if (length + 1 < options.MaxLineLength) { word.CharCount = (next.StartIndex + next.CharCount) - word.StartIndex; word.ByteCount = byteCount; word.EncodeCount = encoded; word.QuotedPairs = quoted; word.Encoding = encoding; continue; } } merged.Add (next); word = next; } words = merged; merged = new List<Word> (); word = words[0]; merged.Add (word); // second pass: now merge atoms with the other words for (int i = 1; i < words.Count; i++) { next = words[i]; if (ShouldMergeWords (options, charset, words, word, i)) { // the resulting word is the max of the 2 types lwspCount = next.StartIndex - (word.StartIndex + word.CharCount); word.Type = (WordType) Math.Max ((int) word.Type, (int) next.Type); word.CharCount = (next.StartIndex + next.CharCount) - word.StartIndex; word.ByteCount = word.ByteCount + lwspCount + next.ByteCount; word.Encoding = Math.Max (word.Encoding, next.Encoding); word.EncodeCount = word.EncodeCount + next.EncodeCount; word.QuotedPairs = word.QuotedPairs + next.QuotedPairs; } else { merged.Add (next); word = next; } } return merged; }
protected override Task <AuthenticationResults> GenerateArcAuthenticationResultsAsync(FormatOptions options, MimeMessage message, CancellationToken cancellationToken) { return(Task.FromResult(GenerateArcAuthenticationResults(options, message, cancellationToken))); }
/// <summary> /// Encodes the phrase. /// </summary> /// <remarks> /// Encodes the phrase according to the rules of rfc2047 using /// the specified charset encoding and formatting options. /// </remarks> /// <returns>The encoded phrase.</returns> /// <param name="options">The formatting options</param> /// <param name="charset">The charset encoding.</param> /// <param name="phrase">The phrase to encode.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="options"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="charset"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="phrase"/> is <c>null</c>.</para> /// </exception> public static byte[] EncodePhrase (FormatOptions options, Encoding charset, string phrase) { if (options == null) throw new ArgumentNullException ("options"); if (charset == null) throw new ArgumentNullException ("charset"); if (phrase == null) throw new ArgumentNullException ("phrase"); return Encode (options, charset, phrase, true); }
public void Setup() { UnixFormatOptions = FormatOptions.Default.Clone(); UnixFormatOptions.NewLineFormat = NewLineFormat.Unix; }
static byte[] FoldTokens (FormatOptions options, IList<Token> tokens, string field, byte[] input) { var output = new StringBuilder (input.Length + 2); int lineLength = field.Length + 2; int lwsp = 0, tab = 0; Token token; output.Append (' '); for (int i = 0; i < tokens.Count; i++) { token = tokens[i]; if (input[token.StartIndex].IsWhitespace ()) { for (int n = token.StartIndex; n < token.StartIndex + token.Length; n++) { if (input[n] == (byte) '\r') continue; lwsp = output.Length; if (input[n] == (byte) '\t') tab = output.Length; output.Append ((char) input[n]); if (input[n] == (byte) '\n') { lwsp = tab = 0; lineLength = 0; } else { lineLength++; } } if (lineLength == 0 && i + 1 < tokens.Count) { output.Append (' '); lineLength = 1; } } else if (token.Encoding != ContentEncoding.Default) { string charset = token.CharsetCulture; if (lineLength + token.Length + charset.Length + 7 > options.MaxLineLength) { if (tab != 0) { // tabs are the perfect breaking opportunity... output.Insert (tab, options.NewLine); lineLength = (lwsp - tab) + 1; } else if (lwsp != 0) { // break just before the last lwsp character output.Insert (lwsp, options.NewLine); lineLength = 1; } else if (lineLength > 1) { // force a line break... output.Append (options.NewLine); output.Append (' '); lineLength = 1; } } // Note: if the encoded-word token is longer than the fold length, oh well... // it probably just means that we are folding a header written by a user-agent // with a different max line length than ours. output.AppendFormat ("=?{0}?{1}?", charset, token.Encoding == ContentEncoding.Base64 ? 'b' : 'q'); for (int n = token.StartIndex; n < token.StartIndex + token.Length; n++) output.Append ((char) input[n]); output.Append ("?="); lineLength += token.Length + charset.Length + 7; lwsp = 0; tab = 0; } else if (lineLength + token.Length > options.MaxLineLength) { if (tab != 0) { // tabs are the perfect breaking opportunity... output.Insert (tab, options.NewLine); lineLength = (lwsp - tab) + 1; } else if (lwsp != 0) { // break just before the last lwsp character output.Insert (lwsp, options.NewLine); lineLength = 1; } else if (lineLength > 1) { // force a line break... output.Append (options.NewLine); output.Append (' '); lineLength = 1; } if (token.Length >= options.MaxLineLength) { // the token is longer than the maximum allowable line length, // so we'll have to break it apart... for (int n = token.StartIndex; n < token.StartIndex + token.Length; n++) { if (lineLength >= options.MaxLineLength) { output.Append (options.NewLine); output.Append (' '); lineLength = 1; } output.Append ((char) input[n]); lineLength++; } } else { for (int n = token.StartIndex; n < token.StartIndex + token.Length; n++) output.Append ((char) input[n]); lineLength += token.Length; } lwsp = 0; tab = 0; } else { for (int n = token.StartIndex; n < token.StartIndex + token.Length; n++) output.Append ((char) input[n]); lineLength += token.Length; lwsp = 0; tab = 0; } } if (output[output.Length - 1] != '\n') output.Append (options.NewLine); return Encoding.ASCII.GetBytes (output.ToString ()); }
/// <summary> /// Creates or populates Revit elements based on the information contained in this class. /// </summary> /// <param name="doc">The document.</param> protected override void Create(Document doc) { if (UnitsInContext != null) { Units documentUnits = new Units(doc.DisplayUnitSystem == DisplayUnit.METRIC ? UnitSystem.Metric : UnitSystem.Imperial); foreach (IFCUnit unit in UnitsInContext) { if (!IFCUnit.IsNullOrInvalid(unit)) { try { FormatOptions formatOptions = new FormatOptions(unit.Unit); formatOptions.SetSymbolTypeId(unit.Symbol); documentUnits.SetFormatOptions(unit.Spec, formatOptions); } catch (Exception ex) { Importer.TheLog.LogError(unit.Id, ex.Message, false); } } } doc.SetUnits(documentUnits); } // We will randomize unused grid names so that they don't conflict with new entries with the same name. // This is only for relink. foreach (ElementId gridId in Importer.TheCache.GridNameToElementMap.Values) { Grid grid = doc.GetElement(gridId) as Grid; if (grid == null) { continue; } // Note that new Guid() is useless - it creates a GUID of all 0s. grid.Name = Guid.NewGuid().ToString(); } // Pre-process sites to orient them properly. IList <IFCSite> sites = new List <IFCSite>(); foreach (IFCObjectDefinition objectDefinition in ComposedObjectDefinitions) { if (objectDefinition is IFCSite) { sites.Add(objectDefinition as IFCSite); } } IFCSite.ProcessSiteLocations(doc, sites); base.Create(doc); // IfcProject usually won't create an element, as it contains no geometry. // If it doesn't, use the ProjectInfo element in the document to store its parameters. if (CreatedElementId == ElementId.InvalidElementId) { CreatedElementId = Importer.TheCache.ProjectInformationId; } }
public static void PrintAsNumber(object number, FormatOptions format) { switch (format) { case FormatOptions.Round: Console.WriteLine("{0:f2}", number); break; case FormatOptions.Percent: Console.WriteLine("{0:p0}", number); break; case FormatOptions.AlignRight: Console.WriteLine("{0,8}", number); break; default: throw new ArgumentException("Invalid format option input."); } }
private void Stream(ArrayList data, FormatOptions opt) { data.Add(new Snoop.Data.ClassSeparator(typeof(FormatOptions))); data.Add(new Snoop.Data.String("Name", opt.GetName())); data.Add(new Snoop.Data.Bool("Use default", opt.UseDefault)); if (!opt.UseDefault) { data.Add(new Snoop.Data.String("Units", opt.DisplayUnits.ToString())); data.Add(new Snoop.Data.String("Unit symbol", opt.UnitSymbol.ToString())); data.Add(new Snoop.Data.Double("Rounding", opt.Accuracy)); data.Add(new Snoop.Data.Bool("Suppress trailing zeros", opt.SuppressTrailingZeros)); data.Add(new Snoop.Data.Bool("Suppress leading zeros", opt.SuppressLeadingZeros)); data.Add(new Snoop.Data.Bool("Suppress spaces", opt.SuppressSpaces)); data.Add(new Snoop.Data.Bool("Use plus prefix", opt.UsePlusPrefix)); data.Add(new Snoop.Data.Bool("Use digit grouping", opt.UseDigitGrouping)); } }