public int Output <T>(CommandLineApplication app, T data, Action <T, TextWriter> text) where T : class { if (text == null) { OutputEncoding = "json"; } switch (OutputEncoding.ToLowerInvariant()) { case "text": text(data, app.Out); break; case "json": var x = new JsonSerializer(); x.Formatting = Formatting.Indented; x.Serialize(app.Out, data); break; default: app.Error.WriteLine($"Unknown output encoding '{OutputEncoding}'"); return(1); } return(0); }
/// <summary> /// 生成静态页(带母版) /// </summary> /// <returns></returns> public bool ToPage(dynamic model) { CompilerServiceBuilder.SetCompilerServiceFactory(new DefaultCompilerServiceFactory()); using (var service = new TemplateService()) { string master = System.IO.File.ReadAllText(MasterUrl, OutputEncoding); string content = System.IO.File.ReadAllText(TemplateUrl, OutputEncoding); service.Compile(content, model.GetType(), MasterMapper); string result = service.Parse(master, model); if (File.Exists(SaveUrl)) { File.Delete(SaveUrl); } using (FileStream stream = new FileStream(SaveUrl, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)) { Byte[] info = OutputEncoding.GetBytes(result); stream.Write(info, 0, info.Length); stream.Flush(); stream.Close(); return(true); } } return(false); }
private void GenerateResourceFileRemark(MemoryStream resourceBuffer, ResourceConfigItem item, string fileName, string dirPathInFileName) { if (item.Remark != null) { Logger.ZLogTrace("Inserting resource file remark"); var filePath = MakeStandardPath(Path.Combine(dirPathInFileName, fileName)); var remarkInfo = new Dictionary <string, string>() { ["name"] = fileName, ["path"] = filePath }; var remarkBuffer = ApplyTokens(item.Remark, remarkInfo); remarkBuffer.Replace(Emitter.CRLF, Emitter.NEW_LINE); var remarkLines = remarkBuffer.ToString().Split(new[] { Emitter.NEW_LINE }, StringSplitOptions.None); foreach (var remarkLine in remarkLines) { var b = OutputEncoding.GetBytes(remarkLine); resourceBuffer.Write(b, 0, b.Length); NewLine(resourceBuffer); } } }
private void GenerateResourceHeader(MemoryStream resourceBuffer, ResourceConfigItem resource, string basePath) { if (resource.Header == null) { Logger.ZLogTrace("Resource header is not specified."); return; } Logger.ZLogTrace("Writing header for resource config item {0}", resource.Name); var headerInfo = ResourceHeaderInfo; var headerContent = GetHeaderContent(resource, basePath); ApplyTokens(headerContent, headerInfo); if (headerContent.Length > 0) { var b = OutputEncoding.GetBytes(headerContent.ToString()); resourceBuffer.Write(b, 0, b.Length); NewLine(resourceBuffer); Logger.ZLogTrace("Wrote " + headerContent.Length + " symbols as a resource header"); } else { Logger.ZLogTrace("No header content written as it was empty"); } Logger.ZLogTrace("Done writing header for resource config item {0}", resource.Name); }
[SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")] //This is fine. StreamWriter disposes the MemoryStream, but calling twice is a NOP. public override void Save(T toSerialize) { var doc = GetConfigurationDoc(FilePath); var node = GetNodeByName(doc, typeof(T).Name); using (var stream = new MemoryStream()) using (var writer = new StreamWriter(stream)) { var serializer = new XmlSerializer(typeof(T)); serializer.Serialize(writer, toSerialize, EmptyNamespace); var settings = XElement.Parse(OutputEncoding.GetString(stream.ToArray()), LoadOptions.SetBaseUri); if (node != null) { node.ReplaceWith(settings); } else { GetNodeByName(doc, RootElement).Add(settings); } } EnsurePathExists(); using (var xml = XmlWriter.Create(FilePath, OutputXmlSettings)) { doc.WriteTo(xml); Cached = toSerialize; } }
/// <summary> /// Writes a character a number of times, optionally adding a new line at the end. /// </summary> /// <param name="charCode">The character code.</param> /// <param name="color">The color.</param> /// <param name="count">The count.</param> /// <param name="newLine">if set to <c>true</c> [new line].</param> /// <param name="writerFlags">The writer flags.</param> public static void Write(byte charCode, ConsoleColor?color = null, int count = 1, bool newLine = false, TerminalWriters writerFlags = TerminalWriters.StandardOutput) { lock (SyncLock) { var bytes = new byte[count]; for (var i = 0; i < bytes.Length; i++) { bytes[i] = charCode; } if (newLine) { var newLineBytes = OutputEncoding.GetBytes(Environment.NewLine); bytes = bytes.Union(newLineBytes).ToArray(); } var buffer = OutputEncoding.GetChars(bytes); var context = new OutputContext { OutputColor = color ?? Settings.DefaultColor, OutputText = buffer, OutputWriters = writerFlags, }; EnqueueOutput(context); } }
public TxtOutputSettings() { this.encodingField = OutputEncoding.ASCII; this.fontFamilyField = "Courier New"; this.fontSizeField = ((float)(9F)); this.lineHeightField = ((float)(1.4F)); this.useFormFeedField = true; this.trimPagesField = false; }
private void CreateLayoutCoordinates() { int temp = 0; foreach (char c in OutputEncoding.Replace(" ", string.Empty)) { LinesCoordinates.Add(new LineByPoints(new System.Drawing.Point(temp, 0), new System.Drawing.Point(temp, CanvasHeight), 0.5)); temp += Overall.HorizontalLineSize; } }
void Parse(string [] args) { string cmd_arg; foreach (string cmd in args) { if (cmd [0] != '-' && cmd [0] != '/') { AssemblyName = cmd; continue; } switch (GetCommand(cmd, out cmd_arg)) { case "text": m_output = Output.Console; break; case "output": m_output = Output.File; m_outputFile = cmd_arg; break; case "utf8": m_encoding = OutputEncoding.UTF8; break; case "unicode": m_encoding = OutputEncoding.Unicode; break; case "-about": About(); break; case "-version": Version(); break; default: if (cmd [0] == '/') { //FIXME: This is only for unix AssemblyName = cmd; } break; } } if (args.Length == 0 || m_error != null) { Usage(); } }
protected virtual byte[] RowToBytes(object[] row, out int bytesWritten) { var buf = WriteBuffer; var s = string.Format(FormatCultureInfo, FormatString, row); bytesWritten = s.Length; if (buf == null || bytesWritten > buf.Length) { buf = new byte[(int)(bytesWritten * 1.25)]; } OutputEncoding.GetBytes(s, 0, s.Length, buf, 0); return(buf); }
private static TextWriter CreateOutputWriter(Stream outputStream) { return(TextWriter.Synchronized(outputStream == Stream.Null ? StreamWriter.Null : new StreamWriter( stream: outputStream, encoding: OutputEncoding.RemovePreamble(), // This ensures no prefix is written to the stream. bufferSize: DefaultConsoleBufferSize, leaveOpen: true) { AutoFlush = true })); }
private void ButtonToEncoding_Click(object sender, EventArgs e) { if (InputTextFild.Text.Length < 3) { OutputDecoding.Clear(); OutputEncoding.Clear(); OutputDecoding.Text = "Please,enter more then 3 symbols!"; OutputEncoding.Text = "Please,enter more then 3 symbols!"; InputTextFild.Clear(); } else { string str = InputTextFild.Text; OutputEncoding.Text = Hamming.Code(str); } }
private byte[] CheckResourceOnBomAndAddToBuffer(MemoryStream buffer, ResourceConfigItem item, FileInfo file, bool oneFileResource) { byte[] content; if (oneFileResource) { Logger.ZLogTrace("Reading resource file {0} as one-file-resource", file.FullName); content = File.ReadAllBytes(file.FullName); } else { Logger.ZLogTrace("Reading resource file {0} via StreamReader with byte order mark detection option", file.FullName); using (var m = new StreamReader(file.FullName, OutputEncoding, true)) { content = OutputEncoding.GetBytes(m.ReadToEnd()); if (m.CurrentEncoding != OutputEncoding) { Logger.ZLogTrace("Converting resource file {0} from encoding {1} into default encoding {2}", file.FullName, m.CurrentEncoding.EncodingName, OutputEncoding.EncodingName); } } } if (content.Length > 0) { var checkBom = (oneFileResource && item.RemoveBom == true) || (!oneFileResource && (!item.RemoveBom.HasValue || item.RemoveBom.Value)); var bomLength = checkBom ? GetBomLength(content) : 0; if (bomLength > 0) { Logger.ZLogTrace("Found BOM symbols ({0} byte length)", bomLength); } if (bomLength < content.Length) { buffer.Write(content, bomLength, content.Length - bomLength); } else { Logger.ZLogTrace("Skipped resource as it contains only BOM"); } } return(content); }
/// <summary> /// Writes the specified text in the given color. /// </summary> /// <param name="text">The text.</param> /// <param name="color">The color.</param> /// <param name="writerFlags">The writer flags.</param> public static void Write(this string text, ConsoleColor?color = null, TerminalWriters writerFlags = TerminalWriters.StandardOutput) { if (text == null) { return; } lock (SyncLock) { var buffer = OutputEncoding.GetBytes(text); var context = new OutputContext { OutputColor = color ?? Settings.DefaultColor, OutputText = OutputEncoding.GetChars(buffer), OutputWriters = writerFlags }; EnqueueOutput(context); } }
private void RefreshChanges() { OutputEncoding = BinaryConverterLogic.GetBinaryString(InputEncoding, EncodingProp); OutputEncodingCharArray = OutputEncoding.Replace(" ", string.Empty).ToCharArray(); LinesCoordinates = SignalProp(OutputEncoding); CanvasWidth = OutputEncodingCharArray.Length * Overall.HorizontalLineSize; CanvasHeight = Overall.VerticalLineSize * 6; CreateLayoutCoordinates(); OnPropertyChanged("OutputEncoding"); OnPropertyChanged("OutputEncodingCharArray"); OnPropertyChanged("LinesCoordinates"); OnPropertyChanged("CanvasWidth"); OnPropertyChanged("CanvasHeight"); }
/// <summary> /// Prints all characters in the current code page. /// This is provided for debugging purposes only. /// </summary> public static void PrintCurrentCodePage() { if (!IsConsolePresent) { return; } lock (SyncLock) { WriteLine($"Output Encoding: {OutputEncoding}"); for (byte byteValue = 0; byteValue < byte.MaxValue; byteValue++) { var charValue = OutputEncoding.GetChars(new[] { byteValue })[0]; switch (byteValue) { case 8: // Backspace case 9: // Tab case 10: // Line feed case 13: // Carriage return charValue = '.'; break; } Write($"{byteValue:000} {charValue} "); // 7 is a beep -- Console.Beep() also works if (byteValue == 7) { Write(" "); } if ((byteValue + 1) % 8 == 0) { WriteLine(); } } WriteLine(); } }
/// <summary> /// Writes a character a number of times, optionally adding a new line at the end. /// </summary> /// <param name="charCode">The character code.</param> /// <param name="color">The color.</param> /// <param name="count">The count.</param> /// <param name="newLine">if set to <c>true</c> [new line].</param> /// <param name="writerFlags">The writer flags.</param> public static void Write(char charCode, ConsoleColor?color = null, int count = 1, bool newLine = false, TerminalWriters writerFlags = TerminalWriters.StandardOutput) { lock (SyncLock) { var text = new string(charCode, count); if (newLine) { text += Environment.NewLine; } var buffer = OutputEncoding.GetBytes(text); var context = new OutputContext { OutputColor = color ?? Settings.DefaultColor, OutputText = OutputEncoding.GetChars(buffer), OutputWriters = writerFlags, }; EnqueueOutput(context); } }
private IEnumerable <Tuple <H5ResourceInfo, byte[]> > PrepareAndExtractResources(string outputPath, string projectPath) { if (AssemblyInfo.Resources.HasEmbedResources()) { // There are resources defined in the config so let's grab files // Find all items and put in the order Logger.ZLogTrace("Preparing resources specified in config..."); foreach (var resource in AssemblyInfo.Resources.EmbedItems) { Logger.ZLogTrace("Preparing resource {0}", resource.Name); if (resource.Inject != true && resource.Extract != true) { Logger.ZLogTrace("Skipping the resource as it has inject != true and extract != true"); continue; } using (var resourceBuffer = new MemoryStream(500 * 1024)) { GenerateResourceHeader(resourceBuffer, resource, projectPath); var needSourceMap = ReadResourceFiles(projectPath, resourceBuffer, resource); if (resourceBuffer.Length > 0) { Logger.ZLogTrace("Prepared file items for resource {0}", resource.Name); var resourcePath = GetFullPathForResource(outputPath, resource); var code = resourceBuffer.ToArray(); if (needSourceMap) { TranslatorOutputItemContent content = code; var fullPath = Path.GetFullPath(Path.Combine(resourcePath.Item1, resourcePath.Item2)); content = GenerateSourceMap(fullPath, content.GetContentAsString()); code = content.GetContentAsBytes(); } ExtractResource(resourcePath.Item1, resourcePath.Item2, resource, code); var info = new H5ResourceInfo { Name = resource.Name, FileName = resource.Name, Path = string.IsNullOrWhiteSpace(resource.Output) ? null : resource.Output }; yield return(Tuple.Create(info, code)); } else { Logger.ZLogError("No files found for resource {0}", resource.Name); } } Logger.ZLogTrace("Done preparing resource {0}", resource.Name); } Logger.ZLogTrace("Done preparing resources specified in config..."); } else { // There are no resources defined in the config so let's just grab files Logger.ZLogTrace("Preparing outputs for resources"); var nonMinifiedCombinedPartsDone = false; var minifiedCombinedPartsDone = false; foreach (var outputItem in Outputs.GetOutputs(true)) { H5ResourceInfoPart[] parts = null; Logger.ZLogTrace("Getting output full path: {0}", outputItem.FullPath.ToString()); Logger.ZLogTrace("Getting output local path: {0}", outputItem.FullPath.LocalPath); var isCombined = outputItem.OutputKind.HasFlag(TranslatorOutputKind.Combined) && Outputs.Combined != null; var isMinified = outputItem.OutputKind.HasFlag(TranslatorOutputKind.Minified); if (isCombined) { Logger.ZLogTrace("The resource item is combined. Setting up its parts."); if (!isMinified) { Logger.ZLogTrace("Choosing non-minified parts."); parts = Outputs.CombinedResourcePartsNonMinified.Select(x => x.Key).ToArray(); } if (isMinified) { Logger.ZLogTrace("Choosing minified parts."); parts = Outputs.CombinedResourcePartsMinified.Select(x => x.Key).ToArray(); } } var info = new H5ResourceInfo { Name = outputItem.Name, FileName = outputItem.Name, Path = null, Parts = parts }; byte[] content; if (!outputItem.HasGeneratedSourceMap) { Logger.ZLogTrace("The output item does not have HasGeneratedSourceMap so we use it right from the Outputs"); content = outputItem.Content.GetContentAsBytes(); Logger.ZLogTrace("The output is of content " + content.Length + " length"); } else { Logger.ZLogTrace("Reading content file as the output has HasGeneratedSourceMap"); content = File.ReadAllBytes(outputItem.FullPath.LocalPath); Logger.ZLogTrace("Read " + content.Length + " bytes for " + info.Name); } yield return(Tuple.Create(info, content)); if (isCombined) { Dictionary <H5ResourceInfoPart, string> partSource = null; if (!isMinified && !nonMinifiedCombinedPartsDone) { Logger.ZLogTrace("Preparing non-minified combined resource parts"); partSource = Outputs.CombinedResourcePartsNonMinified; } if (isMinified && !minifiedCombinedPartsDone) { Logger.ZLogTrace("Preparing minified combined resource parts"); partSource = Outputs.CombinedResourcePartsMinified; } if (partSource != null) { foreach (var part in partSource) { //if (part.Key.Assembly != null) //{ // Logger.ZLogTrace("Resource part " + part.Key.ResourceName + " is not embedded into resources as it is from another assembly " + part.Key.Assembly); // continue; //} if (part.Value == null) { Logger.ZLogTrace("Resource part " + part.Key.ResourceName + " from " + part.Key.Assembly + " is not embedded into resources as it is empty"); continue; } var partResource = new H5ResourceInfo { Name = null, FileName = part.Key.ResourceName, Path = null, Parts = null }; var partContent = new byte[0]; if (!string.IsNullOrEmpty(part.Value)) { if (CheckIfRequiresSourceMap(part.Key)) { var partSourceMap = GenerateSourceMap(part.Key.Name, part.Value); partContent = OutputEncoding.GetBytes(partSourceMap); } else { partContent = OutputEncoding.GetBytes(part.Value); } } yield return(Tuple.Create(partResource, partContent)); } if (!isMinified) { nonMinifiedCombinedPartsDone = true; } if (isMinified) { minifiedCombinedPartsDone = true; } } } } Logger.ZLogTrace("Done preparing output files for resources"); } }
private void EmbedResources(List <H5ResourceInfo> resourcesToEmbed) { Logger.ZLogTrace("Embedding resources..."); var assemblyDef = AssemblyDefinition; var resources = assemblyDef.MainModule.Resources; var configHelper = new ConfigHelper(); CheckIfResourceExistsAndRemove(resources, H5ResourcesPlusSeparatedFormatList); var resourceListName = H5ResourcesJsonFormatList; CheckIfResourceExistsAndRemove(resources, resourceListName); var listArray = resourcesToEmbed.ToArray(); var listContent = Newtonsoft.Json.JsonConvert.SerializeObject(listArray, Newtonsoft.Json.Formatting.Indented); var listResources = new EmbeddedResource(resourceListName, ManifestResourceAttributes.Private, OutputEncoding.GetBytes(listContent)); resources.Add(listResources); Logger.ZLogTrace("Added resource list " + resourceListName); Logger.ZLogTrace(listContent); // Checking if mscorlib reference added and removing if added var mscorlib = assemblyDef.MainModule.AssemblyReferences.FirstOrDefault(r => r.Name == SystemAssemblyName); if (mscorlib != null) { Logger.ZLogTrace("Removing mscorlib reference"); assemblyDef.MainModule.AssemblyReferences.Remove(mscorlib); } var assemblyLocation = AssemblyLocation; Logger.ZLogTrace("Writing resources into " + assemblyLocation); using (var s = File.Open(assemblyLocation, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)) { assemblyDef.Write(s); s.Flush(); s.Close(); } Logger.ZLogTrace("Wrote resources into " + assemblyLocation); Logger.ZLogTrace("Done embedding resources"); }
private Dictionary <string, byte[]> PrepareAndExtractResources(string outputPath, string projectPath, Dictionary <string, string> files) { var resourcesToEmbed = new Dictionary <string, byte[]>(); if (this.AssemblyInfo.Resources.HasEmbedResources()) { // There are resources defined in the config so let's grab files // Find all items and put in the order this.Log.Trace("Preparing resources specified in config..."); foreach (var resource in this.AssemblyInfo.Resources.EmbedItems) { this.Log.Trace("Preparing resource " + resource.Name); if (resource.Inject != true && resource.Extract != true) { this.Log.Trace("Skipping the resource as it has inject != true and extract != true"); continue; } var resourceBuffer = new StringBuilder(); this.GenerateResourseHeader(resourceBuffer, resource, projectPath); this.ReadResourseFiles(projectPath, resourceBuffer, resource); if (resourceBuffer.Length > 0) { this.Log.Trace("Prepared files for resource " + resource.Name); var code = OutputEncoding.GetBytes(resourceBuffer.ToString()); resourcesToEmbed.Add(resource.Name, code); this.ExtractResource(outputPath, projectPath, resource, code); } else { this.Log.Error("No files found for resource " + resource.Name); } this.Log.Trace("Done preparing resource " + resource.Name); } this.Log.Trace("Done preparing resources specified in config..."); } else { // There are no resources defined in the config so let's just grab files this.Log.Trace("Preparing output files for resources"); foreach (var file in files) { try { this.Log.Trace("Reading output file " + file.Value); var content = File.ReadAllBytes(file.Value); resourcesToEmbed.Add(file.Key, content); this.Log.Trace("Read " + content.Length + " bytes"); } catch (Exception ex) { this.Log.Error(ex.ToString()); throw; } } this.Log.Trace("Done preparing output files for resources"); } return(resourcesToEmbed); }
public string CaptureOptions(bool bWithIncludedFiles) { var buf = new StringBuilder(); // Options buf.AppendFormat("linelen:{0}\n", MaxLineLength); buf.AppendFormat("no-obfuscate:{0}\n", NoObfuscate); buf.AppendFormat("detect-consts:{0}\n", DetectConsts); buf.AppendFormat("formatted:{0}\n", Formatted); buf.AppendFormat("diag-symbols:{0}\n", SymbolInfo); buf.AppendFormat("output-encoding:{0}\n", OutputEncoding == null ? "null" : OutputEncoding.ToString()); // File list buf.Append("files:\n"); foreach (var f in m_files) { buf.Append(f.filename); buf.Append(System.IO.Path.PathSeparator); buf.Append(f.encoding == null ? "null" : f.encoding.ToString()); buf.Append("\n"); } // Included file list if (bWithIncludedFiles) { buf.Append("included:\n"); foreach (var f in m_IncludedFiles) { buf.Append(f); buf.Append("\n"); } } return(buf.ToString()); }
void Parse (string [] args) { string cmd_arg; foreach (string cmd in args) { if (cmd [0] != '-' && cmd [0] != '/') { AssemblyName = cmd; continue; } switch (GetCommand (cmd, out cmd_arg)) { case "text": m_output = Output.Console; break; case "output": m_output = Output.File; m_outputFile = cmd_arg; break; case "utf8": m_encoding = OutputEncoding.UTF8; break; case "unicode": m_encoding = OutputEncoding.Unicode; break; case "-about": About (); break; case "-version": Version (); break; default: if (cmd [0] == '/') //FIXME: This is only for unix AssemblyName = cmd; break; } } if (args.Length == 0 || m_error != null) Usage (); }
public static string ToDxcArg(this OutputEncoding value) => value switch {