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 ();
        }
        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 ();
        }
        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 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 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);
                }
            }
        }
Example #8
0
		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;
		}
Example #9
0
        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);
                }
            }
        }
        /// <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();
        }