/// <summary> /// Appends static properties used for event logging /// </summary> void WriteProperties(CsWriter code) { if (_options.AutoLog || !String.IsNullOrEmpty(_options.EventSource)) { code.WriteLine(); code.WriteSummaryXml("The event source used to write events"); code.WriteLine("internal static readonly string EventSourceName = @\"{0}\";", String.IsNullOrEmpty(_options.EventSource) ? _fullClassName : _options.EventSource); code.WriteLine(); code.WriteSummaryXml("The category id used to write events"); using (code.WriteBlock("public static bool TryCreateException(int hResult, string message, out System.Exception exception)")) using (code.WriteBlock("switch (unchecked((uint)hResult))")) { Dictionary<uint, bool> visited = new Dictionary<uint, bool>(); foreach (List<ResxGenItem> lst in _items.Values) foreach (ResxGenItem item in lst) { if (!item.IsException) break; if (item.HResult != 0 && !visited.ContainsKey(item.HResult)) { visited.Add(item.HResult, true); string exName = StronglyTypedResourceBuilder.VerifyResourceName(item.ItemName, Csharp); code.WriteLine("case 0x{0:x8}U: exception = {1}.{2}.Create(hResult, message); return true;", item.HResult, _nameSpace, exName); } } code.WriteLine("default: exception = null; return false;"); } } if (_options.FacilityId > 0) { code.WriteLine(); code.WriteSummaryXml("The the event log facility id of events defined in this resource file"); code.WriteLine("internal static readonly int EventFacilityId = {0};", _options.FacilityId); } if (_options.AutoLog) { if (String.IsNullOrEmpty(_options.EventSource)) Console.Error.WriteLine("Warning: AutoLog == true, but no event source name was defined."); code.WriteLine(); code.WriteSummaryXml("The the event log used to write events for this resource file"); code.WriteLine("internal static readonly string EventLogName = @\"{0}\";", String.IsNullOrEmpty(_options.EventLog) ? "Application" : _options.EventLog); code.WriteLine(); code.WriteSummaryXml("The category id used to write events for this resource file"); code.WriteLine("internal static readonly int EventCategoryId = {0};", Math.Max(0, _options.EventCategoryId)); if (String.IsNullOrEmpty(_eventLogger)) { code.WriteLine(); code.WriteSummaryXml("Writes an event log for the specified message id and arguments"); using (code.WriteBlock("internal static void WriteEvent(string eventLog, string eventSource, int category, System.Diagnostics.EventLogEntryType eventType, long eventId, object[] arguments, System.Exception error)")) using (code.WriteBlock("using (System.Diagnostics.EventLog log = new System.Diagnostics.EventLog(eventLog, \".\", eventSource))")) code.WriteLine("log.WriteEvent(new System.Diagnostics.EventInstance(eventId, category, eventType), null, arguments);"); } } }
public void WriteCtor(CsWriter code, string fullClassName, string formatPrefix) { string formatNm = String.Format("{0}.{1}{2}", fullClassName, formatPrefix, Item.Identifier); string formatFn = FormatterMethod(fullClassName, formatPrefix); string baseArgs = Item.IsFormatter ? formatFn + "({0}, {1})" : "{0}"; string argList = Item.HasArguments ? ", " + Item.Parameters(true) : ""; string strHResult = Item.HResult != 0 ? String.Format("unchecked((int)0x{0:X8}U)", Item.HResult) : "-1"; code.WriteSummaryXml(Item.Value); code.WriteLine("public {0}({1})", MemberName, Item.Parameters(true)); using (code.WriteBlock("\t: this((System.Exception)null, {0}, {1})", strHResult, String.Format(baseArgs, formatNm, Item.Parameters(false)))) { foreach (ResxGenArgument arg in Item.Args) WriteSetProperty(code, arg.IsPublic, arg.Name, arg.ParamName); if (Item.AutoLog) code.WriteLine("WriteEvent({0});", Item.Parameters(false)); } code.WriteSummaryXml(Item.Value); code.WriteLine("public {0}({1}{2}System.Exception innerException)", MemberName, Item.Parameters(true), Item.HasArguments ? ", " : ""); using (code.WriteBlock("\t: this(innerException, {0}, {1})", strHResult, String.Format(baseArgs, formatNm, Item.Parameters(false)))) { foreach (ResxGenArgument arg in Item.Args) WriteSetProperty(code, arg.IsPublic, arg.Name, arg.ParamName); if (Item.AutoLog) code.WriteLine("WriteEvent({0});", Item.Parameters(false)); } if (Item.AutoLog) WriteAutoLog(code, fullClassName, formatPrefix); code.WriteSummaryXml("if(condition == false) throws {0}", SummaryString); using (code.WriteBlock("public static void Assert(bool condition{0})", argList)) code.WriteLine("if (!condition) throw new {0}({1});", MemberName, Item.Parameters(false)); }
public void WriteFormatString(CsWriter code) { foreach (ResxExceptionString exs in _items) { exs.WriteFormatString(code); } }
private void WritePublicProperties(CsWriter code) { Dictionary <string, ResxGenArgument> publicData = new Dictionary <string, ResxGenArgument>(); foreach (ResxExceptionString item in _items) { foreach (ResxGenArgument arg in item.PublicArgs) { publicData[arg.Name] = arg; } } foreach (ResxGenArgument pd in publicData.Values) { if (pd.Name == "HResult" || pd.Name == "HelpLink" || pd.Name == "Source") { continue; //uses base properties } code.WriteLine(); code.WriteSummaryXml("The {0} parameter passed to the constructor", pd.ParamName); code.WriteLine( "public {1} {0} {{ get {{ if (Data[\"{0}\"] is {1}) return ({1})Data[\"{0}\"]; else return default({1}); }} }}", pd.Name, pd.Type); } if (publicData.Count > 0) { code.WriteLine(); } }
public void Write(TextWriter output) { string resxCode = CreateResources(); int lastBrace = resxCode.LastIndexOf('}') - 1; int nextLastBrace = resxCode.LastIndexOf('}', lastBrace) - 1; if (String.IsNullOrEmpty(_nameSpace)) { nextLastBrace = lastBrace; } output.WriteLine(resxCode.Substring(0, nextLastBrace - 1)); using (CsWriter code = new CsWriter()) { //Add formatting methods code.Indent = 2; code.WriteLine(); WriteProperties(code); WriteFormatters(code); code.Indent--; code.WriteLine(); code.WriteLine(resxCode.Substring(nextLastBrace, lastBrace - nextLastBrace)); foreach (ResxException e in _xexceptions.Values) { e.WriteException(code, _fullClassName, "ExceptionStrings.", _baseException, _sealed, _partial); } output.WriteLine(code.ToString()); } output.WriteLine(resxCode.Substring(lastBrace)); }
public virtual void WriteFormatString(CsWriter code) { code.WriteSummaryXml(SummaryString); code.WriteLine( "public static string {0} {{ get {{ return ResourceManager.GetString({1}, {2}); }} }}", Item.Identifier, code.MakeString(Item.FullName), CultureMember); }
void WriteStaticFactory(CsWriter code, string exceptionClass) { code.WriteSummaryXml("Used to recreate this exception from an hresult and message bypassing the message formatting"); using (code.WriteBlock("internal static System.Exception Create(int hResult, string message)")) code.WriteLine("return new {0}.{1}((System.Exception)null, hResult, message);", _nameSpace, exceptionClass); code.WriteSummaryXml("Constructs the exception from an hresult and message bypassing the message formatting"); using (code.WriteBlock("{0} {1}(System.Exception innerException, int hResult, string message) : base(message, innerException)", _sealed ? "private" : "protected", exceptionClass)) { code.WriteLine("base.HResult = hResult;"); if (!String.IsNullOrEmpty(_options.HelpLinkFormat)) { code.WriteLine("base.HelpLink = {0}.ExceptionStrings.HelpLinkForHR(HResult);", _fullClassName); } if (!String.IsNullOrEmpty(_options.EventSource)) { code.WriteLine("base.Source = {0}.EventSourceName;", _fullClassName); } if (_options.AutoLog && _options.EventCategoryId > 0) { WriteSetProperty(code, true, "CategoryId", _fullClassName + ".EventCategoryId"); } } }
public virtual void WriteFormatString(CsWriter code) { code.WriteSummaryXml(SummaryString); code.WriteLine( "public static string {0} {{ get {{ return ResourceManager.GetString({1}, {2}); }} }}", Item.Identifier, code.MakeString(Item.FullName), CultureMember); }
public void WriteException(CsWriter code, string fullClassName, string formatPrefix, string baseException, bool isSealed, bool isPartial) { string baseName = _baseException ?? ": " + baseException.TrimStart(':', ' '); code.WriteSummaryXml("Exception class: {0}\r\n{1}", MemberName, _items[0].SummaryString); code.WriteLine("[System.SerializableAttribute()]"); using (code.WriteClass("public {2}{3}class {0} {1}", MemberName, baseName, isSealed ? "sealed " : "", isPartial ? "partial " : "")) { code.WriteSummaryXml("Serialization constructor"); code.WriteBlock( "{1} {0}(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context)", MemberName, isSealed ? "internal" : "protected") .Dispose(); WriteDefaultCtor(code, fullClassName, formatPrefix, isSealed); WritePublicProperties(code); foreach (ResxExceptionString item in _items) { item.WriteCtor(code, fullClassName, formatPrefix); } } }
void WriteAutoLog(CsWriter code, string fullClassName, string formatPrefix) { code.WriteSummaryXml("Prepares the arguments as strings and writes the event"); using (code.WriteBlock("private void WriteEvent({0})", Item.Parameters(true))) { base.WriteEvent(code, fullClassName, formatPrefix); } }
void WriteAutoLog(CsWriter code, ResxGenItem item) { code.WriteSummaryXml("Prepares the arguments as strings and writes the event"); using (code.WriteBlock("private void WriteEvent({0})", item.Parameters(true))) { WriteEventLogCall(code, item); } }
public CSharpContext(Grammar grammar, FileRef sourceFile, string @namespace, DirRef output, CsWriter writer = null) { Grammar = grammar; SourceFile = sourceFile; Namespace = @namespace; Output = output; Writer = writer; }
static void WriteSetProperty(CsWriter code, bool isPublic, string argName, string argValue) { if (isPublic) { if (argName == "HResult" || argName == "HelpLink" || argName == "Source") code.WriteLine("base.{0} = {1};", argName, argValue); else code.WriteLine("base.Data[\"{0}\"] = {1};", argName, argValue); } }
void WriteDefaultCtor(CsWriter code, string fullClassName, string formatPrefix, bool isSealed) { code.WriteSummaryXml("Used to create this exception from an hresult and message bypassing the message formatting"); using (code.WriteBlock("internal static System.Exception Create(int hResult, string message)")) code.WriteLine("return new {0}((System.Exception)null, hResult, message);", MemberName); code.WriteSummaryXml("Constructs the exception from an hresult and message bypassing the message formatting"); using (code.WriteBlock("{0} {1}(System.Exception innerException, int hResult, string message) : base(message, innerException)", isSealed ? "private" : "protected", MemberName)) { code.WriteLine("base.HResult = hResult;"); code.WriteLine("base.HelpLink = {0}.{1}HelpLinkFormat(HResult, GetType().FullName);", fullClassName, formatPrefix); } }
static void WriteSetProperty(CsWriter code, bool isPublic, string argName, string argValue) { if (isPublic) { if (argName == "HResult" || argName == "HelpLink" || argName == "Source") { code.WriteLine("base.{0} = {1};", argName, argValue); } else { code.WriteLine("base.Data[\"{0}\"] = {1};", argName, argValue); } } }
public virtual void WriteAccessor(CsWriter code, string fullClassName, string formatPrefix) { code.WriteSummaryXml(SummaryString); using (code.WriteBlock("public static string {0}({1})", Item.MemberName, Item.Parameters(true))) { if(Item.AutoLog) WriteEvent(code, fullClassName, formatPrefix); string args = Item.Parameters(false); if( args.Length > 0 ) args = ", " + args; code.WriteLine("return {0}({1}, {2}.{3}{4}{5});", FormatterMethod(fullClassName, formatPrefix), CultureMember, fullClassName, formatPrefix, Item.Identifier, args); } }
void WriteFormatters(CsWriter code) { if (_xstrings.Count > 0) { foreach (ResxString s in _xstrings) { s.WriteAccessor(code, _fullClassName, "FormatStrings."); } code.WriteLine(); code.WriteSummaryXml("Returns the raw format strings."); using (code.WriteClass("public static {0}class FormatStrings", _partial ? "partial " : "")) { foreach (ResxString s in _xstrings) { s.WriteFormatString(code); } } } if (_xexceptions.Count > 0) { code.WriteLine(); code.WriteSummaryXml("Returns the raw exception strings."); using (code.WriteClass("public static {0}class ExceptionStrings", _partial ? "partial " : "")) { code.WriteSummaryXml("Formats a message for an exception"); using (code.WriteBlock("internal static string SafeFormat(string message, params object[] args)")) { using (code.WriteBlock("try")) code.WriteLine("return string.Format(resourceCulture, message, args);"); using (code.WriteBlock("catch")) code.WriteLine("return message ?? string.Empty;"); } string helpLinkFormat = _options.HelpLinkFormat ?? String.Empty; String.Format(helpLinkFormat, 5, String.Empty);//just to make sure it's a valid format code.WriteSummaryXml("{0}", _options.HelpLinkFormat); using (code.WriteBlock("internal static string HelpLinkFormat(int hResult, string typeName)")) code.WriteLine("return SafeFormat({0}, hResult, typeName);", code.MakeString(helpLinkFormat)); foreach (ResxException ex in _xexceptions.Values) { ex.WriteFormatString(code); } } } }
void WriteEventLogCall(CsWriter code, ResxGenItem item) { Dictionary <int, string> formatting = new Dictionary <int, string>(); for (int i = 0; i < item.Args.Count; i++) { formatting[i] = "{0}"; } foreach (Match m in RegexPatterns.FormatSpecifier.Matches(item.Value)) { Group field = m.Groups["field"]; int ix; if (int.TryParse(field.Value, out ix)) { formatting[ix] = String.Format("{0}0{1}", m.Value.Substring(0, field.Index - m.Index), m.Value.Substring(field.Index + field.Length - m.Index)); } } code.WriteLine("string[] ctorEventArguments = new string[] {"); for (int i = 0; i < item.Args.Count; i++) { code.WriteLine("{0}.ExceptionStrings.SafeFormat(@\"{1}\", {2}),", _fullClassName, formatting[i], item.Args[i].ParamName); } code.WriteLine("};"); using (code.WriteBlock("try")) { EventLogEntryType etype = item.MessageId < 0x80000000 ? EventLogEntryType.Information : ((item.MessageId & 0xC0000000) == 0xC0000000) ? EventLogEntryType.Error : EventLogEntryType.Warning; string logMethod = String.IsNullOrEmpty(_eventLogger) ? String.Format("{0}.WriteEvent", _fullClassName) : _eventLogger; code.WriteLine("{0}(", logMethod); code.Indent++; code.WriteLine("{0}.EventLogName,", _fullClassName); code.WriteLine("{0}.EventSourceName,", _fullClassName); code.WriteLine("{0}.EventCategoryId,", _fullClassName); code.WriteLine("System.Diagnostics.EventLogEntryType.{0},", etype); code.WriteLine("0x0{0:X8}L, ctorEventArguments, {1});", item.MessageId, item.IsException ? "this" : "null"); code.Indent--; } code.WriteLine("catch { }"); }
public void TestBasicWriter() { using (CsWriter w = new CsWriter()) { w.AddNamespaces("System"); using(w.WriteNamespace("CSharpTest")) using (w.WriteClass("class Net")) { } string msg = w.ToString(); Assert.IsTrue(msg.Contains("using System;")); Assert.IsTrue(msg.Contains("DebuggerNonUserCodeAttribute")); Assert.IsTrue(msg.Contains("CompilerGenerated")); Assert.IsTrue(msg.Contains("class Net")); } }
public void TestBasicWriter() { using (CsWriter w = new CsWriter()) { w.AddNamespaces("System"); using (w.WriteNamespace("CSharpTest")) using (w.WriteClass("class Net")) { } string msg = w.ToString(); Assert.IsTrue(msg.Contains("using System;")); Assert.IsTrue(msg.Contains("DebuggerNonUserCodeAttribute")); Assert.IsTrue(msg.Contains("CompilerGenerated")); Assert.IsTrue(msg.Contains("class Net")); } }
public void WriteCtor(CsWriter code, string fullClassName, string formatPrefix) { string formatNm = String.Format("{0}.{1}{2}", fullClassName, formatPrefix, Item.Identifier); string formatFn = FormatterMethod(fullClassName, formatPrefix); string baseArgs = Item.IsFormatter ? formatFn + "({0}, {1})" : "{0}"; string argList = Item.HasArguments ? ", " + Item.Parameters(true) : ""; string strHResult = Item.HResult != 0 ? String.Format("unchecked((int)0x{0:X8}U)", Item.HResult) : "-1"; code.WriteSummaryXml(Item.Value); code.WriteLine("public {0}({1})", MemberName, Item.Parameters(true)); using (code.WriteBlock("\t: this((System.Exception)null, {0}, {1})", strHResult, String.Format(baseArgs, formatNm, Item.Parameters(false)))) { foreach (ResxGenArgument arg in Item.Args) { WriteSetProperty(code, arg.IsPublic, arg.Name, arg.ParamName); } if (Item.AutoLog) { code.WriteLine("WriteEvent({0});", Item.Parameters(false)); } } code.WriteSummaryXml(Item.Value); code.WriteLine("public {0}({1}{2}System.Exception innerException)", MemberName, Item.Parameters(true), Item.HasArguments ? ", " : ""); using (code.WriteBlock("\t: this(innerException, {0}, {1})", strHResult, String.Format(baseArgs, formatNm, Item.Parameters(false)))) { foreach (ResxGenArgument arg in Item.Args) { WriteSetProperty(code, arg.IsPublic, arg.Name, arg.ParamName); } if (Item.AutoLog) { code.WriteLine("WriteEvent({0});", Item.Parameters(false)); } } if (Item.AutoLog) { WriteAutoLog(code, fullClassName, formatPrefix); } code.WriteSummaryXml("if(condition == false) throws {0}", SummaryString); using (code.WriteBlock("public static void Assert(bool condition{0})", argList)) code.WriteLine("if (!condition) throw new {0}({1});", MemberName, Item.Parameters(false)); }
public virtual void WriteEvent(CsWriter code, string fullClassName, string formatPrefix) { Dictionary <int, string> formatting = new Dictionary <int, string>(); for (int i = 0; i < Item.Args.Count; i++) { formatting[i] = "{0}"; } foreach (Match m in RegexPatterns.FormatSpecifier.Matches(Item.Value)) { Group field = m.Groups["field"]; int ix; if (int.TryParse(field.Value, out ix)) { formatting[ix] = String.Format("{0}0{1}", m.Value.Substring(0, field.Index - m.Index), m.Value.Substring(field.Index + field.Length - m.Index)); } } code.WriteLine("string[] ctorEventArguments = new string[] {"); for (int i = 0; i < Item.Args.Count; i++) { code.WriteLine("{0}(@\"{1}\", {2}),", FormatterMethod(fullClassName, formatPrefix), formatting[i], Item.Args[i].ParamName); } code.WriteLine("};"); EventLogEntryType etype = Item.MessageId < 0x80000000 ? EventLogEntryType.Information : ((Item.MessageId & 0xC0000000) == 0xC0000000) ? EventLogEntryType.Error : EventLogEntryType.Warning; string logMethod = String.Format("{0}.WriteEvent", fullClassName); code.WriteLine("{0}(", logMethod); code.Indent++; code.WriteLine("{0}.EventLogName,", fullClassName); code.WriteLine("{0}.EventSourceName,", fullClassName); code.WriteLine("{0}.EventCategoryId,", fullClassName); code.WriteLine("System.Diagnostics.EventLogEntryType.{0},", etype); code.WriteLine("0x0{0:X8}L, ctorEventArguments, {1});", Item.MessageId, Item.IsException ? "this" : "null"); code.Indent--; }
public virtual void WriteAccessor(CsWriter code, string fullClassName, string formatPrefix) { code.WriteSummaryXml(SummaryString); using (code.WriteBlock("public static string {0}({1})", Item.MemberName, Item.Parameters(true))) { if (Item.AutoLog) { WriteEvent(code, fullClassName, formatPrefix); } string args = Item.Parameters(false); if (args.Length > 0) { args = ", " + args; } code.WriteLine("return {0}({1}, {2}.{3}{4}{5});", FormatterMethod(fullClassName, formatPrefix), CultureMember, fullClassName, formatPrefix, Item.Identifier, args); } }
private void WritePublicProperties(CsWriter code) { Dictionary<string, ResxGenArgument> publicData = new Dictionary<string, ResxGenArgument>(); foreach (ResxExceptionString item in _items) foreach (ResxGenArgument arg in item.PublicArgs) publicData[arg.Name] = arg; foreach (ResxGenArgument pd in publicData.Values) { if (pd.Name == "HResult" || pd.Name == "HelpLink" || pd.Name == "Source") continue; //uses base properties code.WriteLine(); code.WriteSummaryXml("The {0} parameter passed to the constructor", pd.ParamName); code.WriteLine( "public {1} {0} {{ get {{ if (Data[\"{0}\"] is {1}) return ({1})Data[\"{0}\"]; else return default({1}); }} }}", pd.Name, pd.Type); } if(publicData.Count > 0) code.WriteLine(); }
public virtual void WriteEvent(CsWriter code, string fullClassName, string formatPrefix) { Dictionary<int, string> formatting = new Dictionary<int, string>(); for (int i = 0; i < Item.Args.Count; i++) formatting[i] = "{0}"; foreach (Match m in RegexPatterns.FormatSpecifier.Matches(Item.Value)) { Group field = m.Groups["field"]; int ix; if (int.TryParse(field.Value, out ix)) { formatting[ix] = String.Format("{0}0{1}", m.Value.Substring(0, field.Index - m.Index), m.Value.Substring(field.Index + field.Length - m.Index)); } } code.WriteLine("string[] ctorEventArguments = new string[] {"); for (int i = 0; i < Item.Args.Count; i++) code.WriteLine("{0}(@\"{1}\", {2}),", FormatterMethod(fullClassName, formatPrefix), formatting[i], Item.Args[i].ParamName); code.WriteLine("};"); EventLogEntryType etype = Item.MessageId < 0x80000000 ? EventLogEntryType.Information : ((Item.MessageId & 0xC0000000) == 0xC0000000) ? EventLogEntryType.Error : EventLogEntryType.Warning; string logMethod = String.Format("{0}.WriteEvent", fullClassName); code.WriteLine("{0}(", logMethod); code.Indent++; code.WriteLine("{0}.EventLogName,", fullClassName); code.WriteLine("{0}.EventSourceName,", fullClassName); code.WriteLine("{0}.EventCategoryId,", fullClassName); code.WriteLine("System.Diagnostics.EventLogEntryType.{0},", etype); code.WriteLine("0x0{0:X8}L, ctorEventArguments, {1});", Item.MessageId, Item.IsException ? "this" : "null"); code.Indent--; }
public void WriteException(CsWriter code, string fullClassName, string formatPrefix, string baseException, bool isSealed, bool isPartial) { string baseName = _baseException ?? ": " + baseException.TrimStart(':', ' '); code.WriteSummaryXml("Exception class: {0}\r\n{1}", MemberName, _items[0].SummaryString); code.WriteLine("[System.SerializableAttribute()]"); using (code.WriteClass("public {2}{3}class {0} {1}", MemberName, baseName, isSealed ? "sealed " : "", isPartial ? "partial " : "")) { code.WriteSummaryXml("Serialization constructor"); code.WriteBlock( "{1} {0}(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context)", MemberName, isSealed ? "internal" : "protected") .Dispose(); WriteDefaultCtor(code, fullClassName, formatPrefix, isSealed); WritePublicProperties(code); foreach (ResxExceptionString item in _items) item.WriteCtor(code, fullClassName, formatPrefix); } }
public CSharpWriterProductions(CSharpContext ctx) : base(ctx) { this.writer = ctx.Writer; }
public void TweakVisitor() { var inlines = File.ReadAllLines(inputFile); var outlines = new CsWriter(); outlines.WriteLine($"using System;"); outlines.WriteLine($"using System.Collections.Generic;"); outlines.WriteLine($"using System.Linq;"); outlines.WriteLine($"using Hime.Redist;"); outlines.WriteLine(); outlines.Block($"namespace {Namespace(inlines)}", () => { outlines.Block($"public abstract class {VisitorName()}", () => { outlines.Block($"protected virtual void VisitNode(ASTNode node)", () => { outlines.WriteLine($"VisitNode<bool>(node);"); }); outlines.Block($"protected virtual T VisitNode<T>(ASTNode node)", () => { Switch(inlines, outlines); }); outlines.Block($"protected virtual IEnumerable<object> VisitChildren(ASTNode node)", () => { outlines.Block($"foreach (var child in node.Children)", () => { outlines.WriteLine($"yield return VisitNode<object>(child);"); }); }); outlines.Block($"protected virtual IEnumerable<T> VisitChildren<T>(ASTNode node)", () => { outlines.Block($"foreach (var child in node.Children)", () => { outlines.WriteLine($"yield return VisitNode<T>(child);"); }); }); Virtuals(inlines, outlines); outlines.Block($"partial class OnTerminal", () => { outlines.Block($"protected OnTerminal({VisitorName()} visitor)", () => { }); }); outlines.WriteLine(); outlines.Block($"partial class OnVariable", () => { }); outlines.WriteLine(); outlines.Block($"partial class OnVirtual", () => { }); }); }); outlines.Persist(outputFile); }
public CSharpWriterParseTable(CSharpContext ctx) : base(ctx) { this.writer = ctx.Writer; }
void WriteException(CsWriter code, List <ResxGenItem> lst) { if (lst.Count == 0 || lst[0].IsException == false) { return; } ResxGenItem first = lst[0]; string exName = StronglyTypedResourceBuilder.VerifyResourceName(first.ItemName, Csharp); string baseName = ": " + _baseException; foreach (ResxGenItem item in lst) { if (item.Comments.StartsWith(":")) { baseName = item.Comments; } } code.WriteSummaryXml("Exception class: {0} {1}\r\n{2}", exName, baseName, first.Value); code.WriteLine("[System.SerializableAttribute()]"); using ( code.WriteClass("public {2}{3}class {0} {1}", exName, baseName, _sealed ? "sealed " : "", _partial ? "partial " : "")) { code.WriteSummaryXml("Serialization constructor"); code.WriteBlock( "{1} {0}(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context)", exName, _sealed ? "internal" : "protected") .Dispose(); WriteStaticFactory(code, exName); Dictionary <string, ResxGenArgument> publicData = new Dictionary <string, ResxGenArgument>(); foreach (ResxGenItem item in lst) { foreach (ResxGenArgument arg in item.Args) { if (arg.IsPublic) { publicData[arg.Name] = arg; } } } foreach (ResxGenArgument pd in publicData.Values) { if (pd.Name == "HResult" || pd.Name == "HelpLink" || pd.Name == "Source") { continue; //uses base properties } code.WriteLine(); code.WriteSummaryXml("The {0} parameter passed to the constructor", pd.ParamName); code.WriteLine( "public {1} {0} {{ get {{ if (Data[\"{0}\"] is {1}) return ({1})Data[\"{0}\"]; else return default({1}); }} }}", pd.Name, pd.Type); } code.WriteLine(); foreach (ResxGenItem item in lst) { string formatNm = String.Format("{0}.ExceptionStrings.{1}", _fullClassName, item.Identifier); string formatFn = _fullClassName + ".ExceptionStrings.SafeFormat"; string baseArgs = item.IsFormatter ? formatFn + "({0}, {1})" : "{0}"; string argList = item.HasArguments ? ", " + item.Parameters(true) : ""; string strHResult = item.HResult != 0 ? String.Format("unchecked((int)0x{0:X8}U)", item.HResult) : "-1"; code.WriteSummaryXml(item.Value); code.WriteLine("public {0}({1})", exName, item.Parameters(true)); using (code.WriteBlock("\t: this((System.Exception)null, {0}, {1})", strHResult, String.Format(baseArgs, formatNm, item.Parameters(false)))) { foreach (ResxGenArgument arg in item.Args) { WriteSetProperty(code, arg.IsPublic, arg.Name, arg.ParamName); } if (item.AutoLog) { code.WriteLine("WriteEvent({0});", item.Parameters(false)); } } code.WriteSummaryXml(item.Value); code.WriteLine("public {0}({1}{2}System.Exception innerException)", exName, item.Parameters(true), item.HasArguments ? ", " : ""); using (code.WriteBlock("\t: this(innerException, {0}, {1})", strHResult, String.Format(baseArgs, formatNm, item.Parameters(false)))) { foreach (ResxGenArgument arg in item.Args) { WriteSetProperty(code, arg.IsPublic, arg.Name, arg.ParamName); } if (item.AutoLog) { code.WriteLine("WriteEvent({0});", item.Parameters(false)); } } if (item.AutoLog) { WriteAutoLog(code, item); } code.WriteSummaryXml("if(condition == false) throws {0}", item.Value); using (code.WriteBlock("public static void Assert(bool condition{0})", argList)) code.WriteLine("if (!condition) throw new {0}({1});", exName, item.Parameters(false)); } } }
/// <summary> /// Appends static properties used for event logging /// </summary> void WriteProperties(CsWriter code) { if (_options.AutoLog || !String.IsNullOrEmpty(_options.EventSource)) { code.WriteLine(); code.WriteSummaryXml("The event source used to write events"); code.WriteLine("internal static readonly string EventSourceName = @\"{0}\";", String.IsNullOrEmpty(_options.EventSource) ? _fullClassName : _options.EventSource); code.WriteLine(); code.WriteSummaryXml("The category id used to write events"); using (code.WriteBlock("public static bool TryCreateException(int hResult, string message, out System.Exception exception)")) using (code.WriteBlock("switch (unchecked((uint)hResult))")) { Dictionary <uint, bool> visited = new Dictionary <uint, bool>(); foreach (List <ResxGenItem> lst in _items.Values) { foreach (ResxGenItem item in lst) { if (!item.IsException) { break; } if (item.HResult != 0 && !visited.ContainsKey(item.HResult)) { visited.Add(item.HResult, true); string exName = StronglyTypedResourceBuilder.VerifyResourceName(item.ItemName, Csharp); code.WriteLine("case 0x{0:x8}U: exception = {1}.{2}.Create(hResult, message); return true;", item.HResult, _nameSpace, exName); } } } code.WriteLine("default: exception = null; return false;"); } } if (_options.FacilityId > 0) { code.WriteLine(); code.WriteSummaryXml("The the event log facility id of events defined in this resource file"); code.WriteLine("internal static readonly int EventFacilityId = {0};", _options.FacilityId); } if (_options.AutoLog) { if (String.IsNullOrEmpty(_options.EventSource)) { Console.Error.WriteLine("Warning: AutoLog == true, but no event source name was defined."); } code.WriteLine(); code.WriteSummaryXml("The the event log used to write events for this resource file"); code.WriteLine("internal static readonly string EventLogName = @\"{0}\";", String.IsNullOrEmpty(_options.EventLog) ? "Application" : _options.EventLog); code.WriteLine(); code.WriteSummaryXml("The category id used to write events for this resource file"); code.WriteLine("internal static readonly int EventCategoryId = {0};", Math.Max(0, _options.EventCategoryId)); if (String.IsNullOrEmpty(_eventLogger)) { code.WriteLine(); code.WriteSummaryXml("Writes an event log for the specified message id and arguments"); using (code.WriteBlock("internal static void WriteEvent(string eventLog, string eventSource, int category, System.Diagnostics.EventLogEntryType eventType, long eventId, object[] arguments, System.Exception error)")) using (code.WriteBlock("using (System.Diagnostics.EventLog log = new System.Diagnostics.EventLog(eventLog, \".\", eventSource))")) code.WriteLine("log.WriteEvent(new System.Diagnostics.EventInstance(eventId, category, eventType), null, arguments);"); } } }
public CSharpWriterDfaSet(CSharpContext ctx) : base(ctx) { this.writer = ctx.Writer; }
public string CreateConstants(string header) { string content = File.ReadAllText(header); Regex pattern = new Regex(@"^#define\s+(?<id>[\w_]*)\s+\(?(?:\(long\))?(?<value>.*?)\)?\s*?$", RegexOptions.Multiline | RegexOptions.IgnoreCase); Dictionary <string, string> defines = new Dictionary <string, string>(); foreach (Match m in pattern.Matches(content)) { if (!m.Groups["id"].Value.StartsWith("CATEGORY_", StringComparison.Ordinal) && !m.Groups["id"].Value.StartsWith("FACILITY_", StringComparison.Ordinal)) { defines.Add(m.Groups["id"].Value, m.Groups["value"].Value); } } using (CsWriter code = new CsWriter()) { code.WriteLine("// ReSharper disable InconsistentNaming"); code.WriteLine("#pragma warning disable 1591 //disable missing xml comments"); code.WriteLine(); using (code.WriteNamespace(Namespace)) { if (_genInfo != null) { Dictionary <int, string> items = _genInfo.Facilities; using (code.WriteBlock("public enum Facilities")) { List <int> sorted = new List <int>(items.Keys); sorted.Sort(); foreach (int key in sorted) { code.WriteLine("{0} = {1},", StronglyTypedResourceBuilder.VerifyResourceName(items[key], Csharp), key); } } code.WriteLine(); items = _genInfo.Categories; using (code.WriteBlock("public enum Categories")) { List <int> sorted = new List <int>(items.Keys); sorted.Sort(); foreach (int key in sorted) { code.WriteLine("{0} = {1},", StronglyTypedResourceBuilder.VerifyResourceName(items[key], Csharp), key); } } code.WriteLine(); } using (code.WriteBlock("public enum HResults : long")) { List <string> sorted = new List <string>(defines.Keys); sorted.Sort(); foreach (string key in sorted) { code.WriteLine("{0} = {1},", StronglyTypedResourceBuilder.VerifyResourceName(key, Csharp), defines[key]); } } } return(code.ToString()); } }
void WriteAutoLog(CsWriter code, ResxGenItem item) { code.WriteSummaryXml("Prepares the arguments as strings and writes the event"); using (code.WriteBlock("private void WriteEvent({0})", item.Parameters(true))) { WriteEventLogCall(code, item); } }
void WriteEventLogCall(CsWriter code, ResxGenItem item) { Dictionary<int, string> formatting = new Dictionary<int, string>(); for (int i = 0; i < item.Args.Count; i++) formatting[i] = "{0}"; foreach (Match m in RegexPatterns.FormatSpecifier.Matches(item.Value)) { Group field = m.Groups["field"]; int ix; if (int.TryParse(field.Value, out ix)) { formatting[ix] = String.Format("{0}0{1}", m.Value.Substring(0, field.Index - m.Index), m.Value.Substring(field.Index + field.Length - m.Index)); } } code.WriteLine("string[] ctorEventArguments = new string[] {"); for (int i = 0; i < item.Args.Count; i++) code.WriteLine("{0}.ExceptionStrings.SafeFormat(@\"{1}\", {2}),", _fullClassName, formatting[i], item.Args[i].ParamName); code.WriteLine("};"); using (code.WriteBlock("try")) { EventLogEntryType etype = item.MessageId < 0x80000000 ? EventLogEntryType.Information : ((item.MessageId & 0xC0000000) == 0xC0000000) ? EventLogEntryType.Error : EventLogEntryType.Warning; string logMethod = String.IsNullOrEmpty(_eventLogger) ? String.Format("{0}.WriteEvent", _fullClassName) : _eventLogger; code.WriteLine("{0}(", logMethod); code.Indent++; code.WriteLine("{0}.EventLogName,", _fullClassName); code.WriteLine("{0}.EventSourceName,", _fullClassName); code.WriteLine("{0}.EventCategoryId,", _fullClassName); code.WriteLine("System.Diagnostics.EventLogEntryType.{0},", etype); code.WriteLine("0x0{0:X8}L, ctorEventArguments, {1});", item.MessageId, item.IsException ? "this" : "null"); code.Indent--; } code.WriteLine("catch { }"); }
public string CreateInstaller() { if (_genInfo == null) return String.Empty; Dictionary<string, string> sources = _genInfo.EventSources; Dictionary<string, bool> logNames = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase); foreach (string val in sources.Values) logNames[val] = val != "Application" && val != "Security" && val != "Setup" && val != "System"; int maxCategory = _genInfo.Categories.Count; using (CsWriter code = new CsWriter()) { using (code.WriteNamespace(Namespace)) { code.WriteSummaryXml("Installer class for the Event Log messages"); code.WriteLine("[global::System.ComponentModel.RunInstaller(true)]"); using (code.WriteClass("public class Installer : System.Configuration.Install.Installer")) { foreach (KeyValuePair<string, string> kv in sources) code.WriteLine("readonly System.Diagnostics.EventLogInstaller _install{0}{1};", kv.Value, kv.Key); code.WriteLine(); code.WriteSummaryXml("Constructs the installer for the Event Log"); using (code.WriteBlock("public Installer()")) { foreach (KeyValuePair<string, string> kv in sources) { string name = String.Format("_install{0}{1}", kv.Value, kv.Key); code.WriteLine("{0} = new System.Diagnostics.EventLogInstaller();", name); code.WriteLine("{0}.Log = @\"{1}\";", name, kv.Value.Replace("\"", "\"\"")); code.WriteLine("{0}.Source = @\"{1}\";", name, kv.Key.Replace("\"", "\"\"")); code.WriteLine("{0}.CategoryCount = {1};", name, maxCategory); code.WriteLine( "{0}.UninstallAction = System.Configuration.Install.UninstallAction.Remove;", name); code.WriteLine("Installers.Add({0});", name); code.WriteLine(); } } code.WriteLine(); code.WriteSummaryXml("Customizes the MessageResourceFile durring installation"); using (code.WriteBlock("public override void Install(System.Collections.IDictionary state)")) { foreach (KeyValuePair<string, string> kv in sources) code.WriteLine( "_install{0}{1}.CategoryResourceFile = _install{0}{1}.MessageResourceFile =", kv.Value, kv.Key); code.WriteLine( " System.IO.Path.GetFullPath(Context.Parameters[\"assemblypath\"].Trim('\"'));"); code.WriteLine(); code.WriteLine("base.Install(state);"); foreach (KeyValuePair<string, bool> kv in logNames) { if (!kv.Value) continue;//do not configure default logs code.WriteLine(); using (code.WriteBlock("using (System.Diagnostics.EventLog log = new System.Diagnostics.EventLog(@\"{0}\", \".\"))", kv.Key.Replace("\"", "\"\""))) { code.WriteLine("log.MaximumKilobytes = 1024 * 10;"); code.WriteLine("log.ModifyOverflowPolicy(System.Diagnostics.OverflowAction.OverwriteAsNeeded, 30);"); } } } } } return code.ToString(); } }
public void WriteFormatString(CsWriter code) { foreach (ResxExceptionString exs in _items) exs.WriteFormatString(code); }
void WriteDefaultCtor(CsWriter code, string fullClassName, string formatPrefix, bool isSealed) { code.WriteSummaryXml("Used to create this exception from an hresult and message bypassing the message formatting"); using (code.WriteBlock("internal static System.Exception Create(int hResult, string message)")) code.WriteLine("return new {0}((System.Exception)null, hResult, message);", MemberName); code.WriteSummaryXml("Constructs the exception from an hresult and message bypassing the message formatting"); using (code.WriteBlock("{0} {1}(System.Exception innerException, int hResult, string message) : base(message, innerException)", isSealed ? "private" : "protected", MemberName)) { code.WriteLine("base.HResult = hResult;"); code.WriteLine("base.HelpLink = {0}.{1}HelpLinkFormat(HResult, GetType().FullName);", fullClassName, formatPrefix); } }
public CSharpWriterSymbols(CSharpContext ctx) : base(ctx) { this.writer = ctx.Writer; }
public CSharpWriterVisitor(CSharpContext ctx) : base(ctx) { this.writer = ctx.Writer; }
public string CreateInstaller() { if (_genInfo == null) { return(String.Empty); } Dictionary <string, string> sources = _genInfo.EventSources; Dictionary <string, bool> logNames = new Dictionary <string, bool>(StringComparer.OrdinalIgnoreCase); foreach (string val in sources.Values) { logNames[val] = val != "Application" && val != "Security" && val != "Setup" && val != "System"; } int maxCategory = _genInfo.Categories.Count; using (CsWriter code = new CsWriter()) { using (code.WriteNamespace(Namespace)) { code.WriteSummaryXml("Installer class for the Event Log messages"); code.WriteLine("[global::System.ComponentModel.RunInstaller(true)]"); using (code.WriteClass("public class Installer : System.Configuration.Install.Installer")) { foreach (KeyValuePair <string, string> kv in sources) { code.WriteLine("readonly System.Diagnostics.EventLogInstaller _install{0}{1};", kv.Value, kv.Key); } code.WriteLine(); code.WriteSummaryXml("Constructs the installer for the Event Log"); using (code.WriteBlock("public Installer()")) { foreach (KeyValuePair <string, string> kv in sources) { string name = String.Format("_install{0}{1}", kv.Value, kv.Key); code.WriteLine("{0} = new System.Diagnostics.EventLogInstaller();", name); code.WriteLine("{0}.Log = @\"{1}\";", name, kv.Value.Replace("\"", "\"\"")); code.WriteLine("{0}.Source = @\"{1}\";", name, kv.Key.Replace("\"", "\"\"")); code.WriteLine("{0}.CategoryCount = {1};", name, maxCategory); code.WriteLine( "{0}.UninstallAction = System.Configuration.Install.UninstallAction.Remove;", name); code.WriteLine("Installers.Add({0});", name); code.WriteLine(); } } code.WriteLine(); code.WriteSummaryXml("Customizes the MessageResourceFile durring installation"); using (code.WriteBlock("public override void Install(System.Collections.IDictionary state)")) { foreach (KeyValuePair <string, string> kv in sources) { code.WriteLine( "_install{0}{1}.CategoryResourceFile = _install{0}{1}.MessageResourceFile =", kv.Value, kv.Key); } code.WriteLine( " System.IO.Path.GetFullPath(Context.Parameters[\"assemblypath\"].Trim('\"'));"); code.WriteLine(); code.WriteLine("base.Install(state);"); foreach (KeyValuePair <string, bool> kv in logNames) { if (!kv.Value) { continue; //do not configure default logs } code.WriteLine(); using (code.WriteBlock("using (System.Diagnostics.EventLog log = new System.Diagnostics.EventLog(@\"{0}\", \".\"))", kv.Key.Replace("\"", "\"\""))) { code.WriteLine("log.MaximumKilobytes = 1024 * 10;"); code.WriteLine("log.ModifyOverflowPolicy(System.Diagnostics.OverflowAction.OverwriteAsNeeded, 30);"); } } } } } return(code.ToString()); } }
void WriteFormatters(CsWriter code) { if (_xstrings.Count > 0) { foreach (ResxString s in _xstrings) s.WriteAccessor(code, _fullClassName, "FormatStrings."); code.WriteLine(); code.WriteSummaryXml("Returns the raw format strings."); using (code.WriteClass("public static {0}class FormatStrings", _partial ? "partial " : "")) { foreach (ResxString s in _xstrings) s.WriteFormatString(code); } } if (_xexceptions.Count > 0) { code.WriteLine(); code.WriteSummaryXml("Returns the raw exception strings."); using (code.WriteClass("public static {0}class ExceptionStrings", _partial ? "partial " : "")) { code.WriteSummaryXml("Formats a message for an exception"); using (code.WriteBlock("internal static string SafeFormat(string message, params object[] args)")) { using(code.WriteBlock("try")) code.WriteLine("return string.Format(resourceCulture, message, args);"); using(code.WriteBlock("catch")) code.WriteLine("return message ?? string.Empty;"); } string helpLinkFormat = _options.HelpLinkFormat ?? String.Empty; String.Format(helpLinkFormat, 5, String.Empty);//just to make sure it's a valid format code.WriteSummaryXml("{0}", _options.HelpLinkFormat); using (code.WriteBlock("internal static string HelpLinkFormat(int hResult, string typeName)")) code.WriteLine("return SafeFormat({0}, hResult, typeName);", code.MakeString(helpLinkFormat)); foreach (ResxException ex in _xexceptions.Values) ex.WriteFormatString(code); } } }
void WriteStaticFactory(CsWriter code, string exceptionClass) { code.WriteSummaryXml("Used to recreate this exception from an hresult and message bypassing the message formatting"); using (code.WriteBlock("internal static System.Exception Create(int hResult, string message)")) code.WriteLine("return new {0}.{1}((System.Exception)null, hResult, message);", _nameSpace, exceptionClass); code.WriteSummaryXml("Constructs the exception from an hresult and message bypassing the message formatting"); using (code.WriteBlock("{0} {1}(System.Exception innerException, int hResult, string message) : base(message, innerException)", _sealed ? "private" : "protected", exceptionClass)) { code.WriteLine("base.HResult = hResult;"); if (!String.IsNullOrEmpty(_options.HelpLinkFormat)) code.WriteLine("base.HelpLink = {0}.ExceptionStrings.HelpLinkForHR(HResult);", _fullClassName); if (!String.IsNullOrEmpty(_options.EventSource)) code.WriteLine("base.Source = {0}.EventSourceName;", _fullClassName); if (_options.AutoLog && _options.EventCategoryId > 0) WriteSetProperty(code, true, "CategoryId", _fullClassName + ".EventCategoryId"); } }
/// <summary> /// Appends static properties used for event logging /// </summary> void WriteProperties(CsWriter code) { if (_options.AutoLog) { code.WriteLine(); code.WriteSummaryXml("Create the appropriate type of exception from an hresult using the specified message"); using (code.WriteBlock("public static bool TryCreateException(int hResult, string message, out System.Exception exception)")) using (code.WriteBlock("switch (unchecked((uint)hResult))")) { Dictionary <uint, bool> visited = new Dictionary <uint, bool>(); foreach (ResxException ex in _xexceptions.Values) { if (ex.HResult != 0 && !visited.ContainsKey(ex.HResult)) { visited.Add(ex.HResult, true); code.WriteLine( "case 0x{0:x8}U: exception = {1}.{2}.Create(hResult, message); return true;", ex.HResult, _nameSpace, ex.MemberName); } } code.WriteLine("default: exception = null; return false;"); } code.WriteLine(); code.WriteSummaryXml("The the event log facility id of events defined in this resource file"); code.WriteLine("internal static readonly int EventFacilityId = {0};", Math.Max(0, _options.FacilityId)); code.WriteLine(); code.WriteSummaryXml("The category id used to write events for this resource file"); code.WriteLine("internal static readonly int EventCategoryId = {0};", Math.Max(0, _options.EventCategoryId)); if (String.IsNullOrEmpty(_options.EventSource)) { Console.Error.WriteLine("Warning: AutoLog == true, but no event source name was defined."); } code.WriteLine(); code.WriteSummaryXml("The the event log used to write events for this resource file"); code.WriteLine("internal static readonly string EventLogName = {0};", code.MakeString(String.IsNullOrEmpty(_options.EventLog) ? "Application" : _options.EventLog)); code.WriteLine(); code.WriteSummaryXml("The event source used to write events"); code.WriteLine("internal static readonly string EventSourceName = {0};", code.MakeString(String.IsNullOrEmpty(_options.EventSource) ? "" : _options.EventSource)); code.WriteLine(); code.WriteSummaryXml("Writes an event log for the specified message id and arguments"); using (code.WriteBlock("internal static void WriteEvent(string eventLog, string eventSource, int category, System.Diagnostics.EventLogEntryType eventType, long eventId, object[] arguments, System.Exception error)")) { using (code.WriteBlock("try")) { if (String.IsNullOrEmpty(_eventLogger)) { using (code.WriteBlock("using (System.Diagnostics.EventLog log = new System.Diagnostics.EventLog(eventLog, \".\", eventSource))")) code.WriteLine("log.WriteEvent(new System.Diagnostics.EventInstance(eventId, category, eventType), null, arguments);"); } else { code.WriteLine("{0}(eventLog, eventSource, category, eventType, eventId, arguments, error);", _eventLogger); } } code.WriteLine("catch { }"); } } }
public void Write(TextWriter output) { string resxCode = CreateResources(); int lastBrace = resxCode.LastIndexOf('}') - 1; int nextLastBrace = resxCode.LastIndexOf('}', lastBrace) - 1; if(String.IsNullOrEmpty(_nameSpace)) nextLastBrace = lastBrace; output.WriteLine(resxCode.Substring(0, nextLastBrace - 1)); using (CsWriter code = new CsWriter()) { //Add formatting methods code.Indent = 2; code.WriteLine(); WriteProperties(code); WriteFormatters(code); code.Indent--; code.WriteLine(); code.WriteLine(resxCode.Substring(nextLastBrace, lastBrace - nextLastBrace)); foreach (ResxException e in _xexceptions.Values) e.WriteException(code, _fullClassName, "ExceptionStrings.", _baseException, _sealed, _partial); output.WriteLine(code.ToString()); } output.WriteLine(resxCode.Substring(lastBrace)); }
/// <summary> /// Appends static properties used for event logging /// </summary> void WriteProperties(CsWriter code) { if (_options.AutoLog) { code.WriteLine(); code.WriteSummaryXml("Create the appropriate type of exception from an hresult using the specified message"); using (code.WriteBlock("public static bool TryCreateException(int hResult, string message, out System.Exception exception)")) using (code.WriteBlock("switch (unchecked((uint)hResult))")) { Dictionary<uint, bool> visited = new Dictionary<uint, bool>(); foreach (ResxException ex in _xexceptions.Values) { if (ex.HResult != 0 && !visited.ContainsKey(ex.HResult)) { visited.Add(ex.HResult, true); code.WriteLine( "case 0x{0:x8}U: exception = {1}.{2}.Create(hResult, message); return true;", ex.HResult, _nameSpace, ex.MemberName); } } code.WriteLine("default: exception = null; return false;"); } code.WriteLine(); code.WriteSummaryXml("The the event log facility id of events defined in this resource file"); code.WriteLine("internal static readonly int EventFacilityId = {0};", Math.Max(0, _options.FacilityId)); code.WriteLine(); code.WriteSummaryXml("The category id used to write events for this resource file"); code.WriteLine("internal static readonly int EventCategoryId = {0};", Math.Max(0, _options.EventCategoryId)); if (String.IsNullOrEmpty(_options.EventSource)) Console.Error.WriteLine("Warning: AutoLog == true, but no event source name was defined."); code.WriteLine(); code.WriteSummaryXml("The the event log used to write events for this resource file"); code.WriteLine("internal static readonly string EventLogName = {0};", code.MakeString(String.IsNullOrEmpty(_options.EventLog) ? "Application" : _options.EventLog)); code.WriteLine(); code.WriteSummaryXml("The event source used to write events"); code.WriteLine("internal static readonly string EventSourceName = {0};", code.MakeString(String.IsNullOrEmpty(_options.EventSource) ? "" : _options.EventSource)); code.WriteLine(); code.WriteSummaryXml("Writes an event log for the specified message id and arguments"); using (code.WriteBlock("internal static void WriteEvent(string eventLog, string eventSource, int category, System.Diagnostics.EventLogEntryType eventType, long eventId, object[] arguments, System.Exception error)")) { using (code.WriteBlock("try")) { if (String.IsNullOrEmpty(_eventLogger)) { using (code.WriteBlock("using (System.Diagnostics.EventLog log = new System.Diagnostics.EventLog(eventLog, \".\", eventSource))")) code.WriteLine("log.WriteEvent(new System.Diagnostics.EventInstance(eventId, category, eventType), null, arguments);"); } else { code.WriteLine("{0}(eventLog, eventSource, category, eventType, eventId, arguments, error);",_eventLogger); } } code.WriteLine("catch { }"); } } }
void WriteException(CsWriter code, List<ResxGenItem> lst) { if (lst.Count == 0 || lst[0].IsException == false) return; ResxGenItem first = lst[0]; string exName = StronglyTypedResourceBuilder.VerifyResourceName(first.ItemName, Csharp); string baseName = ": " + _baseException; foreach (ResxGenItem item in lst) if (item.Comments.StartsWith(":")) baseName = item.Comments; code.WriteSummaryXml("Exception class: {0} {1}\r\n{2}", exName, baseName, first.Value); code.WriteLine("[System.SerializableAttribute()]"); using ( code.WriteClass("public {2}{3}class {0} {1}", exName, baseName, _sealed ? "sealed " : "", _partial ? "partial " : "")) { code.WriteSummaryXml("Serialization constructor"); code.WriteBlock( "{1} {0}(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context)", exName, _sealed ? "internal" : "protected") .Dispose(); WriteStaticFactory(code, exName); Dictionary<string, ResxGenArgument> publicData = new Dictionary<string, ResxGenArgument>(); foreach (ResxGenItem item in lst) foreach (ResxGenArgument arg in item.Args) if (arg.IsPublic) publicData[arg.Name] = arg; foreach (ResxGenArgument pd in publicData.Values) { if (pd.Name == "HResult" || pd.Name == "HelpLink" || pd.Name == "Source") continue; //uses base properties code.WriteLine(); code.WriteSummaryXml("The {0} parameter passed to the constructor", pd.ParamName); code.WriteLine( "public {1} {0} {{ get {{ if (Data[\"{0}\"] is {1}) return ({1})Data[\"{0}\"]; else return default({1}); }} }}", pd.Name, pd.Type); } code.WriteLine(); foreach (ResxGenItem item in lst) { string formatNm = String.Format("{0}.ExceptionStrings.{1}", _fullClassName, item.Identifier); string formatFn = _fullClassName + ".ExceptionStrings.SafeFormat"; string baseArgs = item.IsFormatter ? formatFn + "({0}, {1})" : "{0}"; string argList = item.HasArguments ? ", " + item.Parameters(true) : ""; string strHResult = item.HResult != 0 ? String.Format("unchecked((int)0x{0:X8}U)", item.HResult) : "-1"; code.WriteSummaryXml(item.Value); code.WriteLine("public {0}({1})", exName, item.Parameters(true)); using (code.WriteBlock("\t: this((System.Exception)null, {0}, {1})", strHResult, String.Format(baseArgs, formatNm, item.Parameters(false)))) { foreach (ResxGenArgument arg in item.Args) WriteSetProperty(code, arg.IsPublic, arg.Name, arg.ParamName); if (item.AutoLog) code.WriteLine("WriteEvent({0});", item.Parameters(false)); } code.WriteSummaryXml(item.Value); code.WriteLine("public {0}({1}{2}System.Exception innerException)", exName, item.Parameters(true), item.HasArguments ? ", " : ""); using (code.WriteBlock("\t: this(innerException, {0}, {1})", strHResult, String.Format(baseArgs, formatNm, item.Parameters(false)))) { foreach (ResxGenArgument arg in item.Args) WriteSetProperty(code, arg.IsPublic, arg.Name, arg.ParamName); if (item.AutoLog) code.WriteLine("WriteEvent({0});", item.Parameters(false)); } if (item.AutoLog) WriteAutoLog(code, item); code.WriteSummaryXml("if(condition == false) throws {0}", item.Value); using (code.WriteBlock("public static void Assert(bool condition{0})", argList)) code.WriteLine("if (!condition) throw new {0}({1});", exName, item.Parameters(false)); } } }
public string CreateConstants(string header) { string content = File.ReadAllText(header); Regex pattern = new Regex(@"^#define\s+(?<id>[\w_]*)\s+\(?(?:\(long\))?(?<value>.*?)\)?\s*?$", RegexOptions.Multiline | RegexOptions.IgnoreCase); Dictionary<string, string> defines = new Dictionary<string, string>(); foreach (Match m in pattern.Matches(content)) if (!m.Groups["id"].Value.StartsWith("CATEGORY_",StringComparison.Ordinal) && !m.Groups["id"].Value.StartsWith("FACILITY_",StringComparison.Ordinal)) defines.Add(m.Groups["id"].Value, m.Groups["value"].Value); using (CsWriter code = new CsWriter()) { code.WriteLine("// ReSharper disable InconsistentNaming"); code.WriteLine("#pragma warning disable 1591 //disable missing xml comments"); code.WriteLine(); using (code.WriteNamespace(Namespace)) { if (_genInfo != null) { Dictionary<int, string> items = _genInfo.Facilities; using (code.WriteBlock("public enum Facilities")) { List<int> sorted = new List<int>(items.Keys); sorted.Sort(); foreach (int key in sorted) code.WriteLine("{0} = {1},", StronglyTypedResourceBuilder.VerifyResourceName(items[key], Csharp), key); } code.WriteLine(); items = _genInfo.Categories; using (code.WriteBlock("public enum Categories")) { List<int> sorted = new List<int>(items.Keys); sorted.Sort(); foreach (int key in sorted) code.WriteLine("{0} = {1},", StronglyTypedResourceBuilder.VerifyResourceName(items[key], Csharp), key); } code.WriteLine(); } using (code.WriteBlock("public enum HResults : long")) { List<string> sorted = new List<string>(defines.Keys); sorted.Sort(); foreach (string key in sorted) code.WriteLine("{0} = {1},", StronglyTypedResourceBuilder.VerifyResourceName(key, Csharp), defines[key]); } } return code.ToString(); } }
void WriteAutoLog(CsWriter code, string fullClassName, string formatPrefix) { code.WriteSummaryXml("Prepares the arguments as strings and writes the event"); using (code.WriteBlock("private void WriteEvent({0})", Item.Parameters(true))) { base.WriteEvent(code, fullClassName, formatPrefix); } }
public CSharpContext With(CsWriter writer) { return(new CSharpContext(Grammar, SourceFile, Namespace, Output, writer)); }