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); }
/// <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); } } }
/// <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); } }
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 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); } }
/// <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); }