public static void writeDiag(Plane qp, Boolean bRotateBoard = false) { var sb = new StringBuilder(); sb.AppendIndent(8) .Append(ruler(-1, bRotateBoard)) .Append(cNewline); for (var d = 0; d < nDiagonals; d++) { var dInverse = invertDiag(d); var nDiagLen = d < nFiles ? d + 1 : dInverse + 1; var vDiagMask = (Byte)((1 << nDiagLen) - 1); var uDiag = (UInt32)(qp >> DiagOffset[dInverse] & vDiagMask); sb.AppendIndent(8 - nDiagLen) .Append(ruler(d, bRotateBoard)) .AppendDiag(nDiagLen, uDiag) .Append(cNewline); } sb.AppendIndent(8) .Append(ruler(nDiagonals, bRotateBoard)) .Append(cNewline) .FlushLine(); }
public static void TraverseAllScene(StringBuilder xmlBuilder, List <GameObject> meshesToExport, SceneStatistics statistics) { var rootGameObjects = new List <GameObject>(); for (int i = 0; i < SceneManager.sceneCount; i++) { var roots = SceneManager.GetSceneAt(i).GetRootGameObjects(); rootGameObjects.AddRange(roots); } if (xmlBuilder != null) { xmlBuilder.AppendIndent(indentUnit, 3); xmlBuilder.AppendFormat("<scene position={{{0}}}>\n", Vector3ToJSONString(new Vector3(5, 0, 5))); } foreach (var rootGO in rootGameObjects) { RecursivelyTraverseTransform(rootGO.transform, xmlBuilder, meshesToExport, 4, statistics); } if (xmlBuilder != null) { xmlBuilder.AppendIndent(indentUnit, 3); xmlBuilder.Append("</scene>"); } }
/// <summary> /// Generates the method injection invoke. /// </summary> /// <param name="builder">The builder.</param> /// <param name="injectionMethodName">Name of the injection method.</param> /// <param name="methodCallInfoVariableName">Name of the method call information variable.</param> /// <param name="indent">The indent.</param> /// <param name="ifNullCall">If null call.</param> /// <param name="callAfterInjection">The call after injection.</param> protected void GenerateMethodInjectionInvoke(StringBuilder builder, string injectionMethodName, string methodCallInfoVariableName, int indent, string ifNullCall = null, string callAfterInjection = null) { if (builder != null && !string.IsNullOrWhiteSpace(injectionMethodName) && !string.IsNullOrWhiteSpace(methodCallInfoVariableName)) { builder.AppendIndent(indent); builder.AppendLineWithFormat("if(this._injectionDelegates.{0} != null)", injectionMethodName); builder.AppendBeginBrace(ref indent); builder.AppendIndent(indent); builder.AppendLineWithFormat("this._injectionDelegates.{0}({1});", injectionMethodName, methodCallInfoVariableName); if (!string.IsNullOrWhiteSpace(callAfterInjection)) { builder.AppendIndent(indent); builder.AppendLine(callAfterInjection); } builder.AppendEndBrace(ref indent); if (!string.IsNullOrWhiteSpace(ifNullCall)) { builder.AppendIndent(indent); builder.AppendLineWithFormat("else"); builder.AppendBeginBrace(ref indent); builder.AppendIndent(indent); builder.AppendLine(ifNullCall); builder.AppendEndBrace(ref indent); } } }
/// <summary> /// Generates the method call information declarition. /// </summary> /// <param name="builder">The builder.</param> /// <param name="methodInfo">The method information.</param> /// <param name="indent">The indent.</param> /// <param name="methodCallInfoVariableName">Name of the method call information variable.</param> protected void GenerateMethodCallInfoDeclarition(StringBuilder builder, MethodInfo methodInfo, int indent, string methodCallInfoVariableName) { if (builder != null && methodInfo != null && !string.IsNullOrWhiteSpace(methodCallInfoVariableName)) { var tmpMethodCallInfo = new MethodCallInfo(); tmpMethodCallInfo.Fill(methodInfo); builder.AppendIndent(indent); builder.Append(string.Format("{0} {1} = new {0}(", typeof(MethodCallInfo).ToCodeLook(), methodCallInfoVariableName)); builder.Append(string.Format("\"{0}\",", tmpMethodCallInfo.MethodFullName)); builder.Append(" new Dictionary<string, object>{"); foreach (var one in tmpMethodCallInfo.InArgs) { builder.Append(" {\""); builder.Append(one.Key); builder.Append("\", "); builder.Append(one.Key); builder.Append("},"); } builder.RemoveLastIfMatch(StringConstants.CommaChar); builder.Append("}"); builder.AppendLine(")"); builder.AppendBeginBrace(ref indent); builder.AppendIndent(indent); builder.Append("SerializableArgNames = new System.Collections.Generic.List<System.String> {"); builder.Append(CSharpCodeGenerateUtil.CombineCode(tmpMethodCallInfo.SerializableArgNames, (x) => { return(x.AsQuotedString()); }, 16)); builder.AppendLine("}"); builder.AppendEndBrace(ref indent); builder.AppendLine(";"); } }
public static void ProcessAudio(Transform tra, string entityName, StringBuilder exportStr) { var audioSource = tra.GetComponent <AudioSource>(); if (audioSource && exportStr != null) { var audioClip = audioSource.clip; string audioClipRelPath = null; if (audioClip) { audioClipRelPath = string.Format("'{0}'", GetAudioClipRelativePath(audioClip)); resourceRecorder.audioClipsToExport.Add(audioClip); } var playFunctionName = "playAudioSource" + Mathf.Abs(audioSource.GetInstanceID()); exportStr.AppendFormat( @"var audioSource = new AudioSource(new AudioClip({0})) var {1} = () => {{ {2}{3}.addComponent(audioSource)\n" , audioClipRelPath, playFunctionName, indentUnit, entityName); exportStr.AppendIndent(indentUnit, 1).AppendFormat("audioSource.playing = {0}\n", BoolToString(audioSource.playOnAwake)); exportStr.AppendIndent(indentUnit, 1).AppendFormat("audioSource.loop = {0}\n", BoolToString(audioSource.loop)); exportStr.AppendIndent(indentUnit, 1).AppendFormat("audioSource.volume = {0}\n", audioSource.volume); exportStr.AppendIndent(indentUnit, 1).AppendFormat("audioSource.pitch = {0}\n", audioSource.pitch); exportStr.Append("}\n"); resourceRecorder.audioSourceAddFunctions.Add(playFunctionName); } }
/// <summary>Yield all subdirectories of the supplied path as a text outline.</summary> /// <param name="rootPath">Topmost directory.</param> /// <param name="fileFilter">Search pattern or *null* for all.</param> /// <param name="drawWith">Outline characters.</param> /// <param name="order">Output sorting.</param> /// <param name="tab">Number of characters to indent per level.</param> /// <returns>All subdirectories of the supplied path as a text outline.</returns> public static IEnumerable <string> GenerateTextTree(string rootPath, string fileFilter, DrawWith drawWith = DrawWith.Graphic, Ordering order = Ordering.None, int tab = 4) { var sb = new StringBuilder(); for (var dv = new DirNode.Vector(rootPath, null, order, drawWith, tab); dv.Advance(); sb.Length = 0) { sb.AppendIndent(dv, false); sb.Append(dv.Depth == 0 ? dv.Top.Path : dv.Top.Name); yield return(sb.ToString()); if (fileFilter != null) { dv.PregetContents(fileFilter); if (dv.Top.FileInfos.Count > 0) { sb.Length = 0; sb.AppendIndent(dv, true); int indentLength = sb.Length; foreach (var fInfo in dv.Top.FileInfos) { sb.Append(fInfo.Name); yield return(sb.ToString()); sb.Length = indentLength; } yield return(sb.ToString()); } } } }
private static string SetJson(SetRecord record, int indent, bool ignoreFirstIndent) { StringBuilder builder = new StringBuilder(capacity: record.Count * 64); if (ignoreFirstIndent == false) { builder.AppendIndent(indent); } builder.Append('{'); int indentPlus = indent + 1; int indentPPlus = indentPlus + 1; foreach (var pair in record) { builder.AppendLine(); builder.AppendIndent(indentPlus); builder.AppendFormat("\"{0}\": {1}", pair.Key, Json(pair.Value, indentPlus, true)); builder.Append(','); } if (builder.Length > 0) { builder.Remove(builder.Length - 1, 1); } builder.AppendLine(); builder.AppendIndent(indent); builder.Append('}'); return(builder.ToString()); }
private static string BuildInstantiation(DependencyDefinition from) { var builder = new StringBuilder(); switch (from.Provider.Strategy) { case ProviderType.Implementation: { builder.AppendIndent(3); builder.Append(from.Type.FullName); builder.Append(" result = new "); builder.Append(from.Provider.Type.FullName); builder.AppendMethodDependencies(from.Provider.Dependencies, 3); } break; case ProviderType.Factory: { builder.AppendGetDependency(from.Provider.Type, assignTo: "factory", indent: 3, end: true); builder.AppendIndent(3); builder.Append(from.Type.FullName); builder.Append(" result = factory."); builder.Append(from.Provider.Method.Name); builder.AppendMethodDependencies(from.Provider.Dependencies, 3); } break; } builder.AppendLine(); return(builder.ToString()); }
public static void TraverseAllScene(StringBuilder xmlBuilder, List <GameObject> meshesToExport, SceneStatistics statistics, SceneWarningRecorder warningRecorder) { var rootGameObjects = new List <GameObject>(); for (int i = 0; i < SceneManager.sceneCount; i++) { var roots = SceneManager.GetSceneAt(i).GetRootGameObjects(); rootGameObjects.AddRange(roots); } if (xmlBuilder != null) { xmlBuilder.AppendIndent(indentUnit, 3); xmlBuilder.AppendFormat("<scene position={{{0}}}>\n", Vector3ToJSONString(new Vector3(5, 0, 5))); } _sceneMeta = Object.FindObjectOfType <DclSceneMeta>(); primitiveMaterialsToExport = new List <Material>(); primitiveTexturesToExport = new List <Texture>(); GameObjectToNodeTypeDict.Clear(); //====== Start Traversing ====== foreach (var rootGO in rootGameObjects) { RecursivelyTraverseTransform(rootGO.transform, xmlBuilder, meshesToExport, 4, statistics, warningRecorder, GameObjectToNodeTypeDict); } foreach (var material in primitiveMaterialsToExport) { var materialXml = xmlBuilder != null ? new StringBuilder() : null; TraverseMaterial(material, materialXml, warningRecorder); //Append materials if (xmlBuilder != null) { xmlBuilder.AppendIndent(indentUnit, 4); xmlBuilder.Append(materialXml).Append("\n"); } } //Check textures if (warningRecorder != null) { foreach (var texture in primitiveTexturesToExport) { CheckTextureValidity(texture, warningRecorder); } } statistics.materialCount += primitiveMaterialsToExport.Count; //TODO: include glTF's materials statistics.textureCount += primitiveTexturesToExport.Count; //TODO: include glTF's textures if (xmlBuilder != null) { xmlBuilder.AppendIndent(indentUnit, 3); xmlBuilder.Append("</scene>"); } }
public string ToString(int indentLevel) { StringBuilder ret = new StringBuilder(); ret.AppendIndent(indentLevel).Append('-').AppendNullable(this.OldValue).AppendLine(); ret.AppendIndent(indentLevel).Append('+').AppendNullable(this.NewValue); return(ret.ToString()); }
private static void AppendNestedClassTitle(this StringBuilder sb, string name, int deep) { sb.AppendIndent(deep); sb.AppendLine($"public Type_{name} {name} {{ get; private set; }}"); sb.AppendLine(); sb.AppendIndent(deep); sb.AppendLine($"public sealed class Type_{name}"); sb.AppendIndent(deep); sb.AppendLine("{"); }
/// <summary> /// Writes the constructor. /// </summary> /// <param name="builder">The builder.</param> /// <param name="className">Name of the class.</param> protected virtual void WriteConstructor(StringBuilder builder, string className) { if (builder != null) { builder.AppendIndent(2); builder.AppendLineWithFormat("public {0}() : base()", className); builder.AppendIndent(2); builder.AppendLine("{"); builder.AppendIndent(2); builder.AppendLine("}"); builder.AppendLine(); } }
/// <summary> /// Writes the constructor. /// </summary> /// <param name="builder">The builder.</param> /// <param name="className">Name of the class.</param> protected override void WriteConstructor(StringBuilder builder, string className) { if (builder != null) { builder.AppendIndent(2); builder.AppendLineWithFormat("public {0}({1} instance, {2} injectionDelegates):base(instance, injectionDelegates)", className, typeof(T).ToCodeLook(), typeof(MethodInjectionDelegates).ToCodeLook()); builder.AppendIndent(2); builder.AppendLine("{"); builder.AppendIndent(2); builder.AppendLine("}"); builder.AppendLine(); } }
/// <summary> /// Generates the code. /// </summary> /// <param name="builder">The builder.</param> /// <param name="namespace">The namespace.</param> /// <param name="targetClassName">Name of the target class.</param> /// <param name="inheritedClass">The inherited class.</param> /// <param name="selfClass">The self class.</param> /// <param name="methodsToBuild">The methods to build.</param> /// <returns></returns> protected void GenerateCode(StringBuilder builder, string @namespace, string targetClassName, Type inheritedClass, Type selfClass, List <MethodInfo> methodsToBuild) { try { methodsToBuild.CheckNullObject(nameof(methodsToBuild)); //Start to build code WriteFileInfo(builder); WriteNamespaces(builder); builder.AppendLine(); // write namespace builder.AppendLineWithFormat("namespace {0}", Namespace); builder.AppendLine("{"); // write class declaration builder.AppendIndent(1); builder.Append(GenerateClassDeclarationPart(ClassName, selfClass.GetInterfaces())); builder.AppendIndent(1); builder.AppendLine("{"); // write constructor WriteConstructor(builder, ClassName); foreach (var one in methodsToBuild) { GenerateCoreMethod(builder, one); } // End of class builder.AppendIndent(1); builder.AppendLine("}"); // End of namespace builder.AppendLine("}"); builder.AppendLine(); //End of code build } catch (Exception ex) { throw ex.Handle(); } }
private static string ScalerJson(ScalerRecord record, int indent, bool ignoreFirstIndent) { StringBuilder builder = new StringBuilder(capacity: 64); if (ignoreFirstIndent == false) { builder.AppendIndent(indent); } switch (record.ScalerType) { case ScalerType.Null: builder.Append("null"); break; case ScalerType.String: builder.AppendFormat("\"{0}\"", record.Value); break; case ScalerType.Decimal: case ScalerType.Double: builder.Append(record.Value.ToString()); break; case ScalerType.Boolean: builder.Append(record.Value.ToString().ToLower()); break; default: throw new NotImplementedException(); } return(builder.ToString()); }
/// <summary> /// Appends a string with indentation which defined by specified indent level and unit. /// </summary> /// <param name="self"> The <see cref="StringBuilder" /> to append to. </param> /// <param name="value"> The string to append. </param> /// <param name="indentLevel"> Number of unit string to append. </param> /// <param name="indentUnit"> Unit string of each indent level. </param> /// <returns> The <paramref name="self" /> instance. </returns> public static StringBuilder IndentedAppend( this StringBuilder self, string value, byte indentLevel, string indentUnit) { if (indentLevel == 0) { return(self.Append(value)); } if (string.IsNullOrEmpty(value)) { return(self); } self.AppendHeadIndent(indentLevel, indentUnit); int count = value.Length; for (int i = 0; i < count; ++i) { var c = value[i]; self.Append(c); if (c == '\n' && i != count - 1) { self.AppendIndent(indentLevel, indentUnit); } } return(self); }
public string ToString(int indentLevel) { StringBuilder ret = new StringBuilder(); ret.AppendIndent(indentLevel).Append(' ').Append(this.Property.Name).Append(':').AppendNullable(this.Value); return(ret.ToString()); }
/// <summary> /// Appends an indent string combined by specified level and unit if the <see cref="StringBuilder" /> is empty. /// </summary> /// <param name="self"> The <see cref="StringBuilder" /> to append to. </param> /// <param name="indentLevel"> Number of unit string to append. </param> /// <param name="indentUnit"> Unit string of each indent level. </param> /// <returns> The <paramref name="self" /> instance. </returns> public static StringBuilder AppendHeadIndent(this StringBuilder self, byte indentLevel, string indentUnit) { if (self.Length == 0 || self[self.Length - 1] == '\n') { self.AppendIndent(indentLevel, indentUnit); } return(self); }
public string ToString(int indentLevel) { StringBuilder ret = new StringBuilder(); ret.AppendIndent(indentLevel).Append('+').Append(this.ItemIndex).Append(':').AppendNullable(this.NewValue); return(ret.ToString()); }
public string ToString(int indentLevel) { StringBuilder ret = new StringBuilder(); ret.AppendIndent(indentLevel).Append("C<<<").AppendLine(); foreach (IDiffItem diffItem in this.Left) { ret.Append(diffItem.ToString(indentLevel + 1)).AppendLine(); } ret.AppendIndent(indentLevel).Append("C>>>").AppendLine(); foreach (IDiffItem diffItem in this.Right) { ret.Append(diffItem.ToString(indentLevel + 1)).AppendLine(); } return(ret.ToString().TrimEnd('\r', '\n')); }
public string ToString(int indentLevel) { StringBuilder ret = new StringBuilder(); ret.AppendIndent(indentLevel).Append('=').Append(this.Key).Append(':').AppendLine(); ret.Append(this.ValueDiff.ToString(indentLevel + 1)); return(ret.ToString()); }
/// <summary> /// APIs the trace log to string. /// </summary> /// <param name="builder">The builder.</param> /// <param name="log">The log.</param> /// <param name="level">The level.</param> /// <returns>System.String.</returns> private static void ApiTraceLogToString(StringBuilder builder, ApiTraceStep log, int level) { if (builder != null && log != null) { builder.AppendIndent(level); builder.AppendLineWithFormat("Entry: {0}", log.EntryStamp.ToFullDateTimeString()); builder.AppendIndent(level); builder.AppendLineWithFormat("Exit: {0}", log.ExitStamp.ToFullDateTimeString()); builder.AppendIndent(level); builder.AppendLineWithFormat("Exception Key: {0}", log.ExceptionKey); builder.AppendIndent(level); foreach (var one in log.InnerTraces) { builder.AppendLineWithFormat("Inner trace: "); ApiTraceLogToString(builder, one, level + 1); } } }
public static void AppendIndentLine(this StringBuilder stringBuilder, int count, string value) { if (stringBuilder == null) { throw new ArgumentNullException(nameof(stringBuilder)); } stringBuilder.AppendIndent(count); stringBuilder.AppendLine(value); }
/// <summary> /// Appends the indent. /// Returns the same <see cref="StringBuilder"/> instance to make sure it supports chain based actions. /// </summary> /// <param name="stringBuilder">The string builder.</param> /// <param name="level">The level.</param> /// <returns>System.Text.StringBuilder.</returns> private static StringBuilder AppendIndent(this StringBuilder stringBuilder, int level) { if (stringBuilder != null) { stringBuilder.AppendIndent(indentChar, level * 2); stringBuilder.Append(" "); } return(stringBuilder); }
private static void AppendComment(this StringBuilder sb, string comment, int deep) { var commentList = comment.Split('\n'); foreach (var c in commentList) { sb.AppendIndent(deep); sb.AppendLine($"// {c}"); } }
private static string ListJson(ListRecord record, int indent, bool ignoreFirstIndent) { StringBuilder builder = new StringBuilder(capacity: record.Count * 64); if (ignoreFirstIndent == false) { builder.AppendIndent(indent); } builder.Append('['); int indentPlus = indent + 1; if (record.All(rec => rec is ScalerRecord)) { foreach (var value in record) { builder.Append(Json(value, indentPlus, true)); builder.Append(','); } if (record.Count > 0) { builder.Remove(builder.Length - 1, 1); } builder.Append(']'); } else { foreach (var value in record) { builder.AppendLine(); builder.Append(Json(value, indentPlus, false)); builder.Append(','); } if (builder.Length > 0) { builder.Remove(builder.Length - 1, 1); } builder.AppendLine(); builder.AppendIndent(indent); builder.Append(']'); } return(builder.ToString()); }
public static void AppendCommentLine(this StringBuilder stringBuilder, int count, string value) { value = value.Trim().Replace("\n\n", "\n").Replace(" \n", "\n"); var escapedValue = XmlEscape(value); stringBuilder.AppendIndent(count); stringBuilder.Append("/// "); stringBuilder.AppendLine(escapedValue .Replace("\n", $"\n{new string(Space, count)}/// ") .Replace("/// \n", "///\n")); }
string GetParcelsString() { /* * "30,-15", * "30,-16", * "31,-15"*/ var sb = new StringBuilder(); if (sceneMeta.parcels.Count > 0) { const string indentUnit = " "; sb.AppendIndent(indentUnit, 3).Append(ParcelToString(sceneMeta.parcels[0])); for (var i = 1; i < sceneMeta.parcels.Count; i++) { sb.Append(",\n"); sb.AppendIndent(indentUnit, 3).Append(ParcelToString(sceneMeta.parcels[i])); } } return(sb.ToString()); }
//public static readonly Dictionary<GameObject, EDclNodeType> GameObjectToNodeTypeDict = new Dictionary<GameObject, EDclNodeType>(); public static ResourceRecorder TraverseAllScene(StringBuilder exportStr, SceneStatistics statistics, SceneWarningRecorder warningRecorder) { var rootGameObjects = new List <GameObject>(); for (int i = 0; i < SceneManager.sceneCount; i++) { var roots = SceneManager.GetSceneAt(i).GetRootGameObjects(); rootGameObjects.AddRange(roots); } _sceneMeta = Object.FindObjectOfType <DclSceneMeta>(); _resourceRecorder = new ResourceRecorder(); //GameObjectToNodeTypeDict.Clear(); //====== Start Traversing ====== foreach (var rootGO in rootGameObjects) { RecursivelyTraverseTransform(rootGO.transform, exportStr, _resourceRecorder, 4, statistics, warningRecorder); } //Append PlayAudio functions if (exportStr != null) { if (_resourceRecorder.audioSourceAddFunctions.Count > 0) { exportStr.AppendLine(); exportStr.AppendLine( @"export class AutoPlayUnityAudio implements ISystem { activate() {"); foreach (var functionName in _resourceRecorder.audioSourceAddFunctions) { exportStr.AppendIndent(indentUnit, 2).AppendFormat("{0}()\n", functionName); } exportStr.AppendLine( @" } } engine.addSystem(new AutoPlayUnityAudio()) "); } } if (statistics != null) { statistics.textureCount = _resourceRecorder.primitiveTexturesToExport.Count + _resourceRecorder.gltfTextures.Count; } return(_resourceRecorder); }
/// <summary> /// Appends an array of characters with indentation which defined by specified indent level and unit. /// </summary> /// <param name="self"> The <see cref="StringBuilder" /> to append to. </param> /// <param name="value"> The array of characters to append. </param> /// <param name="startIndex"> The starting position in <paramref name="value" />. </param> /// <param name="charCount"> The number of characters to append. </param> /// <param name="indentLevel"> Number of unit string to append. </param> /// <param name="indentUnit"> Unit string of each indent level. </param> /// <returns> The <paramref name="self" /> instance. </returns> public static StringBuilder IndentedAppend(this StringBuilder self, char[] value, int startIndex, int charCount, byte indentLevel, string indentUnit) { if (indentLevel == 0) { return(self.Append(value, startIndex, charCount)); } if (startIndex < 0) { throw new ArgumentOutOfRangeException("startIndex"); } if (charCount < 0) { throw new ArgumentOutOfRangeException("charCount"); } if (value == null) { if (startIndex == 0 && charCount == 0) { return(self); } throw new ArgumentNullException("value"); } if (charCount > value.Length - startIndex) { throw new ArgumentOutOfRangeException("charCount"); } if (charCount == 0) { return(self); } self.AppendHeadIndent(indentLevel, indentUnit); int count = value.Length; int endIndex = startIndex + charCount; for (int i = startIndex; i < endIndex; ++i) { var c = value[i]; self.Append(c); if (c == '\n' && i != count - 1) { self.AppendIndent(indentLevel, indentUnit); } } return(self); }
public static string Format(this Collection <CustomAttribute> attributes) { if (attributes == null || attributes.Count == 0) return String.Empty; var sb = new StringBuilder (); foreach (CustomAttribute attr in attributes) { if (ignored_attributes.ContainsKey (attr.AttributeType.FullName)) continue; sb.AppendIndent ("["); sb.Append (FormatName (attr)); sb.AppendLine ("]"); } return sb.ToString (); }
/// <summary> /// APIs the trace log to string. /// </summary> /// <param name="log">The log.</param> /// <param name="level">The level.</param> /// <returns>System.String.</returns> private static string ApiTraceLogToString(ApiTraceLogPiece log, int level) { StringBuilder builder = new StringBuilder(); if (log != null) { builder.AppendIndent(' ', 2 * (level + 1)); builder.AppendLineWithFormat("Entry: {0}", log.EntryStamp.ToFullDateTimeString()); builder.AppendIndent(' ', 2 * (level + 1)); builder.AppendLineWithFormat("Exit: {0}", log.ExitStamp.ToFullDateTimeString()); builder.AppendIndent(' ', 2 * (level + 1)); builder.AppendLineWithFormat("Parameters: {0}", log.MethodParameters.ToJson()); builder.AppendIndent(' ', 2 * (level + 1)); builder.AppendLineWithFormat("Exception: {0}", log.Exception == null ? "NA" : log.Exception.ToJson()); builder.AppendIndent(' ', 2 * (level + 1)); foreach (var one in log.InnerTraces) { builder.AppendLineWithFormat("Inner trace: {0}", ApiTraceLogToString(one, level + 1)); } } return builder.ToString(); }
public static string FormatName(this EventDefinition ev) { if (ev == null) return String.Empty; var sb = new StringBuilder (); if (ev.HasCustomAttributes) sb.Append (ev.CustomAttributes.Format ()); MethodDefinition adder = ev.AddMethod; MethodDefinition remover = ev.RemoveMethod; MethodDefinition accessor = null; ushort adderAccessMask; ushort removerAccessMask; ushort evAccessMask; GatherAccessorInfo (adder, remover, out accessor, out evAccessMask, out adderAccessMask, out removerAccessMask); sb.AppendIndent (FormatAttributes (accessor)); sb.Append ("event "); sb.Append (FormatName (ev.EventType)); sb.Append (' '); sb.Append (ev.Name); sb.Append (' '); sb.Append ("{"); sb.Append (FormatAccessor ("add", adder, adderAccessMask != evAccessMask)); sb.Append (FormatAccessor ("remove", remover, removerAccessMask != evAccessMask)); sb.AppendLine (); sb.AppendLineIndent ("}"); sb.AppendLine (); return sb.ToString (); }
/// <summary> /// Formats to string. /// </summary> /// <param name="stringBuilder">The string builder.</param> /// <param name="exception">The exception.</param> /// <param name="level">The level.</param> private static void FormatToString(StringBuilder stringBuilder, Exception exception, int level) { if (stringBuilder != null && exception != null) { BaseException baseException = exception as BaseException; stringBuilder.AppendIndent(level).AppendLineWithFormat("Exception Type: {0}", exception.GetType().ToString()); if (baseException != null) { stringBuilder.AppendIndent(level).AppendLineWithFormat("Exception Code: {0}({1})", baseException.Code.ToString(), (int)baseException.Code); } SqlException sqlException = exception as SqlException; if (sqlException != null) { int i = 0; stringBuilder.AppendIndent(level).AppendLineWithFormat("SQL error. Count = {0}", sqlException.Errors.Count); foreach (SqlError sqlError in sqlException.Errors) { i++; int tempLevel = level + 1; stringBuilder.AppendIndent(tempLevel).AppendLineWithFormat("---------- Error #{0} ----------", i); stringBuilder.AppendIndent(tempLevel).AppendLineWithFormat("->Class: {0}", sqlError.Class); stringBuilder.AppendIndent(tempLevel).AppendLineWithFormat("->Number: {0}", sqlError.Number); stringBuilder.AppendIndent(tempLevel).AppendLineWithFormat("->Server: {0}", sqlError.Server); stringBuilder.AppendIndent(tempLevel).AppendLineWithFormat("->Source: {0}", sqlError.Source); stringBuilder.AppendIndent(tempLevel).AppendLineWithFormat("->Procedure: {0}", sqlError.Procedure); stringBuilder.AppendIndent(tempLevel).AppendLineWithFormat("->LineNumber: {0}", sqlError.LineNumber); stringBuilder.AppendIndent(tempLevel).AppendLineWithFormat("->State: {0}", sqlError.State); stringBuilder.AppendIndent(tempLevel).AppendLineWithFormat("->Message: {0}", sqlError.Message); } } stringBuilder.AppendIndent(level).AppendLineWithFormat("Exception Message: {0}", exception.Message); stringBuilder.AppendIndent(level).AppendLineWithFormat("Source: {0}", exception.Source); stringBuilder.AppendIndent(level).AppendLineWithFormat("Site: {0}", exception.TargetSite); stringBuilder.AppendIndent(level).AppendLineWithFormat("StackTrace: {0}", exception.StackTrace); if (baseException != null) { stringBuilder.AppendIndent(level).AppendLineWithFormat("Exception Code: {0}({1})", baseException.Code.ToString(), (int)baseException.Code); stringBuilder.AppendIndent(level).AppendLineWithFormat("Operator Credential: {0}", baseException.OperatorCredential.ToJson()); stringBuilder.AppendIndent(level).AppendLineWithFormat("Scene: {0}", baseException.Scene.ToJson()); stringBuilder.AppendIndent(level).AppendLineWithFormat("Hint: {0}", baseException.Hint.ToJson()); } stringBuilder.AppendIndent(level).AppendLineWithFormat("Data Reference: {0}", GenerateDataString(baseException?.ReferenceData?.ToJson())); if (exception.InnerException != null) { level++; stringBuilder.AppendIndent(level).AppendLine("-------------------- Inner Exception --------------------"); FormatToString(stringBuilder, exception.InnerException, level); } } }
public static string FormatName(this PropertyDefinition prop) { if (prop == null) return String.Empty; var sb = new StringBuilder (); if (prop.HasCustomAttributes) sb.Append (prop.CustomAttributes.Format ()); MethodDefinition getter = prop.GetMethod; MethodDefinition setter = prop.SetMethod; MethodDefinition accessor = null; ushort getterAccessMask; ushort setterAccessMask; ushort propAccessMask; GatherAccessorInfo (getter, setter, out accessor, out propAccessMask, out getterAccessMask, out setterAccessMask); sb.AppendIndent (FormatAttributes (accessor)); sb.Append (FormatName (prop.PropertyType)); sb.Append (' '); if (prop.HasParameters) { sb.Append ("this ["); bool first = true; foreach (ParameterDefinition p in prop.Parameters) { if (!first) sb.Append (", "); else first = false; sb.Append (FormatName (p)); } sb.Append ("]"); } else if (accessor.IsExplicitImplementation ()) { TypeReference iface; MethodReference ifaceMethod; accessor.GetInfoForExplicitlyImplementedMethod (out iface, out ifaceMethod); if (iface != null) { sb.Append (iface.Name); sb.Append ('.'); string name = prop.Name; string iname = iface.FullName + "."; if (name.StartsWith (iname, StringComparison.OrdinalIgnoreCase)) sb.Append (name.Substring (iname.Length)); else sb.Append (name); } else sb.Append (prop.Name); } else sb.Append (prop.Name); sb.Append (' '); sb.Append ("{"); sb.Append (FormatAccessor ("get", getter, getterAccessMask != propAccessMask)); sb.Append (FormatAccessor ("set", setter, setterAccessMask != propAccessMask)); sb.AppendLine (); sb.AppendLineIndent ("}"); sb.AppendLine (); return sb.ToString (); }
public static string FormatName(this MethodDefinition method) { if (method == null) return String.Empty; string name = method.Name; var sb = new StringBuilder (); if (method.HasCustomAttributes) sb.Append (method.CustomAttributes.Format ()); sb.AppendIndent (FormatAttributes (method)); if (!method.IsSpecialName) { sb.Append (FormatName (method.ReturnType)); sb.Append (' '); } else if (method.IsAccessor ()) return String.Empty; if (method.IsConstructor) sb.Append (FormatGenericTypeName (method.DeclaringType.Name)); else if (name == "Finalize") sb.Append ("~" + FormatGenericTypeName (method.DeclaringType.Name)); else if (method.IsSpecialName) sb.Append (TranslateSpecialName (method)); else if (method.IsExplicitImplementation ()) { TypeReference iface; MethodReference ifaceMethod; method.GetInfoForExplicitlyImplementedMethod (out iface, out ifaceMethod); if (iface != null) { sb.Append (FormatName (iface)); sb.Append ('.'); sb.Append (ifaceMethod.Name); } else sb.Append (method.Name); } else sb.Append (name); bool first = true; if (method.HasGenericParameters) { sb.Append ('<'); foreach (GenericParameter gp in method.GenericParameters) { if (!first) sb.Append (", "); else first = false; sb.Append (FormatName (gp)); } sb.Append ("> "); } sb.Append (" ("); if (method.HasParameters) { first = true; foreach (ParameterDefinition p in method.Parameters) { if (!first) sb.Append (", "); else first = false; sb.Append (FormatName (p)); } } sb.Append (")"); if (method.IsAbstract || method.DeclaringType.IsInterface) sb.AppendLine (";"); else { sb.AppendLine (); sb.AppendLineIndent ("{"); try { Utils.Indent++; sb.AppendLineIndent ("throw new NotImplementedException ();"); } finally { Utils.Indent--; } sb.AppendLineIndent ("}"); sb.AppendLine (); } return sb.ToString (); }
public static string Format(string val, int indent = 2, bool setBrackets = false) { StringBuilder builder = new StringBuilder(); int index = 0; int level = indent; bool quotation = false; bool trim = false; int lines = 1; if (level == 2) { builder.AppendLineUnix(); builder.AppendIndent(level); } while (index < val.Length) { char c = val[index]; switch (c) { case ';': if (!quotation) { lines++; builder.Append(";\n"); builder.AppendIndent(level); trim = true; } else { builder.Append(c); } break; case '{': if (!quotation) { lines++; builder.Append("{\n"); level++; builder.AppendIndent(level); trim = true; } else { builder.Append(c); } break; case '}': if (!quotation) { level--; lines++; if (builder.Length > 0 && builder[builder.Length - 1] == '\t') { builder[builder.Length - 1] = '}'; } else { builder.Append(c); } builder.Append('\n'); builder.AppendIndent(level); trim = true; } else { builder.Append(c); } break; case ' ': case '\t': if (trim) { index++; continue; } builder.Append(c); break; case '\"': trim = false; quotation = !quotation; builder.Append(c); break; default: trim = false; builder.Append(c); break; } index++; } string toRet = builder.ToString(); if (indent == 2) { toRet = toRet.Trim(new char[] { '\n', '\t' }); if (lines <= 2) return " " + toRet + " "; return "\n\t\t" + toRet + "\n\t"; } return toRet; }
static void WriteType(StringBuilder sb, List <string> usings, TypeDefinition type, StubGenOptions opts) { Action <StringBuilder, List <string>, TypeDefinition, StubGenOptions> typeWriter = null; // TODO: security attributes if (type.IsSerializable) sb.AppendLineIndent ("[Serializable]"); if (type.HasCustomAttributes) sb.Append (type.CustomAttributes.Format ()); sb.AppendIndent (); FormatTypeAttributes (sb, type); if (type.IsEnum) { sb.Append ("enum"); typeWriter = EnumWriter; } else if (type.IsClass) { sb.Append ("class"); typeWriter = ClassWriter; } else if (type.IsInterface) { sb.Append ("interface"); typeWriter = InterfaceWriter; } else if (type.IsValueType) { if (type.FullName == "System.Delegate" || type.FullName == "System.MulticastDelegate") sb.Append ("delegate"); else sb.Append ("struct"); } sb.AppendFormat (" {0}", type.FormatName ()); bool haveColon = false; bool first = true; TypeReference tref = type.BaseType; if (WritableBaseType (tref)) { sb.Append (" : "); haveColon = true; first = false; usings.AddUsing (tref.Namespace); sb.Append (tref.FormatName ()); } if (type.HasInterfaces) { foreach (TypeReference tr in type.Interfaces.OnlyVisible (opts.IncludeNonPublic)) { if (first) { if (!haveColon) sb.Append (" : "); first = false; } else sb.Append (", "); usings.AddUsing (tr.Namespace); sb.Append (tr.FormatName ()); } } // TODO: output generic parameter constraints sb.AppendLine (); sb.AppendLineIndent ("{"); if (typeWriter != null) { Utils.Indent++; try { typeWriter (sb, usings, type, opts); } finally { Utils.Indent--; } } sb.AppendLineIndent ("}"); }
/// <summary> /// APIs the trace log to string. /// </summary> /// <param name="builder">The builder.</param> /// <param name="log">The log.</param> /// <param name="level">The level.</param> /// <returns>System.String.</returns> private static void ApiTraceLogToString(StringBuilder builder, ApiTraceLogPiece log, int level) { if (builder != null && log != null) { builder.AppendIndent(' ', 2 * (level + 1)); builder.AppendLineWithFormat("Entry: {0}", log.EntryStamp.ToFullDateTimeString()); builder.AppendIndent(' ', 2 * (level + 1)); builder.AppendLineWithFormat("Exit: {0}", log.ExitStamp.ToFullDateTimeString()); builder.AppendIndent(' ', 2 * (level + 1)); builder.AppendLineWithFormat("Exception Key: {0}", log.ExceptionKey); builder.AppendIndent(' ', 2 * (level + 1)); foreach (var one in log.InnerTraces) { builder.AppendLineWithFormat("Inner trace: "); ApiTraceLogToString(builder, one, level + 1); } } }
public static string FormatName(this FieldDefinition field) { if (field == null) return String.Empty; if (field.HasCustomAttributes) field.CustomAttributes.Format (); var sb = new StringBuilder (); sb.AppendIndent (FormatAttributes (field)); sb.Append (' '); sb.Append (FormatName (field.FieldType)); sb.Append (' '); sb.Append (field.Name); if (field.HasConstant) { sb.Append (" = "); sb.Append (Utils.FormatValue (field.Constant, field.FieldType)); } sb.AppendLine (";"); return sb.ToString (); }
public static string FormatAccessor(string name, MethodDefinition accessor, bool needsAttributes) { if (accessor == null || String.IsNullOrEmpty (name)) return String.Empty; var sb = new StringBuilder (); Utils.Indent++; try { sb.AppendLine (); if (accessor.HasCustomAttributes) sb.Append (accessor.CustomAttributes.Format ()); if (needsAttributes) { sb.AppendIndent (FormatAttributes (accessor)); sb.Append (' '); } else sb.AppendIndent (); sb.Append (name); bool needNewline = false; if (accessor.IsAbstract || accessor.DeclaringType.IsInterface || (needNewline = accessor.IsCompilerGenerated ())) { sb.Append (";"); } else sb.Append (" { throw new NotImplementedException (); }"); } finally { Utils.Indent--; } return sb.ToString (); }