public void TestNestedChunks() { // Any character that appears after a '\' will always be added. This only has an effect for the '{', '}' and '\' characters, all others do not need to be escaped FormatChunk[] chunks = FormatChunk.Parse(@"This: {Tag:Is a very {complicated: {nested} format string with \{{escaped}\} tags and other \\ \'\characters\}}} and some trailing text").ToArray(); // ReSharper disable PossibleNullReferenceException Assert.AreEqual(3, chunks.Length); Assert.AreEqual("This: ", chunks[0].Value); Assert.AreEqual("Tag", chunks[1].Tag); Assert.AreEqual(" and some trailing text", chunks[2].Value); chunks = chunks[1].Children.ToArray(); Assert.AreEqual(2, chunks.Length); Assert.AreEqual("Is a very ", chunks[0].Value); Assert.AreEqual("complicated", chunks[1].Tag); chunks = chunks[1].Children.ToArray(); Assert.AreEqual(5, chunks.Length); Assert.AreEqual(" ", chunks[0].Value); Assert.AreEqual("nested", chunks[1].Tag); Assert.AreEqual(@" format string with {", chunks[2].Value); Assert.AreEqual("escaped", chunks[3].Tag); Assert.AreEqual(@"} tags and other \ 'characters}", chunks[4].Value); // ReSharper restore PossibleNullReferenceException }
/// <summary> /// Resolves the specified tag. /// </summary> /// <param name="context">The context.</param> /// <param name="chunk">The chunk.</param> /// <returns>An object that will be cached unless it is a <see cref="T:WebApplications.Utilities.Formatting.Resolution" />.</returns> // ReSharper disable once CodeAnnotationAnalyzer public override object Resolve(FormatWriteContext context, FormatChunk chunk) { if (chunk.Tag == null) { throw new ArgumentException(); } switch (chunk.Tag.ToLowerInvariant()) { case "isvalid": return(IsValid ? Resolution.Empty : Resolution.Null); case "guid": return(Guid); case "host": return(Host); case "name": return(Name); case "fullname": return(FullName); case "pipe": return(Pipe); default: return(Resolution.Unknown); } }
/// <summary> /// Resolves the email subject format builder. /// </summary> /// <param name="context">The context.</param> /// <param name="chunk">The chunk.</param> /// <param name="logs">The logs.</param> /// <returns></returns> private object ResolveSubject( [NotNull] FormatWriteContext context, [NotNull] FormatChunk chunk, [NotNull] Log[] logs) { // ReSharper disable once PossibleNullReferenceException switch (chunk.Tag.ToLowerInvariant()) { case "default": return(DefaultSubject); case FormatTagName: return(string.IsNullOrWhiteSpace(Name) ? Resolution.Null : Name); case FormatTagMore: int count = logs.Length - 1; return(count < 1 ? Resolution.Null : new FuncResolvable( (ctx, ch) => String.Equals( ch.Tag, FormatTagMoreCount, StringComparison.InvariantCultureIgnoreCase) ? count : Resolution.Unknown)); default: return(logs[0]?.Resolve(context, chunk) ?? Resolution.Unknown); } }
public static FormatChunk GetFormatChunk(Stream stream) { var id = new byte[4]; stream.Read(id, 0, id.Length); while (Encoding.ASCII.GetString(id) != "fmt ") { stream.Position -= 3; stream.Read(id, 0, id.Length); } stream.Position -= 4; var formatChunk = new FormatChunk(); var rawData = new byte[24]; stream.Read(rawData, 0, rawData.Length); formatChunk.ID = Encoding.ASCII.GetString(rawData.Take(4).ToArray()); formatChunk.Size = BitConverter.ToInt32(rawData.Skip(4).Take(4).ToArray(), 0); formatChunk.FormatTag = BitConverter.ToInt16(rawData.Skip(8).Take(2).ToArray(), 0); formatChunk.Channels = BitConverter.ToUInt16(rawData.Skip(10).Take(2).ToArray(), 0); formatChunk.SamplesPerSecond = BitConverter.ToUInt32(rawData.Skip(12).Take(4).ToArray(), 0); formatChunk.AverageBytesPerSecond = BitConverter.ToUInt32(rawData.Skip(16).Take(4).ToArray(), 0); formatChunk.BlockAlign = BitConverter.ToUInt16(rawData.Skip(20).Take(2).ToArray(), 0); formatChunk.BitsPerSecond = BitConverter.ToUInt16(rawData.Skip(22).ToArray(), 0); return(formatChunk); }
/// <summary> /// Resolves the specified tag. /// </summary> /// <param name="context">The context.</param> /// <param name="chunk">The chunk.</param> /// <returns>An object that will be cached unless it is a <see cref="T:WebApplications.Utilities.Formatting.Resolution" />.</returns> public override object Resolve(FormatWriteContext context, FormatChunk chunk) { string key; // ReSharper disable once PossibleNullReferenceException switch (chunk.Tag.ToLowerInvariant()) { case "default": case "verbose": return(EnumerableElementVerboseFormat); case "xml": return(EnumerableElementXMLFormat); case "json": return(EnumerableElementJSONFormat); case "html": return(EnumerableElementHTMLFormat); case "noline": return(EnumerableElementNoLineFormat); case "key": key = Translation.GetResource( Resource, context.FormatProvider as CultureInfo ?? Translation.DefaultCulture); return(string.IsNullOrEmpty(key) ? Resolution.Null : key); case "keyxml": key = Translation.GetResource( Resource, context.FormatProvider as CultureInfo ?? Translation.DefaultCulture); return(string.IsNullOrEmpty(key) ? Resolution.Null : key.XmlEscape()); case "keyxmltag": key = Translation.GetResource( Resource, context.FormatProvider as CultureInfo ?? Translation.DefaultCulture); return(string.IsNullOrEmpty(key) ? Resolution.Null : key.Replace(' ', '_')); case "value": return(Values); case "valuexml": return(Values.Select(v => v?.XmlEscape())); case "valuehtml": return(Values.Select(v => v != null ? _newLineRegex.Replace(v.XmlEscape(), m => "<br/>" + m.Value) : null)); default: return(Resolution.Unknown); } }
public HeaderChunk(FormatChunk formatChunk, DataChunk dataChunk) { ChunkId = "RIFF".ToCharArray(); RiffType = "WAVE".ToCharArray(); FormatChunk = formatChunk; DataChunk = dataChunk; ChunkSize = 36 + DataChunk.ChunkSize; }
public DataChunk(Chunk chunk, FormatChunk format) : base(chunk) { if (id != "data") { throw new WrongFileFormatException("Invalid file format"); } this.format = format; }
private static Dictionary <int, (WaveSampleChunk, int)> AddSamples(Config config, DLS dls) { ListChunk waves = dls.WavePool; var sampleDict = new Dictionary <int, (WaveSampleChunk, int)>((int)config.SampleTableSize); for (int i = 0; i < config.SampleTableSize; i++) { int ofs = config.Reader.ReadInt32(config.SampleTableOffset + (i * 4)); if (ofs == 0) { continue; // Skip null samples } ofs += config.SampleTableOffset; SampleHeader sh = config.Reader.ReadObject <SampleHeader>(ofs); // Create format chunk var fmt = new FormatChunk(WaveFormat.PCM); fmt.WaveInfo.Channels = 1; fmt.WaveInfo.SamplesPerSec = (uint)(sh.SampleRate >> 10); fmt.WaveInfo.AvgBytesPerSec = fmt.WaveInfo.SamplesPerSec; fmt.WaveInfo.BlockAlign = 1; fmt.FormatInfo.BitsPerSample = 8; // Create wave sample chunk and add loop if there is one var wsmp = new WaveSampleChunk { UnityNote = 60, Options = WaveSampleOptions.NoTruncation | WaveSampleOptions.NoCompression }; if (sh.DoesLoop == 0x40000000) { wsmp.Loop = new WaveSampleLoop { LoopStart = (uint)sh.LoopOffset, LoopLength = (uint)(sh.Length - sh.LoopOffset), LoopType = LoopType.Forward }; } // Get PCM sample byte[] pcm = new byte[sh.Length]; Array.Copy(config.ROM, ofs + 0x10, pcm, 0, sh.Length); // Add int dlsIndex = waves.Count; waves.Add(new ListChunk("wave") { fmt, wsmp, new DataChunk(pcm), new ListChunk("INFO") { new InfoSubChunk("INAM", $"Sample {i}") } }); sampleDict.Add(i, (wsmp, dlsIndex)); } return(sampleDict); }
public void TestInvalidAlignedFillPoint() { FormatChunk[] chunks = FormatChunk.Parse("{0,}").ToArray(); Assert.AreEqual(1, chunks.Length); FormatChunk chunk = chunks[0]; Assert.IsNotNull(chunk); Assert.AreEqual("0", chunk.Tag); Assert.IsNull(chunk.Value); }
public void BeginRecording() { waveHeader = new WaveHeader(); formatChunk = new FormatChunk(SampleRate, NumChannels); dataChunk = new DataChunk(); waveHeader.FileLength += formatChunk.Length(); IsRecording = true; onScreenDisplayHandler.EnqueueMessage("Sound recording started."); }
public override byte[] ToBytes() { List <byte> bytes = new List <byte>(); bytes.AddRange(Encoding.UTF8.GetBytes(ChunkId)); bytes.AddRange(BitConverter.GetBytes(ChunkSize)); bytes.AddRange(Encoding.UTF8.GetBytes(RiffType)); bytes.AddRange(FormatChunk.ToBytes()); bytes.AddRange(DataChunk.ToBytes()); return(bytes.ToArray <byte>()); }
public void TestAlignedFillPoint() { FormatChunk[] chunks = FormatChunk.Parse("{0,-1}").ToArray(); Assert.AreEqual(1, chunks.Length); FormatChunk chunk = chunks[0]; Assert.IsNotNull(chunk); Assert.AreEqual("{0,-1}", chunk.ToString("F", null)); Assert.IsNull(chunk.Value); Assert.IsNotNull(chunk.Tag); Assert.AreEqual("0", chunk.Tag); Assert.AreEqual(-1, chunk.Alignment); Assert.IsNull(chunk.Format); }
/// <summary> /// Resolves the specified tag. /// </summary> /// <param name="context">The context.</param> /// <param name="chunk">The chunk.</param> /// <returns>An object that will be cached unless it is a <see cref="T:WebApplications.Utilities.Formatting.Resolution" />.</returns> // ReSharper disable once CodeAnnotationAnalyzer public override object Resolve(FormatWriteContext context, FormatChunk chunk) { // ReSharper disable once PossibleNullReferenceException switch (chunk.Tag.ToLowerInvariant()) { case "name": return(Name); case "value": return(Value); default: return(Resolution.Unknown); } }
/// <summary> /// Resolves the specified tag. /// </summary> /// <param name="context">The context.</param> /// <param name="chunk">The chunk.</param> /// <returns>An object that will be cached unless it is a <see cref="T:WebApplications.Utilities.Formatting.Resolution" />.</returns> // ReSharper disable once CodeAnnotationAnalyzer public override object Resolve(FormatWriteContext context, FormatChunk chunk) { CultureInfo culture = context.FormatProvider as CultureInfo ?? Translation.DefaultCulture; string key; // ReSharper disable once PossibleNullReferenceException switch (chunk.Tag.ToLowerInvariant()) { case "default": case "verbose": return(VerboseFormat); case "xml": return(XMLFormat); case "json": return(JSONFormat); case "noline": return(NoLineFormat); case "key": key = Translation.GetResource(() => Resources.LogKeys_Context, culture); return(string.IsNullOrEmpty(key) ? Resolution.Null : key); case "keyxml": key = Translation.GetResource(() => Resources.LogKeys_Context, culture); return(string.IsNullOrEmpty(key) ? Resolution.Null : key.XmlEscape()); case "keyxmltag": key = Translation.GetResource(() => Resources.LogKeys_Context, culture); return(string.IsNullOrEmpty(key) ? Resolution.Null : key.Replace(' ', '_')); case "value": // ReSharper disable once AssignNullToNotNullAttribute return(_context.Select(kvp => new ContextElement(kvp.Key, kvp.Value)).ToArray()); default: return(Resolution.Unknown); } }
/// <summary> /// Constructor that initializes a WAV.Enumerator on a <see cref="Stream"/>. /// </summary> /// <param name="stream">The <see cref="Stream"/> to read from.</param> /// <param name="channel">The channel to read, or <see cref="AllChannels"/>.</param> /// <param name="SampleRate">The sample rate of the WAV data in Hertz units.</param> public Enumerator(Stream stream, int channel, out double SampleRate) { data = null; s = stream; this.channel = channel; // read RIFF chunk RIFFChunk riff = new RIFFChunk(stream); if (riff.riffType != "WAVE") { throw new WrongFileFormatException("Not a WAV file"); } // read format chunk Chunk chunk = new Chunk(stream); if (chunk.id != "fmt ") { throw new WrongFileFormatException("Invalid file format"); } format = new FormatChunk(chunk); if (format.format != 1) { throw new NotSupportedException("Only PCM WAV format is supported"); } SampleRate = sampleRate = format.samplesPerSecond; // skip non data chunks chunk = new Chunk(stream); while (!chunk.EndOfFile && chunk.id != "data") { chunk.Skip(); chunk = new Chunk(stream); } if (chunk.EndOfFile) { throw new WrongFileFormatException("Invalid file format"); } //inititalize data chunk data = new DataChunk(chunk, format); }
public void TestTrailingSpace() { FormatChunk[] chunks = FormatChunk.Parse("{0,-1:G} ").ToArray(); Assert.AreEqual(2, chunks.Length); FormatChunk chunk = chunks[0]; Assert.IsNotNull(chunk); Assert.AreEqual("{0,-1:G}", chunk.ToString("F", null)); Assert.IsNull(chunk.Value); Assert.IsNotNull(chunk.Tag); Assert.AreEqual("0", chunk.Tag); Assert.AreEqual(-1, chunk.Alignment); Assert.AreEqual("G", chunk.Format); chunk = chunks[1]; Assert.IsNotNull(chunk); Assert.AreEqual(" ", chunk.Value); Assert.IsNull(chunk.Tag); }
/// <summary> /// Resolves the specified tag. /// </summary> /// <param name="context">The context.</param> /// <param name="chunk">The chunk.</param> /// <returns>An object that will be cached unless it is a <see cref="T:WebApplications.Utilities.Formatting.Resolution" />.</returns> // ReSharper disable once CodeAnnotationAnalyzer public override object Resolve(FormatWriteContext context, FormatChunk chunk) { // ReSharper disable once PossibleNullReferenceException switch (chunk.Tag.ToLowerInvariant()) { case "default": case "verbose": return(ElementVerboseFormat); case "xml": return(ElementXMLFormat); case "json": return(ElementJSONFormat); case "noline": return(ElementNoLineFormat); case "key": return(Key); case "keyxml": return(Key.XmlEscape()); case "keyxmltag": return(Key.Replace(' ', '_')); case "value": return(Value); case "valuexml": return(Value.XmlEscape()); case "valuejson": return(Value == null ? "null" : Value.ToJSON()); default: return(Resolution.Unknown); } }
/// <summary> /// Resolves the body email body format builder. /// </summary> /// <param name="context">The context.</param> /// <param name="chunk">The chunk.</param> /// <param name="logs">The logs.</param> /// <param name="isHtml">if set to <see langword="true" /> the body is HTML.</param> /// <returns></returns> private object ResolveBody( [NotNull] FormatWriteContext context, [NotNull] FormatChunk chunk, [NotNull] Log[] logs, bool isHtml) { // ReSharper disable once PossibleNullReferenceException switch (chunk.Tag.ToLowerInvariant()) { case "default": return(isHtml ? DefaultBodyHtml : Log.VerboseFormat); case FormatTagName: return(string.IsNullOrWhiteSpace(Name) ? Resolution.Null : Name); case "logs": return(logs); default: return(logs[0]?.Resolve(context, chunk) ?? Resolution.Unknown); } }
public WaveFile(string fileName) { var stream = File.OpenRead(fileName); RiffHeader = RiffHeader.GetRiffHeader(stream); var pos = stream.Position; FormatChunk = FormatChunk.GetFormatChunk(stream); stream.Position = pos + FormatChunk.Size + 8; DataChunk = DataChunk.GetDataChunk(stream); //if (stream.Length < 12 + 8 + FormatChunk.Size + 8 + DataChunk.Size) throw new InvalidDataException("The Wave file format is invalid.") Data = new short[DataChunk.Size / 2]; byte[] bytes = new byte[DataChunk.Size]; stream.Read(bytes, 0, bytes.Length); stream.Dispose(); for (int i = 0; i < Data.Length; i++) { Data[i] = BitConverter.ToInt16(new byte[2] { bytes[2 * i], bytes[2 * i + 1] }, 0); } }
/// <summary> /// Resolves the specified tag. /// </summary> /// <param name="context">The context.</param> /// <param name="chunk">The chunk.</param> /// <returns> /// An object that will be cached unless it is a <see cref="T:WebApplications.Utilities.Formatting.Resolution" />. /// </returns> public override object Resolve(FormatWriteContext context, FormatChunk chunk) { Debug.Assert(chunk.Tag != null); switch (chunk.Tag.ToLowerInvariant()) { case "name": return(Name); case "altnames": return(_names.Length > 1 ? _names.Skip(1) : Resolution.Null); case "description": return(Description); case "parameters": object[] parameters = ArgumentParameters.Select(ResolveParameter).ToArray(); return(parameters.Length > 0 ? parameters : Resolution.Null); default: return(Resolution.Unknown); } }
/// <summary> /// Resolves the specified tag. /// </summary> /// <param name="context">The context.</param> /// <param name="chunk">The chunk.</param> /// <returns>An object that will be cached unless it is a <see cref="T:WebApplications.Utilities.Formatting.Resolution" />.</returns> // ReSharper disable once CodeAnnotationAnalyzer public override object Resolve(FormatWriteContext context, FormatChunk chunk) { // ReSharper disable once PossibleNullReferenceException switch (chunk.Tag.ToLowerInvariant()) { case "default": return(VerboseFormat); case "short": return(ShortFormat); case "categoryname": return(CategoryName); case "instanceguid": return(InstanceGuid); case "info": return(_infoDictionary.Values.Count > 0 ? _infoDictionary.Values : Resolution.Null); default: return(Resolution.Unknown); } }
//--Methods public WaveFile(Chunk[] chunks) { this.chks = chunks; this.dataChk = FindChunk <DataChunk>(); this.fmtChk = FindChunk <FormatChunk>(); }
/// <summary> /// Resolves the specified tag. /// </summary> /// <param name="context">The context.</param> /// <param name="chunk">The chunk.</param> /// <returns>An object that will be cached unless it is a <see cref="T:WebApplications.Utilities.Formatting.Resolution" />.</returns> // ReSharper disable once CodeAnnotationAnalyzer public override object Resolve(FormatWriteContext context, FormatChunk chunk) { // ReSharper disable once PossibleNullReferenceException switch (chunk.Tag.ToLowerInvariant()) { case "default": case "verbose": return(ElementVerboseFormat); case "xml": return(ElementXMLFormat); case "json": return(ElementJSONFormat); case "jsonfirst": return(ElementJSONFirstFormat); case "html": return(ElementHTMLFormat); case "noline": return(ElementNoLineFormat); case "key": string key = Translation.GetResource( Resource, context.FormatProvider as CultureInfo ?? Translation.DefaultCulture); return(string.IsNullOrEmpty(key) ? Resolution.Null : key); case "keyxml": string keyXml = Translation.GetResource( Resource, context.FormatProvider as CultureInfo ?? Translation.DefaultCulture); return(string.IsNullOrEmpty(keyXml) ? Resolution.Null : keyXml.XmlEscape()); case "keyxmltag": string keyXmlTag = Translation.GetResource( Resource, context.FormatProvider as CultureInfo ?? Translation.DefaultCulture); return(string.IsNullOrEmpty(keyXmlTag) ? Resolution.Null : keyXmlTag.Replace(' ', '_')); case "value": return(Value); case "valuexml": return(Value == null ? Resolution.Null : Value.XmlEscape()); case "valuehtml": return(Value == null ? Resolution.Null : _newLineRegex.Replace(Value.XmlEscape(), m => "<br/>" + m.Value)); case "valuejson": return(Value == null ? "null" : Value.ToString().ToJSON()); default: return(Resolution.Unknown); } }
/// <summary> /// Disposes the Enumerator. /// </summary> public void Dispose() { data = null; format = null; x = double.NaN; }
/// <summary> /// Resolves the specified tag. /// </summary> /// <param name="context">The context.</param> /// <param name="chunk">The chunk.</param> /// <returns>A <see cref="Resolution" />.</returns> public override object Resolve(FormatWriteContext context, FormatChunk chunk) { // ReSharper disable once PossibleNullReferenceException switch (chunk.Tag.ToLowerInvariant()) { case "verbose": return(VerboseFormat); case "reversed": return(ReversedFormat); case "key": return(Key); case "value": return(Value); case "position": return(new Resolution(context.Position, true)); case "!fill": int length = Math.Min( 120, context.Layout.Width.Value - context.Layout.FirstLineIndentSize.Value); char c = !string.IsNullOrEmpty(chunk.Format) ? chunk.Format[0] : '-'; StringBuilder fill = new StringBuilder(length + context.Position < 1 ? 2 : 4); if (context.Position > 0) { fill.AppendLine(); } fill.AppendLine(new string(c, length)); // Note we have to replace control chunk with value chunk to write it out. return(new Resolution(new FormatChunk(fill.ToString()), true)); case "nest": string k; string v; if (string.IsNullOrWhiteSpace(chunk.Format)) { k = "UnspecKey"; v = "UnspecValue"; } else { string[] split = chunk.Format.Split(new[] { ',' }, 2, StringSplitOptions.RemoveEmptyEntries); if (split.Length < 1) { k = "UnspecKey"; v = "UnspecValue"; } else if (split.Length < 2) { k = split[0]; v = "UnspecValue"; } else { k = split[0]; v = split[1]; } } return(new RWTest(k, v)); default: return(Resolution.Unknown); } }
/// <summary> /// Initializes a new instance of the <see cref="FileLogger" /> class. /// </summary> /// <param name="name">The filename.</param> /// <param name="directory">The directory to log to (default to entry assembly directory).</param> /// <param name="maxLog"><para>The maximum number of log items in a single log file.</para> /// <para>By default this is set to 1,000.</para></param> /// <param name="maxDuration">The maximum time period that a single log file can cover.</param> /// <param name="validLevels"><para>The valid log levels.</para> /// <para>By default allows <see cref="LoggingLevels">all log levels</see>.</para></param> /// <param name="format">The log format (default to "Verbose,Xml").</param> /// <param name="fileNameFormat"><para>The filename format - where {DateTime} is the creation date time.</para> /// <para>By default the format is "{ApplicationName}-{DateTime:yyMMddHHmmssffff}".</para></param> /// <param name="extension"><para>The file extension.</para> /// <para>By default this is set to use "log".</para></param> /// <param name="buffer">The buffer.</param> /// <param name="autoFlush">if set to <see langword="true" /> [auto flush].</param> /// <exception cref="LoggingException"><para> /// <paramref name="maxLog" /> was less than 10, which would result in too many log files to be created.</para> /// <para>-or-</para> /// <para> /// <paramref name="maxDuration" /> was less than 10 seconds, which would result in too many log files to be created.</para> /// <para>-or-</para> /// <para> /// <paramref name="directory" /> was either <see cref="string.IsNullOrWhiteSpace">null or whitespace</see>.</para> /// <para>-or-</para> /// <para>The <paramref name="fileNameFormat" /> string was either <see cref="string.IsNullOrWhiteSpace">null or whitespace</see>.</para> /// <para>-or-</para> /// <para>An error occurred trying to access the <paramref name="directory" />.</para> /// <para>-or-</para> /// <para> /// <paramref name="extension" /> was more than 5 characters long.</para> /// <para>-or-</para> /// <para>The <paramref name="fileNameFormat" /> led to an invalid path or created a path that references the wrong <paramref name="directory" />.</para> /// <para>-or-</para> /// <para>File path contained <see cref="Path.GetInvalidPathChars">invalid characters</see>.</para></exception> public FileLogger( [NotNull] string name, [CanBeNull] string directory = null, Int64 maxLog = 1000, TimeSpan maxDuration = default(TimeSpan), LoggingLevels validLevels = LoggingLevels.All, [CanBeNull] FormatBuilder format = null, [CanBeNull] FormatBuilder fileNameFormat = null, [CanBeNull] string extension = null, uint buffer = 65536, bool autoFlush = false) : base(name, true, validLevels) { MaxLog = maxLog; MaxDuration = maxDuration == default(TimeSpan) ? TimeSpan.FromDays(1) : maxDuration; _directory = directory ?? DefaultDirectory; _fileNameFormat = fileNameFormat ?? DefaultFileNameFormat; _extension = extension ?? string.Empty; if (format != null) { // If there is a single chunk with no format, children or alignment, // Check if it is one of the built in formats. FormatChunk[] formatChunks = format.RootChunk.Children.Take(2).ToArray(); FormatChunk chunk = formatChunks.Length == 1 ? formatChunks[0] : null; if ((chunk != null) && !chunk.IsResolved && !chunk.IsControl && (chunk.Tag != null) && (chunk.Alignment == 0) && (chunk.Format == null) && (!chunk.Children.Any())) { switch (chunk.Tag.ToLowerInvariant()) { case "all": format = Log.AllFormat; break; case "verbose": format = Log.VerboseFormat; break; case "xml": format = Log.XMLFormat; break; case "json": format = Log.JSONFormat; break; case "short": format = Log.ShortFormat; break; } } } _format = format ?? Log.VerboseFormat; _pathFormat = ValidatePathFormat(_directory, _fileNameFormat, ref _extension, _format); Buffer = buffer; AutoFlush = autoFlush; }
private static FormatBuilder ValidatePathFormat( [NotNull] string directory, [NotNull] FormatBuilder fileNameFormat, [NotNull] ref string extension, [NotNull] FormatBuilder format) { if (directory == null) { throw new ArgumentNullException("directory"); } if (fileNameFormat == null) { throw new ArgumentNullException("fileNameFormat"); } if (extension == null) { throw new ArgumentNullException("extension"); } if (format == null) { throw new ArgumentNullException("format"); } if (string.IsNullOrWhiteSpace(directory)) { directory = DefaultDirectory; } try { directory = Path.GetFullPath(directory.Trim()); if (!System.IO.Directory.Exists(directory)) { System.IO.Directory.CreateDirectory(directory); } } catch (Exception e) { // ReSharper disable once AssignNullToNotNullAttribute throw new LoggingException( e, LoggingLevel.Critical, () => Resources.FileLogger_DirectoryAccessOrCreationError, directory); } if (fileNameFormat.IsEmpty) { // ReSharper disable once AssignNullToNotNullAttribute throw new LoggingException(LoggingLevel.Critical, () => Resources.FileLogger_FileNameFormatNotSpecified); } if (string.IsNullOrWhiteSpace(extension)) { if (format == Log.XMLFormat) { extension = ".xml"; } else if (format == Log.JSONFormat) { extension = ".json"; } else { extension = ".log"; } } else { extension = extension.Trim(); if (extension.StartsWith(".")) { extension = extension.Substring(1); } if (extension.Any(c => !Char.IsLetterOrDigit(c))) { throw new LoggingException( LoggingLevel.Critical, // ReSharper disable once AssignNullToNotNullAttribute () => Resources.FileLogger_Extension_Invalid_Char, extension); } if (extension.Length > 5) { throw new LoggingException( LoggingLevel.Critical, // ReSharper disable once AssignNullToNotNullAttribute () => Resources.FileLogger_ExtensionLongerThanFiveCharacters, extension); } extension = "." + extension; } FormatBuilder pathBuilder = new FormatBuilder() .Append(directory) .Append('\\') .AppendFormat(fileNameFormat); // Add a dedupe tag if not already present // ReSharper disable once PossibleNullReferenceException Stack <FormatChunk> formatStack = new Stack <FormatChunk>(); formatStack.Push(fileNameFormat.RootChunk); bool found = false; while (formatStack.Count > 0) { FormatChunk chunk = formatStack.Pop(); // ReSharper disable once PossibleNullReferenceException if (string.Equals(chunk.Tag, FormatTagDedupe, StringComparison.CurrentCultureIgnoreCase)) { found = true; break; } foreach (var child in chunk.Children) { formatStack.Push(child); } } if (!found) { pathBuilder.AppendFormat("{dedupe: ({dedupe:D})}"); } return(pathBuilder .Append(extension) .MakeReadOnly()); }
//--Public Methods public WaveFile(IChunk[] WaveChunks) { this.waveChunks = WaveChunks; this.dataChunk = (DataChunk)GetChunk(WaveHelper.WaveChunkType.Data); this.fmtChunk = (FormatChunk)GetChunk(WaveHelper.WaveChunkType.Format); }
public void TestEmpty() { FormatChunk[] chunks = FormatChunk.Parse(string.Empty).ToArray(); Assert.AreEqual(0, chunks.Length); }