System.Text.StringBuilder.AppendFormat(string, object, object)

Here are the examples of the csharp api System.Text.StringBuilder.AppendFormat(string, object, object) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1024 Examples 7

19 View Source File : StatisticService.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public object[] HostVisit(DateTime start, DateTime end, string user)
		{
			Debug.replacedert(!string.IsNullOrEmpty(user));
			StringBuilder filter = new StringBuilder();
			filter.AppendFormat(" '{0:yyyy-MM-dd}'<=SessionDate AND SessionDate<='{1:yyyy-MM-dd}' ", start, end);
			filter.AppendFormat(" AND Domain='{0}'", user.Contains(@"\") ? user.Split('\\')[0] : Environment.MachineName);
			filter.AppendFormat(" AND UserName='{0}'", user.Contains(@"\") ? user.Split('\\')[1] : user);
			filter.AppendFormat(" AND UrlHost NOT LIKE '_:'");

			var groups = Database.Execute(db => db.ReadObjects<SnapGroup>("StatisticView", filter.ToString(), null, 4,
					"Domain", "UserName", "SessionDate", "UrlHost", "Sum(SnapCount) AS SnapCount"));

			List<object> array = new List<object>();
			foreach (var g in groups)
			{
				if (string.IsNullOrEmpty(g.UrlHost))
					continue;
				array.Add(new
					{
						User = g.User,
						Date = g.SessionDate,
						Host = g.UrlHost,
						Count = g.SnapCount,
					});
			}
			return array.ToArray();
		}

19 View Source File : CSharpProperty.cs
License : GNU General Public License v3.0
Project Creator : alexgracianoarj

public string GetDeclarationLine(bool showAccessors)
		{
			StringBuilder builder = new StringBuilder(50);

			if (AccessModifier != AccessModifier.Default) {
				builder.Append(Language.GetAccessString(AccessModifier, true));
				builder.Append(" ");
			}

			if (IsHider)
				builder.Append("new ");
			if (IsStatic)
				builder.Append("static ");
			if (IsVirtual)
				builder.Append("virtual ");
			if (IsAbstract)
				builder.Append("abstract ");
			if (IsSealed)
				builder.Append("sealed ");
			if (IsOverride)
				builder.Append("override ");

			builder.AppendFormat("{0} {1}", Type, Name);

			if (HasParameter) {
				builder.Append("[");
				for (int i = 0; i < ArgumentList.Count; i++) {
					builder.Append(ArgumentList[i]);
					if (i < ArgumentList.Count - 1)
						builder.Append(", ");
				}
				builder.Append("]");
			}

			if (showAccessors) {
				builder.Append(" { ");
				if (!IsWriteonly) {
					if (ReadAccess != AccessModifier.Default) {
						builder.Append(Language.GetAccessString(ReadAccess, true));
						builder.Append(" get; ");
					}
					else {
						builder.Append("get; ");
					}
				}
				if (!IsReadonly) {
					if (WriteAccess != AccessModifier.Default) {
						builder.Append(Language.GetAccessString(WriteAccess, true));
						builder.Append(" set; ");
					}
					else {
						builder.Append("set; ");
					}
				}
				builder.Append("}");
			}

			return builder.ToString();
		}

19 View Source File : CollectionEx.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static string LinkToSql(this Dictionary<string, string> em)
        {
            if (em == null)
            {
                return null;
            }
            var sb = new StringBuilder();
            var first = true;
            foreach (var value in em)
            {
                if (first)
                {
                    first = false;
                }
                else
                {
                    sb.Append(',');
                }
                sb.AppendFormat("\r\n\t[{0}] = {1}", value.Key, value.Value);
            }
            return first ? null : sb.ToString();
        }

19 View Source File : DataQueryService.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public object[] SearchUrl(DateTime start, DateTime end, string user, string host, string url)
		{
			StringBuilder filter = new StringBuilder();
			filter.AppendFormat(" '{0:yyyy-MM-dd}'<=date(StartTime) AND date(StartTime)<='{1:yyyy-MM-dd}' ", start, end);
			if (!string.IsNullOrEmpty(user) && ValidUser(user))
			{
				var domainUser = DomainUser.Create(user);
				if (domainUser != null)
					filter.AppendFormat(" AND Domain='{0}' AND UserName='{1}'", domainUser.Domain, domainUser.UserName);
			}
			if (!string.IsNullOrEmpty(host) && ValidHost(host))
				filter.AppendFormat(" AND UrlHost='{0}' ", host);
			else
				filter.Append(@" AND UrlHost NOT LIKE '_:'");
			if (!string.IsNullOrEmpty(url) && ValidKey(url))
				filter.AppendFormat(" AND WindowUrl LIKE '%{0}%' ", url);

			var segments = Database.Execute(db => db.SelectObjects<SnapshotGroup>("SearchUrl", filter.ToString(),
				"SessionDate", "SessionId", "Domain", "UserName", "StartTime", "EndTime", "UrlHost", "WindowUrl", "SnapshotCount"));

			List<object> objs = new List<object>();
			foreach (var sg in segments)
				objs.Add(new
				{
					SID = sg.SID,
					Date = sg.SessionDate,
					User = sg.User,
					Host = sg.UrlHost,
					Time = sg.TimeRange,
					Url = sg.WindowUrl,
					Count = sg.SnapshotCount,
				});

			return objs.ToArray();
		}

19 View Source File : StringHelper.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static void AppendAttrib(this StringBuilder code, string name, bool value)
        {
            code.AppendFormat(@" {0}=""{1}""", name, value ? "True" : "False");
        }

19 View Source File : CalendarHandler.cs
License : MIT License
Project Creator : Adoxio

private static void AppendField(StringBuilder vevent, string name, string value)
			{
				if (string.IsNullOrEmpty(value))
				{
					return;
				}

				vevent.AppendFormat("{0}: {1}\r\n", name, value);
			}

19 View Source File : NameValueCollectionExtensions.cs
License : MIT License
Project Creator : albyho

public static string ToQueryString(this NameValueCollection queryString)
        {
            if (queryString.Count > 0)
            {
                var qs = new StringBuilder();
                qs.Append("?");
                for (var i = 0; i < queryString.Count; i++)
                {
                    if (i > 0)
                        qs.Append("&");

                    qs.AppendFormat("{0}={1}", queryString.Keys[i], queryString[i]);
                }
                return qs.ToString();
            }
            return String.Empty;
        }

19 View Source File : Helper.cs
License : MIT License
Project Creator : 5minlab

public void Append(string key, object value) {
            sb.AppendFormat("{0}={1}, ", key, value);
        }

19 View Source File : SvgWriter.cs
License : MIT License
Project Creator : AlexGyver

public string CreateStyle(
            OxyColor fill,
            OxyColor stroke,
            double thickness,
            double[] dashArray = null,
            OxyPenLineJoin lineJoin = OxyPenLineJoin.Miter)
        {
            // http://oreilly.com/catalog/svgess/chapter/ch03.html
            var style = new StringBuilder();
            if (fill == null)
            {
                style.AppendFormat("fill:none;");
            }
            else
            {
                style.AppendFormat("fill:{0};", this.ColorToString(fill));
                if (fill.A != 0xFF)
                {
                    style.AppendFormat(CultureInfo.InvariantCulture, "fill-opacity:{0};", fill.A / 255.0);
                }
            }

            if (stroke == null)
            {
                style.AppendFormat("stroke:none;");
            }
            else
            {
                string formatString = "stroke:{0};stroke-width:{1:" + this.NumberFormat + "}";
                style.AppendFormat(formatString, this.ColorToString(stroke), thickness);
                switch (lineJoin)
                {
                    case OxyPenLineJoin.Round:
                        style.AppendFormat(";stroke-linejoin:round");
                        break;
                    case OxyPenLineJoin.Bevel:
                        style.AppendFormat(";stroke-linejoin:bevel");
                        break;
                }

                if (stroke.A != 0xFF)
                {
                    style.AppendFormat(CultureInfo.InvariantCulture, ";stroke-opacity:{0}", stroke.A / 255.0);
                }

                if (dashArray != null && dashArray.Length > 0)
                {
                    style.Append(";stroke-dasharray:");
                    for (int i = 0; i < dashArray.Length; i++)
                    {
                        style.AppendFormat(
                            CultureInfo.InvariantCulture, "{0}{1}", i > 0 ? "," : string.Empty, dashArray[i]);
                    }
                }
            }

            return style.ToString();
        }

19 View Source File : WexApi.cs
License : MIT License
Project Creator : aabiryukov

static string BuildPostData(NameValueDictionary d)
        {
            var s = new StringBuilder();
            foreach (var key in d.Keys)
            {
	            var value = d[key];
				s.AppendFormat("{0}={1}", key, WebUtility.UrlEncode(value));
                s.Append("&");
            }
            if (s.Length > 0) s.Remove(s.Length - 1, 1);
            return s.ToString();
        }

19 View Source File : DataQueryService.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public object[] Searchreplacedle(DateTime start, DateTime end, string user, string prog, string replacedle)
		{
			StringBuilder filter = new StringBuilder();
			filter.AppendFormat(" '{0:yyyy-MM-dd}'<=date(StartTime) AND date(StartTime)<='{1:yyyy-MM-dd}' ", start, end);
			if (!string.IsNullOrEmpty(user) && ValidUser(user))
			{
				var domainUser = DomainUser.Create(user);
				if (domainUser != null)
					filter.AppendFormat(" AND Domain='{0}' AND UserName='{1}'", domainUser.Domain, domainUser.UserName);
			}
			if (!string.IsNullOrEmpty(prog) && ValidProgram(prog))
				filter.AppendFormat(" AND ProcessName='{0}' ", prog);
			if (!string.IsNullOrEmpty(replacedle) && ValidKey(replacedle))
				filter.AppendFormat(" AND Windowreplacedle LIKE '%{0}%' ", replacedle);

			var segments = Database.Execute(db => db.SelectObjects<SnapshotGroup>("Searchreplacedle", filter.ToString(),
				"SessionDate", "SessionId", "Domain", "UserName", "ProcessName", "Windowreplacedle", "StartTime", "EndTime", "SnapshotCount"));

			List<object> objs = new List<object>();
			foreach (var sg in segments)
				objs.Add(new
				{
					Date = sg.SessionDate,
					User = sg.User,
					Prog = sg.ProcessName,
					replacedle = sg.Windowreplacedle,
					SID = sg.SessionId,
					Time = sg.TimeRange,
					Count = sg.SnapshotCount,
				});
			return objs.ToArray();
		}

19 View Source File : DiagnosticVerifier.cs
License : Apache License 2.0
Project Creator : agoda-com

private static string FormatDiagnostics(ImmutableArray<Diagnosticreplacedyzer> replacedyzers, params Diagnostic[] diagnostics)
        {
            var builder = new StringBuilder();
            for (var i = 0; i < diagnostics.Length; ++i)
            {
                var diagnosticsId = diagnostics[i].Id;

                builder.Append("// ").AppendLine(diagnostics[i].ToString());

                var applicablereplacedyzer = replacedyzers.FirstOrDefault(a => a.SupportedDiagnostics.Any(dd => dd.Id == diagnosticsId));
                if (applicablereplacedyzer != null)
                {
                    var replacedyzerType = applicablereplacedyzer.GetType();

                    var location = diagnostics[i].Location;
                    if (location == Location.None)
                    {
                        builder.AppendFormat("GetGlobalResult({0}.{1})", replacedyzerType.Name, diagnosticsId);
                    }
                    else
                    {
                        replacedert.True(
                            location.IsInSource,
                            string.Format("Test base does not currently handle diagnostics in metadata locations. Diagnostic in metadata:\r\n{0}", diagnostics[i]));

                        var resultMethodName = diagnostics[i].Location.SourceTree.FilePath.EndsWith(".cs") ? "GetCSharpResultAt" : "GetBasicResultAt";
                        var linePosition = diagnostics[i].Location.GetLineSpan().StartLinePosition;

                        builder.AppendFormat(
                            "{0}({1}, {2}, {3}.{4})",
                            resultMethodName,
                            linePosition.Line + 1,
                            linePosition.Character + 1,
                            replacedyzerType.Name,
                            diagnosticsId);
                    }

                    if (i != diagnostics.Length - 1)
                    {
                        builder.Append(',');
                    }

                    builder.AppendLine();
                }
            }

            return builder.ToString();
        }

19 View Source File : HttpUtility.cs
License : MIT License
Project Creator : adamfisher

public override string ToString()
            {
                int count = Count;
                if (count == 0)
                    return "";
                StringBuilder sb = new StringBuilder();
                var keys = this.Keys;
                foreach (var key in this.Keys)
                {
                    sb.AppendFormat("{0}={1}&", key, this[key]);
                }
                if (sb.Length > 0)
                    sb.Length--;
                return sb.ToString();
            }

19 View Source File : DatabaseEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal

private void DumpException(Exception ex, string sql, params object[] pramsArray)
		{
			StringBuilder sb = new StringBuilder();
			if (pramsArray != null)
			{
				foreach (object prams in pramsArray)
				{
					if (prams != null)
					{
						System.Reflection.PropertyInfo[] props = prams.GetType().GetProperties();
						foreach (var p in props)
							sb.AppendFormat("{0} = {1},", p.Name, p.GetValue(prams, null));
					}
				}
			}
			TraceLog.WriteLineError(string.Format(
@"Exception at DatabaseEngine.
sql : {0}
parameters : {1}
exception : {2}", sql, sb.ToString(), ex.Message));
			TraceLog.WriteException(ex);
		}

19 View Source File : SqlServerDbAdapter.cs
License : MIT License
Project Creator : 17MKH

public override string GeneratePagingSql(string select, string table, string where, string sort, int skip, int take, string groupBy = null, string having = null)
    {
        if (sort.IsNull())
        {
            if (groupBy.IsNull())
                sort = " ORDER BY [Id] ASC";
            else
            {
                throw new ArgumentException("SqlServer分组分页查询需要指定排序规则");
            }
        }

        var sqlBuilder = new StringBuilder();
        if (IsHighVersion)
        {
            #region ==2012+版本==

            sqlBuilder.AppendFormat("SELECT {0} FROM {1}", select, table);

            if (where.NotNull())
                sqlBuilder.AppendFormat(" {0}", where);

            if (groupBy.NotNull())
                sqlBuilder.Append(groupBy);

            if (having.NotNull())
                sqlBuilder.Append(having);

            sqlBuilder.AppendFormat("{0} OFFSET {1} ROW FETCH NEXT {2} ROW ONLY", sort, skip, take);

            #endregion
        }
        else
        {
            #region ==2012以下版本==

            sqlBuilder.AppendFormat("SELECT * FROM (SELECT ROW_NUMBER() OVER({0}) AS RowNum,{1} FROM {2}", sort, select, table);
            if (!string.IsNullOrWhiteSpace(where))
                sqlBuilder.AppendFormat(" WHERE {0}", where);

            sqlBuilder.AppendFormat(") AS T WHERE T.RowNum BETWEEN {0} AND {1}", skip + 1, skip + take);

            #endregion
        }

        return sqlBuilder.ToString();
    }

19 View Source File : StatisticService.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public object[] ComputerUsage(DateTime start, DateTime end, string user)
		{
			Debug.replacedert(!string.IsNullOrEmpty(user));
			StringBuilder filter = new StringBuilder();
			filter.AppendFormat(" '{0:yyyy-MM-dd}'<=SnapDate AND SnapDate<='{1:yyyy-MM-dd}' ", start, end);
			filter.AppendFormat(" AND Domain='{0}'", user.Contains(@"\") ? user.Split('\\')[0] : Environment.MachineName);
			filter.AppendFormat(" AND UserName='{0}'", user.Contains(@"\") ? user.Split('\\')[1] : user);

			var groups = Database.Execute(db=>db.ReadObjects<SnapGroup>("HoursView", filter.ToString(), "SnapHour", 4,
				"Domain", "UserName", "SnapDate AS SessionDate", "SnapHour", "Sum(SnapCount) AS SnapCount"));

			List<object> array = new List<object>();
			foreach (var g in groups)
				array.Add(new
				{
					User = g.User,
					Date = g.SessionDate,
					Hour = g.SnapHour,
					Count = g.SnapCount,
				});
			return array.ToArray();
		}

19 View Source File : SqliteTable.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public string JoinConditionSQL(bool isAnd, params string[] conditions)
        {
            if (conditions == null || conditions.Length == 0)
            {
                throw new ArgumentException(@"没有条件用于组合", "conditions");
            }
            var sql = new StringBuilder();
            sql.AppendFormat(@"({0})", conditions[0]);
            for (var idx = 1; idx < conditions.Length; idx++)
            {
                sql.AppendFormat(@" {0} ({1}) ", isAnd ? "AND" : "OR", conditions[idx]);
            }
            return sql.ToString();
        }

19 View Source File : CSharpEvent.cs
License : GNU General Public License v3.0
Project Creator : alexgracianoarj

public string GetDeclarationLine(bool withSemicolon)
		{
			StringBuilder builder = new StringBuilder(50);

			if (AccessModifier != AccessModifier.Default) {
				builder.Append(Language.GetAccessString(AccessModifier, true));
				builder.Append(" ");
			}
			
			if (IsHider)
				builder.Append("new ");
			if (IsStatic)
				builder.Append("static ");
			if (IsVirtual)
				builder.Append("virtual ");
			if (IsAbstract)
				builder.Append("abstract ");
			if (IsSealed)
				builder.Append("sealed ");
			if (IsOverride)
				builder.Append("override ");

			builder.AppendFormat("event {0} {1}", Type, Name);

			if (withSemicolon && !HasBody)
				builder.Append(";");

			return builder.ToString();
		}

19 View Source File : UriExtensions.cs
License : MIT License
Project Creator : 13xforever

public static string FormatUriParams(NameValueCollection parameters)
        {
            if (parameters == null || parameters.Count == 0)
                return "";

            var result = new StringBuilder();
            foreach (var key in parameters.AllKeys)
            {
                var value = parameters[key];
                if (value == null)
                    continue;

                result.AppendFormat("&{0}={1}", Uri.EscapeDataString(key), Uri.EscapeDataString(value));
            }
            if (result.Length == 0)
                return "";
            return result.ToString(1, result.Length - 1);
        }

19 View Source File : NvidiaGPU.cs
License : MIT License
Project Creator : AlexGyver

public override string GetReport() {
      StringBuilder r = new StringBuilder();

      r.AppendLine("Nvidia GPU");
      r.AppendLine();

      r.AppendFormat("Name: {0}{1}", name, Environment.NewLine);
      r.AppendFormat("Index: {0}{1}", adapterIndex, Environment.NewLine);

      if (displayHandle.HasValue && NVAPI.NvAPI_GetDisplayDriverVersion != null) {
        NvDisplayDriverVersion driverVersion = new NvDisplayDriverVersion();
        driverVersion.Version = NVAPI.DISPLAY_DRIVER_VERSION_VER;
        if (NVAPI.NvAPI_GetDisplayDriverVersion(displayHandle.Value,
          ref driverVersion) == NvStatus.OK) {
          r.Append("Driver Version: ");
          r.Append(driverVersion.DriverVersion / 100);
          r.Append(".");
          r.Append((driverVersion.DriverVersion % 100).ToString("00",
            CultureInfo.InvariantCulture));
          r.AppendLine();
          r.Append("Driver Branch: ");
          r.AppendLine(driverVersion.BuildBranch);
        }
      }
      r.AppendLine();

      if (NVAPI.NvAPI_GPU_GetPCIIdentifiers != null) {
        uint deviceId, subSystemId, revisionId, extDeviceId;

        NvStatus status = NVAPI.NvAPI_GPU_GetPCIIdentifiers(handle, 
          out deviceId, out subSystemId, out revisionId, out extDeviceId);

        if (status == NvStatus.OK) {
          r.Append("DeviceID: 0x");
          r.AppendLine(deviceId.ToString("X", CultureInfo.InvariantCulture));
          r.Append("SubSystemID: 0x");
          r.AppendLine(subSystemId.ToString("X", CultureInfo.InvariantCulture));
          r.Append("RevisionID: 0x");
          r.AppendLine(revisionId.ToString("X", CultureInfo.InvariantCulture));
          r.Append("ExtDeviceID: 0x");
          r.AppendLine(extDeviceId.ToString("X", CultureInfo.InvariantCulture));
          r.AppendLine();
        }
      }

      if (NVAPI.NvAPI_GPU_GetThermalSettings != null) {
        NvGPUThermalSettings settings = new NvGPUThermalSettings();
        settings.Version = NVAPI.GPU_THERMAL_SETTINGS_VER;
        settings.Count = NVAPI.MAX_THERMAL_SENSORS_PER_GPU;
        settings.Sensor = new NvSensor[NVAPI.MAX_THERMAL_SENSORS_PER_GPU];

        NvStatus status = NVAPI.NvAPI_GPU_GetThermalSettings(handle,
          (int)NvThermalTarget.ALL, ref settings);

        r.AppendLine("Thermal Settings");
        r.AppendLine();
        if (status == NvStatus.OK) {
          for (int i = 0; i < settings.Count; i++) {
            r.AppendFormat(" Sensor[{0}].Controller: {1}{2}", i,
              settings.Sensor[i].Controller, Environment.NewLine);
            r.AppendFormat(" Sensor[{0}].DefaultMinTemp: {1}{2}", i,
              settings.Sensor[i].DefaultMinTemp, Environment.NewLine);
            r.AppendFormat(" Sensor[{0}].DefaultMaxTemp: {1}{2}", i,
              settings.Sensor[i].DefaultMaxTemp, Environment.NewLine);
            r.AppendFormat(" Sensor[{0}].CurrentTemp: {1}{2}", i,
              settings.Sensor[i].CurrentTemp, Environment.NewLine);
            r.AppendFormat(" Sensor[{0}].Target: {1}{2}", i,
              settings.Sensor[i].Target, Environment.NewLine);
          }
        } else {
          r.Append(" Status: ");
          r.AppendLine(status.ToString());
        }
        r.AppendLine();
      }

      if (NVAPI.NvAPI_GPU_GetAllClocks != null) {
        NvClocks allClocks = new NvClocks();
        allClocks.Version = NVAPI.GPU_CLOCKS_VER;
        allClocks.Clock = new uint[NVAPI.MAX_CLOCKS_PER_GPU];
        NvStatus status = NVAPI.NvAPI_GPU_GetAllClocks(handle, ref allClocks);

        r.AppendLine("Clocks");
        r.AppendLine();
        if (status == NvStatus.OK) {
          for (int i = 0; i < allClocks.Clock.Length; i++)
            if (allClocks.Clock[i] > 0) {
              r.AppendFormat(" Clock[{0}]: {1}{2}", i, allClocks.Clock[i],
                Environment.NewLine);
            }
        } else {
          r.Append(" Status: ");
          r.AppendLine(status.ToString());
        }
        r.AppendLine();
      }

      if (NVAPI.NvAPI_GPU_GetTachReading != null) {
        int tachValue;
        NvStatus status = NVAPI.NvAPI_GPU_GetTachReading(handle, out tachValue);

        r.AppendLine("Tachometer");
        r.AppendLine();
        if (status == NvStatus.OK) {
          r.AppendFormat(" Value: {0}{1}", tachValue, Environment.NewLine);
        } else {
          r.Append(" Status: ");
          r.AppendLine(status.ToString());
        }
        r.AppendLine();
      }

      if (NVAPI.NvAPI_GPU_GetPStates != null) {
        NvPStates states = new NvPStates();
        states.Version = NVAPI.GPU_PSTATES_VER;
        states.PStates = new NvPState[NVAPI.MAX_PSTATES_PER_GPU];
        NvStatus status = NVAPI.NvAPI_GPU_GetPStates(handle, ref states);

        r.AppendLine("P-States");
        r.AppendLine();
        if (status == NvStatus.OK) {
          for (int i = 0; i < states.PStates.Length; i++)
            if (states.PStates[i].Present)
              r.AppendFormat(" Percentage[{0}]: {1}{2}", i,
                states.PStates[i].Percentage, Environment.NewLine);
        } else {
          r.Append(" Status: ");
          r.AppendLine(status.ToString());
        }
        r.AppendLine();
      }

      if (NVAPI.NvAPI_GPU_GetUsages != null) {
        NvUsages usages = new NvUsages();
        usages.Version = NVAPI.GPU_USAGES_VER;
        usages.Usage = new uint[NVAPI.MAX_USAGES_PER_GPU];
        NvStatus status = NVAPI.NvAPI_GPU_GetUsages(handle, ref usages);

        r.AppendLine("Usages");
        r.AppendLine();
        if (status == NvStatus.OK) {
          for (int i = 0; i < usages.Usage.Length; i++)
            if (usages.Usage[i] > 0)
              r.AppendFormat(" Usage[{0}]: {1}{2}", i,
                usages.Usage[i], Environment.NewLine);
        } else {
          r.Append(" Status: ");
          r.AppendLine(status.ToString());
        }
        r.AppendLine();
      }

      if (NVAPI.NvAPI_GPU_GetCoolerSettings != null) {
        NvGPUCoolerSettings settings = new NvGPUCoolerSettings();
        settings.Version = NVAPI.GPU_COOLER_SETTINGS_VER;
        settings.Cooler = new NvCooler[NVAPI.MAX_COOLER_PER_GPU];
        NvStatus status =
          NVAPI.NvAPI_GPU_GetCoolerSettings(handle, 0, ref settings);

        r.AppendLine("Cooler Settings");
        r.AppendLine();
        if (status == NvStatus.OK) {
          for (int i = 0; i < settings.Count; i++) {
            r.AppendFormat(" Cooler[{0}].Type: {1}{2}", i,
              settings.Cooler[i].Type, Environment.NewLine);
            r.AppendFormat(" Cooler[{0}].Controller: {1}{2}", i,
              settings.Cooler[i].Controller, Environment.NewLine);
            r.AppendFormat(" Cooler[{0}].DefaultMin: {1}{2}", i,
              settings.Cooler[i].DefaultMin, Environment.NewLine);
            r.AppendFormat(" Cooler[{0}].DefaultMax: {1}{2}", i,
              settings.Cooler[i].DefaultMax, Environment.NewLine);
            r.AppendFormat(" Cooler[{0}].CurrentMin: {1}{2}", i,
              settings.Cooler[i].CurrentMin, Environment.NewLine);
            r.AppendFormat(" Cooler[{0}].CurrentMax: {1}{2}", i,
              settings.Cooler[i].CurrentMax, Environment.NewLine);
            r.AppendFormat(" Cooler[{0}].CurrentLevel: {1}{2}", i,
              settings.Cooler[i].CurrentLevel, Environment.NewLine);
            r.AppendFormat(" Cooler[{0}].DefaultPolicy: {1}{2}", i,
              settings.Cooler[i].DefaultPolicy, Environment.NewLine);
            r.AppendFormat(" Cooler[{0}].CurrentPolicy: {1}{2}", i,
              settings.Cooler[i].CurrentPolicy, Environment.NewLine);
            r.AppendFormat(" Cooler[{0}].Target: {1}{2}", i,
              settings.Cooler[i].Target, Environment.NewLine);
            r.AppendFormat(" Cooler[{0}].ControlType: {1}{2}", i,
              settings.Cooler[i].ControlType, Environment.NewLine);
            r.AppendFormat(" Cooler[{0}].Active: {1}{2}", i,
              settings.Cooler[i].Active, Environment.NewLine);
          }
        } else {
          r.Append(" Status: ");
          r.AppendLine(status.ToString());
        }
        r.AppendLine();
      }

      if (NVAPI.NvAPI_GPU_GetMemoryInfo != null && displayHandle.HasValue) {
        NvMemoryInfo memoryInfo = new NvMemoryInfo();
        memoryInfo.Version = NVAPI.GPU_MEMORY_INFO_VER;
        memoryInfo.Values = new uint[NVAPI.MAX_MEMORY_VALUES_PER_GPU];
        NvStatus status = NVAPI.NvAPI_GPU_GetMemoryInfo(displayHandle.Value,
          ref memoryInfo);

        r.AppendLine("Memory Info");
        r.AppendLine();
        if (status == NvStatus.OK) {
          for (int i = 0; i < memoryInfo.Values.Length; i++)
            r.AppendFormat(" Value[{0}]: {1}{2}", i,
                memoryInfo.Values[i], Environment.NewLine);
        } else {
          r.Append(" Status: ");
          r.AppendLine(status.ToString());
        }
        r.AppendLine();
      }

      return r.ToString();
    }

19 View Source File : MulitStringDictionary.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public override string ToString()
        {
            var sb = new StringBuilder() ;
            if(_global.Count > 0)
            {
                sb.AppendFormat("〖{0}〗" , Global) ;
            }
            foreach(var name in Keys)
            {
                if(base[name].Count > 0)
                {
                    sb.AppendFormat("{0}:{1}" , name , this[name]) ;
                }
            }
            return sb.ToString() ;
        }

19 View Source File : StringHelper.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static void AppendAttrib(this StringBuilder code, string name, object value)
        {
            if (value != null)
                code.AppendFormat(@" {0}=""{1}""", name, value);
        }

19 View Source File : DefaultCacheKeyBuilder.cs
License : MIT License
Project Creator : 1100100

public string Generate(string sql, object param, string customKey, int? pageIndex = default, int? pageSize = default)
        {
            if (!string.IsNullOrWhiteSpace(customKey))
                return $"{CacheConfiguration.KeyPrefix}{(string.IsNullOrWhiteSpace(CacheConfiguration.KeyPrefix) ? "" : ":")}{customKey}";

            if (string.IsNullOrWhiteSpace(sql))
                throw new ArgumentNullException(nameof(sql));

            var builder = new StringBuilder();
            builder.AppendFormat("{0}:", sql);

            if (param == null)
                return $"{CacheConfiguration.KeyPrefix}{(string.IsNullOrWhiteSpace(CacheConfiguration.KeyPrefix) ? "" : ":")}{HashCacheKey(builder.ToString().TrimEnd(':'))}";

            var prop = GetProperties(param);
            foreach (var item in prop)
            {
                builder.AppendFormat("{0}={1}&", item.Name, item.GetValue(param));
            }
            if (pageIndex.HasValue)
            {
                builder.AppendFormat("pageindex={0}&", pageIndex.Value);
            }
            if (pageSize.HasValue)
            {
                builder.AppendFormat("pagesize={0}&", pageSize.Value);
            }
            return $"{CacheConfiguration.KeyPrefix}{(string.IsNullOrWhiteSpace(CacheConfiguration.KeyPrefix) ? "" : ":")}{HashCacheKey(builder.ToString().TrimEnd('&'))}";
        }

19 View Source File : MySqlTable.sql.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public string FieldConditionSQL(bool isAnd, params string[] fields)
        {
            if (fields == null || fields.Length == 0)
                throw new ArgumentException(@"û���ֶ����������������", nameof(fields));
            var sql = new StringBuilder();
            sql.AppendFormat(@"({0})", FieldConditionSQL(fields[0]));
            for (var idx = 1; idx < fields.Length; idx++)
                sql.AppendFormat(@" {0} ({1}) ", isAnd ? "AND" : "OR", FieldConditionSQL(fields[idx]));
            return sql.ToString();
        }

19 View Source File : MixedRealityToolkitVisualProfiler.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

private void BuildFrameRateStrings()
        {
            cpuFrameRateStrings = new string[maxTargetFrameRate + 1];
            gpuFrameRateStrings = new string[maxTargetFrameRate + 1];
            string displayedDecimalFormat = string.Format("{{0:F{0}}}", displayedDecimalDigits);

            StringBuilder stringBuilder = new StringBuilder(32);
            StringBuilder milisecondStringBuilder = new StringBuilder(16);

            for (int i = 0; i < cpuFrameRateStrings.Length; ++i)
            {
                float miliseconds = (i == 0) ? 0.0f : (1.0f / i) * 1000.0f;
                milisecondStringBuilder.AppendFormat(displayedDecimalFormat, miliseconds);
                stringBuilder.AppendFormat("CPU: {0} fps ({1} ms)", i.ToString(), milisecondStringBuilder.ToString());
                cpuFrameRateStrings[i] = stringBuilder.ToString();
                stringBuilder.Length = 0;
                stringBuilder.AppendFormat("GPU: {0} fps ({1} ms)", i.ToString(), milisecondStringBuilder.ToString());
                gpuFrameRateStrings[i] = stringBuilder.ToString();
                milisecondStringBuilder.Length = 0;
                stringBuilder.Length = 0;
            }
        }

19 View Source File : JsonServiceScript.cs
License : GNU General Public License v3.0
Project Creator : aiportal

private string GenerateFunctions()
		{
			///? exclude parameters of RawRequestAttribute, RawResponseAttribute, RawParametersAttribute
			StringBuilder sb = new StringBuilder();
			var ms = _svc.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
			foreach(MethodInfo mi in ms)
			{
				sb.AppendFormat(@"this.{0} = function (p, onResult, onError) {{ return this.implement('{0}', p, onResult, onError); }};", mi.Name);
				sb.AppendLine();
			
				var ps = new List<string>();
				foreach (var p in mi.GetParameters())
					ps.Add(p.Name + ":''");
				sb.AppendFormat(@"this.{0}.params = {{ {1} }};", mi.Name, string.Join(",", ps.ToArray()));
				sb.AppendLine();
			}
			return sb.ToString();
		}

19 View Source File : HyperTextExport.cs
License : GNU General Public License v3.0
Project Creator : ahmed605

private static string GetAttributes(HtmlNode node)
        {
            Dictionary<string, string> attributes = new Dictionary<string, string>();
            Dictionary<string, string> styleAttributes = new Dictionary<string, string>();

            HtmlRenderState state = node.RenderState;

            if (node.Tag == HtmlTag.Html || node.Tag == HtmlTag.Head ||
                    node.Tag == HtmlTag.replacedle || node.Tag == HtmlTag.Style)
            {
                return "";
            }

            // Write out style attributes
            if (state.HasBackground == 1)
            {
                if (state.BackgroundImageOffset == 0)
                {
                    styleAttributes.Add("background-color", GetColor(state.BackgroundColor));
                }
                else
                {
                    styleAttributes.Add("background-image", "url(" + state.BackgroundImageTextureInfo.TextureName + ".png)");
                    styleAttributes.Add("background-repeat", GetAttributeValue(state.BackgroundRepeat));
                }
            }
            if (state.Width > -1)
            {
                if (node.NodeType == HtmlNodeType.HtmlTableNode || node.NodeType == HtmlNodeType.HtmlTableElementNode)
                {
                    attributes.Add("width", state.Width.ToString());
                }
                else
                {
                    styleAttributes.Add("width", GetSize(state.Width));
                }
            }
            if (state.Height > -1)
            {
                if (node.NodeType == HtmlNodeType.HtmlTableNode || node.NodeType == HtmlNodeType.HtmlTableElementNode)
                {
                    attributes.Add("height", state.Height.ToString());
                }
                else
                {
                    styleAttributes.Add("height", GetSize(state.Height));
                }
            }

            styleAttributes.Add("margin-left", GetSize(state.MarginLeft));
            styleAttributes.Add("margin-right", GetSize(state.MarginRight));
            styleAttributes.Add("margin-top", GetSize(state.MarginTop));
            styleAttributes.Add("margin-bottom", GetSize(state.MarginBottom));

            styleAttributes.Add("padding-left", GetSize(state.PaddingLeft));
            styleAttributes.Add("padding-right", GetSize(state.PaddingRight));
            styleAttributes.Add("padding-top", GetSize(state.PaddingTop));
            styleAttributes.Add("padding-bottom", GetSize(state.PaddingBottom));

            styleAttributes.Add("border-left", GetAttributeValue(state.BorderLeftStyle) + " " + GetSize(state.BorderLeftWidth) + " " + GetColor(state.BorderLeftColor));
            styleAttributes.Add("border-right", GetAttributeValue(state.BorderRightStyle) + " " + GetSize(state.BorderRightWidth) + " " + GetColor(state.BorderRightColor));
            styleAttributes.Add("border-top", GetAttributeValue(state.BorderTopStyle) + " " + GetSize(state.BorderTopWidth) + " " + GetColor(state.BorderTopColor));
            styleAttributes.Add("border-bottom", GetAttributeValue(state.BorderBottomStyle) + " " + GetSize(state.BorderBottomWidth) + " " + GetColor(state.BorderBottomColor));

            styleAttributes.Add("text-decoration", GetAttributeValue(state.TextDecoration));
            styleAttributes.Add("font-size", GetAttributeValue(state.FontSize));
            styleAttributes.Add("display", GetAttributeValue(state.Display));
            styleAttributes.Add("color", GetColor(state.Color));

            if (node.NodeType == HtmlNodeType.HtmlTableNode)
            {
                attributes.Add("cellpadding", state.CellPadding.ToString());
                attributes.Add("cellspacing", state.CellSpacing.ToString());
            }
            else if (node.NodeType == HtmlNodeType.HtmlTableElementNode)
            {
                if (state.ColSpan > 1)
                {
                    attributes.Add("colspan", state.ColSpan.ToString());                    
                }
                if (state.RowSpan > 1)
                {
                    attributes.Add("rowspan", state.RowSpan.ToString());
                }

                if ((int)state.VerticalAlign > -1)
                {
                    attributes.Add("valign", GetAttributeValue(state.VerticalAlign));
                }
                if ((int)state.HorizontalAlign > -1)
                {
                    attributes.Add("align", GetAttributeValue(state.HorizontalAlign));
                }
            }
            else
            {
                if ((int)state.VerticalAlign > -1)
                {
                    styleAttributes.Add("vertical-align", GetAttributeValue(state.VerticalAlign));
                }
                if ((int)state.HorizontalAlign > -1)
                {
                    styleAttributes.Add("text-align", GetAttributeValue(state.HorizontalAlign));
                }
            }
            
            if (node.Tag == HtmlTag.A)
            {
                attributes.Add("href", "#");
                attributes.Add("onclick", "alert('Link to: " + node.LinkAddress + "');");
            }
            else if (node.Tag == HtmlTag.Img)
            {
                string path = node.LinkAddress;
                path = path.Substring(0, path.Length - Path.GetExtension(path).Length);
                attributes.Add("src", path + ".png");
            }
            
            if (styleAttributes.Count > 0)
            {
                StringBuilder sbStyle = new StringBuilder();
                foreach (var pair in styleAttributes)
                {
                    sbStyle.AppendFormat("{0}: {1}; ", pair.Key, pair.Value);
                }
                attributes.Add("style", sbStyle.ToString());
            }

            StringBuilder sbAttributes = new StringBuilder();
            foreach (var pair in attributes)
            {
                sbAttributes.AppendFormat(" {0}=\"{1}\"", pair.Key, pair.Value);
            }

            return sbAttributes.ToString();
        }

19 View Source File : MainControl.xaml.cs
License : MIT License
Project Creator : Actipro

private void UpdateHitTestInfo(IHitTestResult result) {
			StringBuilder text = new StringBuilder();

			if (result != null) {
				text.AppendFormat("Snapshot version {0}{1}", result.Snapshot.Version.Number, Environment.NewLine);

				if (result.View != null)
					text.AppendFormat("Over '{0}' view{1}", this.GetPlacementName(result.View), Environment.NewLine);

				switch (result.Type) {
					case HitTestResultType.Splitter: {
						EditorViewSplitter splitter = result.VisualElement as EditorViewSplitter;
						if (splitter != null)
							text.AppendLine("Over view splitter");
						break;
					}
					case HitTestResultType.ViewMargin:
						text.AppendFormat("Over '{0}' margin{1}", result.ViewMargin.Key, Environment.NewLine);
						text.AppendFormat("Closest text position is ({0},{1}){2}", result.Position.Line, result.Position.Character, Environment.NewLine);
						break;
					case HitTestResultType.ViewScrollBar: {
						System.Windows.Controls.Primitives.ScrollBar scrollBar = result.VisualElement as System.Windows.Controls.Primitives.ScrollBar;
						if (scrollBar != null)
							text.AppendFormat("Over '{0}' scrollbar{1}", scrollBar.Orientation, Environment.NewLine);
						break;
					}
					case HitTestResultType.ViewScrollBarBlock:
						text.AppendLine("Over scroll bar block");
						break;
					case HitTestResultType.ViewScrollBarSplitter: {
						ScrollBarSplitter splitter = result.VisualElement as ScrollBarSplitter;
						if (splitter != null)
							text.AppendLine("Over scroll bar splitter");
						break;
					}
					case HitTestResultType.ViewScrollBarTray:
						text.AppendLine("Over scroll bar tray (that can contain other controls like buttons)");
						break;
					case HitTestResultType.ViewTextArea:
						text.AppendFormat("Not directly over any view line or character{0}", Environment.NewLine);
						text.AppendFormat("Closest text position is ({0},{1}){2}", result.Position.Line, result.Position.Character, Environment.NewLine);
						break;
					case HitTestResultType.ViewTextAreaOverCharacter: {
						ITextSnapshotReader reader = result.GetReader();
						text.AppendFormat("Directly over offset {0} and text position ({1},{2}){3}", result.Offset, result.Position.Line, result.Position.Character, Environment.NewLine);
						text.AppendFormat("Directly over character '{0}'{1}", reader.Character, Environment.NewLine);
						
						IToken token = reader.Token;
						if (token != null) {
							text.AppendFormat("Directly over token '{0}' with range ({1},{2})-({3},{4}){5}", token.Key, 
								token.StartPosition.Line, token.StartPosition.Character, 
								token.EndPosition.Line, token.EndPosition.Character, Environment.NewLine);
							text.AppendFormat("Directly over token text '{0}'{1}", reader.TokenText, Environment.NewLine);
						}
						break;
					}
					case HitTestResultType.ViewTextAreaOverIntraTextSpacer:
						text.AppendFormat("Over spacer '{0}' on doreplacedent line {1}{2}", result.IntraTextSpacerTag, result.Position.Line, Environment.NewLine);
						break;
					case HitTestResultType.ViewTextAreaOverLine:
						text.AppendFormat("Over whitespace at the end of doreplacedent line {0}{1}", result.Position.Line, Environment.NewLine);
						break;
					default:
						if (result.VisualElement != null)
							text.AppendFormat("Over a '{0}' element{1}", result.VisualElement.GetType().FullName, Environment.NewLine);
						else
							text.AppendLine("No other hit test details available");
						break;
				}
			}
			else {
				text.AppendLine("Not over the SyntaxEditor");
			}

			resultsTextBox.Text = text.ToString();
		}

19 View Source File : DataQueryService.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public object[] SearchText(DateTime start, DateTime end, string user, string prog, string text)
		{
			StringBuilder filter = new StringBuilder();
			filter.AppendFormat(" '{0:yyyy-MM-dd}'<=date(StartTime) AND date(StartTime)<='{1:yyyy-MM-dd}' ", start, end);
			filter.Append(" AND length(trim(InputText)) > 0 ");
			if (!string.IsNullOrEmpty(user) && ValidUser(user))
			{
				var domainUser = DomainUser.Create(user);
				if (domainUser != null)
					filter.AppendFormat(" AND Domain='{0}' AND UserName='{1}'", domainUser.Domain, domainUser.UserName);
			}
			if (!string.IsNullOrEmpty(prog) && ValidProgram(prog))
				filter.AppendFormat(" AND ProcessName='{0}' ", prog);
			if (!string.IsNullOrEmpty(text) && ValidKey(text))
				filter.AppendFormat(" AND InputText LIKE '%{0}%' ", text);

			var segments = Database.Execute(db => db.SelectObjects<SnapshotGroup>("SearchText", filter.ToString(),
				"SessionDate", "SessionId", "Domain", "UserName", "ProcessName", "Windowreplacedle", "StartTime", "EndTime", "InputText", "SnapshotCount"));

			List<object> objs = new List<object>();
			foreach (var sg in segments)
				objs.Add(new
				{
					Date = sg.SessionDate,
					User = sg.User,
					Prog = sg.ProcessName,
					replacedle = sg.Windowreplacedle,
					Text = sg.Text,
					SID = sg.SessionId,
					Time = sg.TimeRange,
					Count = sg.SnapshotCount,
				});
			return objs.ToArray();
		}

19 View Source File : SqliteDbAdapter.cs
License : MIT License
Project Creator : 17MKH

public override string GeneratePagingSql(string select, string table, string where, string sort, int skip, int take, string groupBy = null, string having = null)
    {
        var sqlBuilder = new StringBuilder();
        sqlBuilder.AppendFormat("SELECT {0} FROM {1}", select, table);
        if (where.NotNull())
            sqlBuilder.AppendFormat(" {0}", where);

        if (groupBy.NotNull())
            sqlBuilder.Append(groupBy);

        if (having.NotNull())
            sqlBuilder.Append(having);

        if (sort.NotNull())
            sqlBuilder.AppendFormat("{0}", sort);

        sqlBuilder.AppendFormat(" LIMIT {0} OFFSET {1};", take, skip);

        return sqlBuilder.ToString();
    }

19 View Source File : DataQueryService.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public object[] SearchFile(DateTime start, DateTime end, string user, string drive, string file)
		{
			StringBuilder filter = new StringBuilder();
			filter.AppendFormat(" '{0:yyyy-MM-dd}'<=date(StartTime) AND date(StartTime)<='{1:yyyy-MM-dd}' ", start, end);
			if (!string.IsNullOrEmpty(user) && ValidUser(user))
			{
				var domainUser = DomainUser.Create(user);
				if (domainUser != null)
					filter.AppendFormat(" AND Domain='{0}' AND UserName='{1}'", domainUser.Domain, domainUser.UserName);
			}
			if (!string.IsNullOrEmpty(drive) && ValidDrive(drive))
				filter.AppendFormat(" AND UrlHost='{0}' ", drive);
			else
				filter.AppendFormat(" AND UrlHost LIKE '_:'");
			if (!string.IsNullOrEmpty(file) && ValidKey(file))
				filter.AppendFormat(" AND WindowUrl LIKE 'file:///%{0}%' ", file);

			var segments = Database.Execute(db => db.SelectObjects<SnapshotGroup>("SearchUrl", filter.ToString(),
				"SessionDate", "SessionId", "Domain", "UserName", "StartTime", "EndTime", "UrlHost", "WindowUrl", "SnapshotCount"));

			List<object> objs = new List<object>();
			foreach (var sg in segments)
				objs.Add(new
				{
					SID = sg.SID,
					Date = sg.SessionDate,
					User = sg.User,
					Host = sg.UrlHost,
					Time = sg.TimeRange,
					Url = sg.WindowUrl,
					Count = sg.SnapshotCount,
				});

			return objs.ToArray();
		}

19 View Source File : PaypalHelper.cs
License : MIT License
Project Creator : Adoxio

public string GetSubmitUrl(Dictionary<string, string> values)
		{
			StringBuilder url = new StringBuilder();

			if (values.ContainsKey("cmd") && values.ContainsKey("business"))
			{
				//Do I need to check if dict contains "upload" and put it right after "cmd"????
				url.AppendFormat("{0}?cmd={1}&business={2}", PayPalBaseUrl, values["cmd"], values["business"]);
			}
			else
			{
				throw new Exception("Invalid Paypal submit URL.  No value for cmd or business found in query string");
			}

			foreach (var value in values)
			{
				if (value.Key == "cmd" || value.Key == "business")
				{
					continue;
				}

				if (value.Key.Contains("amount") || value.Key.Contains("shipping") || value.Key.Contains("handling"))
				{
					if (decimal.Parse(value.Value) != 0.00M)
					{
						url.AppendFormat("&{0}={1:f2}", value.Key, decimal.Parse(value.Value));
					}
				}

				url.AppendFormat("&{0}={1}", value.Key, HttpUtility.UrlEncode(value.Value));

			}

			return url.ToString();
		}

19 View Source File : ScriptEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal

private static string GenerateFunctions(object svc)
		{
			///> exclude parameters of RawRequestAttribute, RawResponseAttribute, RawParametersAttribute
			StringBuilder sb = new StringBuilder();
			var ms = svc.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
			foreach(MethodInfo mi in ms)
			{
				sb.AppendFormat(@"this.{0} = function (p, onResult, onError) {{ return this.implement('{0}', p, onResult, onError); }};", mi.Name);
				sb.AppendLine();
			
				var ps = new List<string>();
				foreach (var p in mi.GetParameters())
					ps.Add(p.Name + ":''");
				sb.AppendFormat(@"this.{0}.params = {{ {1} }};", mi.Name, string.Join(",", ps.ToArray()));
				sb.AppendLine();
			}
			return sb.ToString();
		}

19 View Source File : ICachingKeyGenerator.Default.cs
License : MIT License
Project Creator : 1100100

public string GenerateKeyPlaceholder(string keyPrefix, int globalExpire, string route, MethodInfo methodInfo, CachingAttribute cachingAttribute = default)
        {
            var sb = new StringBuilder();
            if (!string.IsNullOrWhiteSpace(keyPrefix))
                sb.AppendFormat("{0}{1}", keyPrefix, LinkString);
            if (cachingAttribute == null || string.IsNullOrWhiteSpace(cachingAttribute.Key))
            {
                sb.AppendFormat("{0}", route);
                if (methodInfo.GetParameters().Length > 0)
                    sb.Append(LinkString + "{0}");
            }
            else
                sb.Append(cachingAttribute.Key);

            return sb.ToString();
        }

19 View Source File : DataQueryService.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public object[] GetSessions(DateTime start, DateTime end, string user)
		{
			StringBuilder sbFilter = new StringBuilder();
			sbFilter.AppendFormat(" '{0:yyyy-MM-dd}'<=date(CreateTime) AND date(CreateTime)<='{1:yyyy-MM-dd}' ", start, end);
			sbFilter.Append(" AND SnapshotCount>0 ");
			if (!string.IsNullOrEmpty(user) && ValidUser(user))
			{
				var domainUser = DomainUser.Create(user);
				if (domainUser != null)
					sbFilter.AppendFormat(" AND Domain='{0}' AND UserName='{1}'", domainUser.Domain, domainUser.UserName);
			}

			var sessions = Database.Execute(db => db.SelectObjects<SessionObj>("SessionView", sbFilter.ToString(),
				"SessionId", "CreateTime", "LastActiveTime", "UserName", "Domain", "ClientName", "ClientAddress", "IsEnd", "SnapshotCount", "DataLength"));

			List<object> objs = new List<object>();
			foreach (var s in sessions)
				objs.Add(new
				{
					SID = s.SID,
					Date = s.Date,
					User = s.User,
					Time = s.TimeRange,
					Count = s.SnapshotCount,
					Length = s.DataLength,
					Active = s.IsActive,
					Client = s.ClientName,
					Address = s.ClientAddress,
				});

			return objs.ToArray();
		}

19 View Source File : RedisLiteHelper.cs
License : MIT License
Project Creator : AElfProject

public override string ToString()
        {
            var sb = new StringBuilder();
            sb.AppendFormat("{0}:{1}", Host, Port);

            var args = new List<string>();
            
            if (Client != null)
                args.Add("Client=" + Client);
            if (Preplacedword != null)
                args.Add("Preplacedword=" + System.Net.WebUtility.UrlEncode(Preplacedword));
            if (Db != RedisConfig.DefaultDb)
                args.Add("Db=" + Db);
            if (Ssl)
                args.Add("Ssl=true");
            if (ConnectTimeout != RedisConfig.DefaultConnectTimeout)
                args.Add("ConnectTimeout=" + ConnectTimeout);
            if (SendTimeout != RedisConfig.DefaultSendTimeout)
                args.Add("SendTimeout=" + SendTimeout);
            if (ReceiveTimeout != RedisConfig.DefaultReceiveTimeout)
                args.Add("ReceiveTimeout=" + ReceiveTimeout);
            if (RetryTimeout != RedisConfig.DefaultRetryTimeout)
                args.Add("RetryTimeout=" + RetryTimeout);
            if (IdleTimeOutSecs != RedisConfig.DefaultIdleTimeOutSecs)
                args.Add("IdleTimeOutSecs=" + IdleTimeOutSecs);
            if (NamespacePrefix != null)
                args.Add("NamespacePrefix=" + System.Net.WebUtility.UrlEncode(NamespacePrefix));

            if (args.Count > 0)
                sb.Append("?").Append(string.Join("&", args));

            return sb.ToString();
        }

19 View Source File : StatisticService.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public object[] ProgramUsage(DateTime start, DateTime end, string user)
		{
			Debug.replacedert(!string.IsNullOrEmpty(user));
			StringBuilder filter = new StringBuilder();
			filter.AppendFormat(" '{0:yyyy-MM-dd}'<=SessionDate AND SessionDate<='{1:yyyy-MM-dd}' ", start, end);
			filter.AppendFormat(" AND Domain='{0}'", user.Contains(@"\") ? user.Split('\\')[0] : Environment.MachineName);
			filter.AppendFormat(" AND UserName='{0}'", user.Contains(@"\") ? user.Split('\\')[1] : user);

			var groups = Database.Execute(db => db.ReadObjects<SnapGroup>("StatisticView", filter.ToString(), null, 4,
					"Domain", "UserName", "SessionDate", "ProcessName", "Sum(SnapCount) AS SnapCount"));

			List<object> array = new List<object>();
			foreach (var g in groups)
			{
				if (string.IsNullOrEmpty(g.ProcessName))
					continue;
				array.Add(new
				{
					User = g.User,
					Date = g.SessionDate,
					Prog = g.ProcessName,
					Count = g.SnapCount,
				});
			}
			return array.ToArray();
		}

19 View Source File : TemplateEngin.cs
License : MIT License
Project Creator : 2881099

private static ITemplateOutput Parser(string tplcode, string[] usings, IDictionary options) {
			int view = Interlocked.Increment(ref _view);
			StringBuilder sb = new StringBuilder();
			IDictionary options_copy = new Hashtable();
			foreach (DictionaryEntry options_de in options) options_copy[options_de.Key] = options_de.Value;
			sb.AppendFormat(@"
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;{1}

//namespace TplDynamicCodeGenerate {{
	public clreplaced TplDynamicCodeGenerate_view{0} : FreeSql.Template.TemplateEngin.ITemplateOutput {{
		public FreeSql.Template.TemplateEngin.TemplateReturnInfo OuTpUt(StringBuilder tOuTpUt, IDictionary oPtIoNs, string rEfErErFiLeNaMe, FreeSql.Template.TemplateEngin tEmPlAtEsEnDeR) {{
			FreeSql.Template.TemplateEngin.TemplateReturnInfo rTn = tOuTpUt == null ? 
				new FreeSql.Template.TemplateEngin.TemplateReturnInfo {{ Sb = (tOuTpUt = new StringBuilder()), Blocks = new Dictionary<string, int[]>() }} :
				new FreeSql.Template.TemplateEngin.TemplateReturnInfo {{ Sb = tOuTpUt, Blocks = new Dictionary<string, int[]>() }};
			Dictionary<string, int[]> TPL__blocks = rTn.Blocks;
			Stack<int[]> TPL__blocks_stack = new Stack<int[]>();
			int[] TPL__blocks_stack_peek;
			List<IDictionary> TPL__forc = new List<IDictionary>();
			Func<IDictionary> pRoCeSsOpTiOnS = new Func<IDictionary>(delegate () {{
				IDictionary nEwoPtIoNs = new Hashtable();
				foreach (DictionaryEntry oPtIoNs_dE in oPtIoNs)
					nEwoPtIoNs[oPtIoNs_dE.Key] = oPtIoNs_dE.Value;
				foreach (IDictionary TPL__forc_dIc in TPL__forc)
					foreach (DictionaryEntry TPL__forc_dIc_dE in TPL__forc_dIc)
						nEwoPtIoNs[TPL__forc_dIc_dE.Key] = TPL__forc_dIc_dE.Value;
				return nEwoPtIoNs;
			}});
			FreeSql.Template.TemplateEngin.TemplateIf tPlIf = delegate(object exp) {{
				if (exp is bool) return (bool)exp;
				if (exp == null) return false;
				if (exp is int && (int)exp == 0) return false;
				if (exp is string && (string)exp == string.Empty) return false;
				if (exp is long && (long)exp == 0) return false;
				if (exp is short && (short)exp == 0) return false;
				if (exp is byte && (byte)exp == 0) return false;
				if (exp is double && (double)exp == 0) return false;
				if (exp is float && (float)exp == 0) return false;
				if (exp is decimal && (decimal)exp == 0) return false;
				return true;
			}};
			FreeSql.Template.TemplateEngin.TemplatePrint print = delegate(object[] pArMs) {{
				if (pArMs == null || pArMs.Length == 0) return;
				foreach (object pArMs_A in pArMs) if (pArMs_A != null) tOuTpUt.Append(pArMs_A);
			}};
			FreeSql.Template.TemplateEngin.TemplatePrint Print = print;", view, usings?.Any() == true ? $"\r\nusing {string.Join(";\r\nusing ", usings)};" : "");

			#region {miss}...{/miss}块内容将不被解析
			string[] tmp_content_arr = _reg_miss.Split(tplcode);
			if (tmp_content_arr.Length > 1) {
				sb.AppendFormat(@"
			string[] TPL__MISS = new string[{0}];", Math.Ceiling(1.0 * (tmp_content_arr.Length - 1) / 2));
				int miss_len = -1;
				for (int a = 1; a < tmp_content_arr.Length; a += 2) {
					sb.Append(string.Concat(@"
			TPL__MISS[", ++miss_len, @"] = """, Utils.GetConstString(tmp_content_arr[a]), @""";"));
					tmp_content_arr[a] = string.Concat("{#TPL__MISS[", miss_len, "]}");
				}
				tplcode = string.Join("", tmp_content_arr);
			}
			#endregion
			#region 扩展语法如 <div @if="表达式"></div>
			tplcode = htmlSyntax(tplcode, 3); //<div @if="c#表达式" @for="index 1,100"></div>
											  //处理 {% %} 块 c#代码
			tmp_content_arr = _reg_code.Split(tplcode);
			if (tmp_content_arr.Length == 1) {
				tplcode = Utils.GetConstString(tplcode)
					.Replace("{%", "{$TEMPLATE__CODE}")
					.Replace("%}", "{/$TEMPLATE__CODE}");
			} else {
				tmp_content_arr[0] = Utils.GetConstString(tmp_content_arr[0]);
				for (int a = 1; a < tmp_content_arr.Length; a += 4) {
					tmp_content_arr[a] = "{$TEMPLATE__CODE}";
					tmp_content_arr[a + 2] = "{/$TEMPLATE__CODE}";
					tmp_content_arr[a + 3] = Utils.GetConstString(tmp_content_arr[a + 3]);
				}
				tplcode = string.Join("", tmp_content_arr);
			}
			#endregion
			sb.Append(@"
			tOuTpUt.Append(""");

			string error = null;
			int tpl_tmpid = 0;
			int forc_i = 0;
			string extends = null;
			Stack<string> codeTree = new Stack<string>();
			Stack<string> forEndRepl = new Stack<string>();
			sb.Append(_reg.Replace(tplcode, delegate (Match m) {
				string _0 = m.Groups[0].Value;
				if (!string.IsNullOrEmpty(error)) return _0;

				string _1 = m.Groups[1].Value.Trim(' ', '\t');
				string _2 = m.Groups[2].Value
					.Replace("\\\\", "\\")
					.Replace("\\\"", "\"");
				_2 = Utils.ReplaceSingleQuote(_2);

				switch (_1) {
					#region $TEMPLATE__CODE--------------------------------------------------
					case "$TEMPLATE__CODE":
						codeTree.Push(_1);
						return @""");
";
					case "/$TEMPLATE__CODE":
						string pop = codeTree.Pop();
						if (pop != "$TEMPLATE__CODE") {
							codeTree.Push(pop);
							error = "编译出错,{% 与 %} 并没有配对";
							return _0;
						}
						return @"
			tOuTpUt.Append(""";
					#endregion
					case "include":
						return string.Format(@""");
tEmPlAtEsEnDeR.RenderFile2(tOuTpUt, pRoCeSsOpTiOnS(), ""{0}"", rEfErErFiLeNaMe);
			tOuTpUt.Append(""", _2);
					case "import":
						return _0;
					case "module":
						return _0;
					case "/module":
						return _0;
					case "extends":
						//{extends ../inc/layout.html}
						if (string.IsNullOrEmpty(extends) == false) return _0;
						extends = _2;
						return string.Empty;
					case "block":
						codeTree.Push("block");
						return string.Format(@""");
TPL__blocks_stack_peek = new int[] {{ tOuTpUt.Length, 0 }};
TPL__blocks_stack.Push(TPL__blocks_stack_peek);
TPL__blocks.Add(""{0}"", TPL__blocks_stack_peek);
tOuTpUt.Append(""", _2.Trim(' ', '\t'));
					case "/block":
						codeTreeEnd(codeTree, "block");
						return @""");
TPL__blocks_stack_peek = TPL__blocks_stack.Pop();
TPL__blocks_stack_peek[1] = tOuTpUt.Length - TPL__blocks_stack_peek[0];
tOuTpUt.Append(""";

					#region ##---------------------------------------------------------
					case "#":
						if (_2[0] == '#')
							return string.Format(@""");
			try {{ Print({0}); }} catch {{ }}
			tOuTpUt.Append(""", _2.Substring(1));
						return string.Format(@""");
			Print({0});
			tOuTpUt.Append(""", _2);
					#endregion
					#region for--------------------------------------------------------
					case "for":
						forc_i++;
						int cur_tpl_tmpid = tpl_tmpid;
						string sb_endRepl = string.Empty;
						StringBuilder sbfor = new StringBuilder();
						sbfor.Append(@""");");
						Match mfor = _reg_forin.Match(_2);
						if (mfor.Success) {
							string mfor1 = mfor.Groups[1].Value.Trim(' ', '\t');
							string mfor2 = mfor.Groups[2].Value.Trim(' ', '\t');
							sbfor.AppendFormat(@"
//new Action(delegate () {{
	IDictionary TPL__tmp{0} = new Hashtable();
	TPL__forc.Add(TPL__tmp{0});
	var TPL__tmp{1} = {3};
	var TPL__tmp{2} = {4};", ++tpl_tmpid, ++tpl_tmpid, ++tpl_tmpid, mfor.Groups[3].Value, mfor1);
							sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
	{0} = TPL__tmp{1};", mfor1, cur_tpl_tmpid + 3));
							if (options_copy.Contains(mfor1) == false) options_copy[mfor1] = null;
							if (!string.IsNullOrEmpty(mfor2)) {
								sbfor.AppendFormat(@"
	var TPL__tmp{1} = {0};
	{0} = 0;", mfor2, ++tpl_tmpid);
								sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
	{0} = TPL__tmp{1};", mfor2, tpl_tmpid));
								if (options_copy.Contains(mfor2) == false) options_copy[mfor2] = null;
							}
							sbfor.AppendFormat(@"
	if (TPL__tmp{1} != null)
	foreach (var TPL__tmp{0} in TPL__tmp{1}) {{", ++tpl_tmpid, cur_tpl_tmpid + 2);
							if (!string.IsNullOrEmpty(mfor2))
								sbfor.AppendFormat(@"
		TPL__tmp{1}[""{0}""] = ++ {0};", mfor2, cur_tpl_tmpid + 1);
							sbfor.AppendFormat(@"
		TPL__tmp{1}[""{0}""] = TPL__tmp{2};
		{0} = TPL__tmp{2};
		tOuTpUt.Append(""", mfor1, cur_tpl_tmpid + 1, tpl_tmpid);
							codeTree.Push("for");
							forEndRepl.Push(sb_endRepl);
							return sbfor.ToString();
						}
						mfor = _reg_foron.Match(_2);
						if (mfor.Success) {
							string mfor1 = mfor.Groups[1].Value.Trim(' ', '\t');
							string mfor2 = mfor.Groups[2].Value.Trim(' ', '\t');
							string mfor3 = mfor.Groups[3].Value.Trim(' ', '\t');
							sbfor.AppendFormat(@"
//new Action(delegate () {{
	IDictionary TPL__tmp{0} = new Hashtable();
	TPL__forc.Add(TPL__tmp{0});
	var TPL__tmp{1} = {3};
	var TPL__tmp{2} = {4};", ++tpl_tmpid, ++tpl_tmpid, ++tpl_tmpid, mfor.Groups[4].Value, mfor1);
							sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
	{0} = TPL__tmp{1};", mfor1, cur_tpl_tmpid + 3));
							if (options_copy.Contains(mfor1) == false) options_copy[mfor1] = null;
							if (!string.IsNullOrEmpty(mfor2)) {
								sbfor.AppendFormat(@"
	var TPL__tmp{1} = {0};", mfor2, ++tpl_tmpid);
								sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
	{0} = TPL__tmp{1};", mfor2, tpl_tmpid));
								if (options_copy.Contains(mfor2) == false) options_copy[mfor2] = null;
							}
							if (!string.IsNullOrEmpty(mfor3)) {
								sbfor.AppendFormat(@"
	var TPL__tmp{1} = {0};
	{0} = 0;", mfor3, ++tpl_tmpid);
								sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
	{0} = TPL__tmp{1};", mfor3, tpl_tmpid));
								if (options_copy.Contains(mfor3) == false) options_copy[mfor3] = null;
							}
							sbfor.AppendFormat(@"
	if (TPL__tmp{2} != null)
	foreach (DictionaryEntry TPL__tmp{1} in TPL__tmp{2}) {{
		{0} = TPL__tmp{1}.Key;
		TPL__tmp{3}[""{0}""] = {0};", mfor1, ++tpl_tmpid, cur_tpl_tmpid + 2, cur_tpl_tmpid + 1);
							if (!string.IsNullOrEmpty(mfor2))
								sbfor.AppendFormat(@"
		{0} = TPL__tmp{1}.Value;
		TPL__tmp{2}[""{0}""] = {0};", mfor2, tpl_tmpid, cur_tpl_tmpid + 1);
							if (!string.IsNullOrEmpty(mfor3))
								sbfor.AppendFormat(@"
		TPL__tmp{1}[""{0}""] = ++ {0};", mfor3, cur_tpl_tmpid + 1);
							sbfor.AppendFormat(@"
		tOuTpUt.Append(""");
							codeTree.Push("for");
							forEndRepl.Push(sb_endRepl);
							return sbfor.ToString();
						}
						mfor = _reg_forab.Match(_2);
						if (mfor.Success) {
							string mfor1 = mfor.Groups[1].Value.Trim(' ', '\t');
							sbfor.AppendFormat(@"
//new Action(delegate () {{
	IDictionary TPL__tmp{0} = new Hashtable();
	TPL__forc.Add(TPL__tmp{0});
	var TPL__tmp{1} = {5};
	{5} = {3} - 1;
	if ({5} == null) {5} = 0;
	var TPL__tmp{2} = {4} + 1;
	while (++{5} < TPL__tmp{2}) {{
		TPL__tmp{0}[""{5}""] = {5};
		tOuTpUt.Append(""", ++tpl_tmpid, ++tpl_tmpid, ++tpl_tmpid, mfor.Groups[2].Value, mfor.Groups[3].Value, mfor1);
							sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
	{0} = TPL__tmp{1};", mfor1, cur_tpl_tmpid + 1));
							if (options_copy.Contains(mfor1) == false) options_copy[mfor1] = null;
							codeTree.Push("for");
							forEndRepl.Push(sb_endRepl);
							return sbfor.ToString();
						}
						return _0;
					case "/for":
						if (--forc_i < 0) return _0;
						codeTreeEnd(codeTree, "for");
						return string.Format(@""");
	}}{0}
	TPL__forc.RemoveAt(TPL__forc.Count - 1);
//}})();
			tOuTpUt.Append(""", forEndRepl.Pop());
					#endregion
					#region if---------------------------------------------------------
					case "if":
						codeTree.Push("if");
						return string.Format(@""");
			if ({1}tPlIf({0})) {{
				tOuTpUt.Append(""", _2[0] == '!' ? _2.Substring(1) : _2, _2[0] == '!' ? '!' : ' ');
					case "elseif":
						codeTreeEnd(codeTree, "if");
						codeTree.Push("if");
						return string.Format(@""");
			}} else if ({1}tPlIf({0})) {{
				tOuTpUt.Append(""", _2[0] == '!' ? _2.Substring(1) : _2, _2[0] == '!' ? '!' : ' ');
					case "else":
						codeTreeEnd(codeTree, "if");
						codeTree.Push("if");
						return @""");
			} else {
			tOuTpUt.Append(""";
					case "/if":
						codeTreeEnd(codeTree, "if");
						return @""");
			}
			tOuTpUt.Append(""";
						#endregion
				}
				return _0;
			}));

			sb.Append(@""");");
			if (string.IsNullOrEmpty(extends) == false) {
				sb.AppendFormat(@"
FreeSql.Template.TemplateEngin.TemplateReturnInfo eXtEnDs_ReT = tEmPlAtEsEnDeR.RenderFile2(null, pRoCeSsOpTiOnS(), ""{0}"", rEfErErFiLeNaMe);
string rTn_Sb_string = rTn.Sb.ToString();
foreach(string eXtEnDs_ReT_blocks_key in eXtEnDs_ReT.Blocks.Keys) {{
	if (rTn.Blocks.ContainsKey(eXtEnDs_ReT_blocks_key)) {{
		int[] eXtEnDs_ReT_blocks_value = eXtEnDs_ReT.Blocks[eXtEnDs_ReT_blocks_key];
		eXtEnDs_ReT.Sb.Remove(eXtEnDs_ReT_blocks_value[0], eXtEnDs_ReT_blocks_value[1]);
		int[] rTn_blocks_value = rTn.Blocks[eXtEnDs_ReT_blocks_key];
		eXtEnDs_ReT.Sb.Insert(eXtEnDs_ReT_blocks_value[0], rTn_Sb_string.Substring(rTn_blocks_value[0], rTn_blocks_value[1]));
		foreach(string eXtEnDs_ReT_blocks_keyb in eXtEnDs_ReT.Blocks.Keys) {{
			if (eXtEnDs_ReT_blocks_keyb == eXtEnDs_ReT_blocks_key) continue;
			int[] eXtEnDs_ReT_blocks_valueb = eXtEnDs_ReT.Blocks[eXtEnDs_ReT_blocks_keyb];
			if (eXtEnDs_ReT_blocks_valueb[0] >= eXtEnDs_ReT_blocks_value[0])
				eXtEnDs_ReT_blocks_valueb[0] = eXtEnDs_ReT_blocks_valueb[0] - eXtEnDs_ReT_blocks_value[1] + rTn_blocks_value[1];
		}}
		eXtEnDs_ReT_blocks_value[1] = rTn_blocks_value[1];
	}}
}}
return eXtEnDs_ReT;
", extends);
			} else {
				sb.Append(@"
return rTn;");
			}
			sb.Append(@"
		}
	}
//}
");
			var str = "FreeSql.Template.TemplateEngin.TemplatePrint Print = print;";
			int dim_idx = sb.ToString().IndexOf(str) + str.Length;
			foreach (string dic_name in options_copy.Keys) {
				sb.Insert(dim_idx, string.Format(@"
			dynamic {0} = oPtIoNs[""{0}""];", dic_name));
			}
			//Console.WriteLine(sb.ToString());
			return Complie(sb.ToString(), @"TplDynamicCodeGenerate_view" + view);
		}

19 View Source File : InitializationFile.cs
License : MIT License
Project Creator : AlexanderPro

public override string ToString()
        {
            var content = new StringBuilder();
            foreach (var pair in _content)
            {
                content.AppendFormat("[{0}]{1}", pair.Key, Environment.NewLine);
                foreach (var pairInner in pair.Value)
                {
                    content.AppendFormat("{0}={1}{2}", pairInner.Key, pairInner.Value, Environment.NewLine);
                }
                content.AppendLine();
            }
            return content.ToString();
        }

19 View Source File : SqliteTable.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public string FieldConditionSQL(bool isAnd, params string[] fields)
        {
            if (fields == null || fields.Length == 0)
            {
                throw new ArgumentException(@"没有字段用于生成组合条件", "fields");
            }
            var sql = new StringBuilder();
            sql.AppendFormat(@"({0})", FieldConditionSQL(fields[0]));
            for (var idx = 1; idx < fields.Length; idx++)
            {
                sql.AppendFormat(@" {0} ({1}) ", isAnd ? "AND" : "OR", FieldConditionSQL(fields[idx]));
            }
            return sql.ToString();
        }

19 View Source File : CSharpMethod.cs
License : GNU General Public License v3.0
Project Creator : alexgracianoarj

public string GetDeclarationLine(bool withSemicolon)
		{
			StringBuilder builder = new StringBuilder(100);

			if (AccessModifier != AccessModifier.Default) {
				builder.Append(Language.GetAccessString(AccessModifier, true));
				builder.Append(" ");
			}
			if (IsHider)
				builder.Append("new ");
			if (IsStatic)
				builder.Append("static ");
			if (IsVirtual)
				builder.Append("virtual ");
			if (IsAbstract)
				builder.Append("abstract ");
			if (IsSealed)
				builder.Append("sealed ");
			if (IsOverride)
				builder.Append("override ");

			if (string.IsNullOrEmpty(Type))
				builder.AppendFormat("{0}(", Name);
			else
				builder.AppendFormat("{0} {1}(", Type, Name);

			for (int i = 0; i < ArgumentList.Count; i++) {
				builder.Append(ArgumentList[i]);
				if (i < ArgumentList.Count - 1)
					builder.Append(", ");
			}
			builder.Append(")");

			if (withSemicolon && !HasBody)
				builder.Append(";");

			return builder.ToString();
		}

19 View Source File : SozlukDataStore.cs
License : MIT License
Project Creator : 0ffffffffh

private static string BuildFetchSQLQuery(
            ref string baseQueryHash,
            string content, 
            string suser, 
            DateTime begin, DateTime end,
            int rowBegin,int rowEnd)
        {
            bool linkAnd = false;
            string query;

            StringBuilder sb = new StringBuilder();
            StringBuilder cond = new StringBuilder();

            if (!CacheManager.TryGetCachedResult<string>(baseQueryHash, out query))
            {

                if (!string.IsNullOrEmpty(suser))
                    sb.AppendFormat(SEARCH_SUSER_ID_GET_SQL, suser.Trim());

                if (!string.IsNullOrEmpty(content))
                {
                    cond.AppendFormat(SEARCH_COND_CONTENT, content.Trim());
                    linkAnd = true;
                }

                if (!string.IsNullOrEmpty(suser))
                {
                    if (linkAnd)
                        cond.Append(" AND ");
                    else
                        linkAnd = true;

                    cond.Append(SEARCH_COND_SUSER);
                }

                if (begin != DateTime.MinValue && end != DateTime.MinValue)
                {
                    if (linkAnd)
                        cond.Append(" AND ");

                    cond.AppendFormat(SEARCH_COND_DATE, begin.ToString(), end.ToString());

                }

                sb.Append(SEARCH_SQL_BASE);

                if (cond.Length > 0)
                {
                    cond.Insert(0, "WHERE ");
                    sb.Replace("%%CONDITIONS%%", cond.ToString());
                }
                else
                {
                    sb.Replace("%%CONDITIONS%%", string.Empty);
                }

                if (!string.IsNullOrEmpty(content))
                    sb.Replace("%%COUNT_CONDITION%%", string.Format(SEARCH_COND_COUNT_CONTENT, content));
                else
                    sb.Replace("%%COUNT_CONDITION%%", SEARCH_COND_COUNT_ALL);


                if (!string.IsNullOrEmpty(suser))
                    sb.Append(" AND EntryCount > 0");

                sb.Append(";");

                baseQueryHash = Helper.Md5(sb.ToString());

                CacheManager.CacheObject(baseQueryHash, sb.ToString());
            }
            else
            {
                sb.Append(query);
            }

            sb.Replace("%%ROW_LIMIT_CONDITION%%",
                string.Format("RowNum BETWEEN {0} AND {1}", rowBegin, rowEnd));
            
            query = sb.ToString();

            cond.Clear();
            sb.Clear();

            cond = null;
            sb = null;

            return query;
        }

19 View Source File : GenericCPU.cs
License : MIT License
Project Creator : AlexGyver

public override string GetReport() {
      StringBuilder r = new StringBuilder();

      switch (vendor) {
        case Vendor.AMD: r.AppendLine("AMD CPU"); break;
        case Vendor.Intel: r.AppendLine("Intel CPU"); break;
        default: r.AppendLine("Generic CPU"); break;
      }

      r.AppendLine();
      r.AppendFormat("Name: {0}{1}", name, Environment.NewLine);
      r.AppendFormat("Number of Cores: {0}{1}", coreCount,
        Environment.NewLine);
      r.AppendFormat("Threads per Core: {0}{1}", cpuid[0].Length,
        Environment.NewLine);
      r.AppendLine(string.Format(CultureInfo.InvariantCulture,
        "Timer Frequency: {0} MHz", Stopwatch.Frequency * 1e-6));
      r.AppendLine("Time Stamp Counter: " + (hasTimeStampCounter ? (
        isInvariantTimeStampCounter ? "Invariant" : "Not Invariant") : "None"));
      r.AppendLine(string.Format(CultureInfo.InvariantCulture,
        "Estimated Time Stamp Counter Frequency: {0} MHz",
        Math.Round(estimatedTimeStampCounterFrequency * 100) * 0.01));
      r.AppendLine(string.Format(CultureInfo.InvariantCulture,
        "Estimated Time Stamp Counter Frequency Error: {0} Mhz",
        Math.Round(estimatedTimeStampCounterFrequency *
        estimatedTimeStampCounterFrequencyError * 1e5) * 1e-5));
      r.AppendLine(string.Format(CultureInfo.InvariantCulture,
        "Time Stamp Counter Frequency: {0} MHz",
        Math.Round(timeStampCounterFrequency * 100) * 0.01));   
      r.AppendLine();

      uint[] msrArray = GetMSRs();
      if (msrArray != null && msrArray.Length > 0) {
        for (int i = 0; i < cpuid.Length; i++) {
          r.AppendLine("MSR Core #" + (i + 1));
          r.AppendLine();
          r.AppendLine(" MSR       EDX       EAX");
          foreach (uint msr in msrArray)
            AppendMSRData(r, msr, cpuid[i][0].Thread);
          r.AppendLine();
        }
      }

      return r.ToString();
    }

19 View Source File : CollectionEx.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static string LinkToString(this Dictionary<string, string> em, string sp = ",", string head = null, string food = null)
        {
            if (em == null)
            {
                return null;
            }
            var sb = new StringBuilder();
            var first = true;
            if (head != null)
            {
                first = false;
                sb.Append(head);
                sb.Append(sp);
            }
            foreach (var value in em)
            {
                if (first)
                {
                    first = false;
                }
                else
                {
                    sb.Append(sp);
                }
                sb.AppendFormat(@"{{""{0}"",""{1}""}}", value.Key, value.Value);
            }
            if (first)
                return null;
            if (food != null)
            {
                sb.Append(sp);
                sb.Append(food);
            }
            return sb.ToString();
        }

19 View Source File : ClassStruct.cs
License : MIT License
Project Creator : 91Act

public static void ReadClreplacedStruct(StringBuilder sb, List<ClreplacedMember> members, EndianBinaryReader a_Stream)
        {
            for (int i = 0; i < members.Count; i++)
            {
                var member = members[i];
                var level = member.Level;
                var varTypeStr = member.Type;
                var varNameStr = member.Name;
                object value = null;
                var align = (member.Flag & 0x4000) != 0;
                var append = true;
                if (member.alignBefore)
                    a_Stream.AlignStream(4);
                if (varTypeStr == "SInt8")//sbyte
                {
                    value = a_Stream.ReadSByte();
                }
                else if (varTypeStr == "UInt8")//byte
                {
                    value = a_Stream.ReadByte();
                }
                else if (varTypeStr == "short" || varTypeStr == "SInt16")//Int16
                {
                    value = a_Stream.ReadInt16();
                }
                else if (varTypeStr == "UInt16" || varTypeStr == "unsigned short")//UInt16
                {
                    value = a_Stream.ReadUInt16();
                }
                else if (varTypeStr == "int" || varTypeStr == "SInt32")//Int32
                {
                    value = a_Stream.ReadInt32();
                }
                else if (varTypeStr == "UInt32" || varTypeStr == "unsigned int" || varTypeStr == "Type*")//UInt32
                {
                    value = a_Stream.ReadUInt32();
                }
                else if (varTypeStr == "long long" || varTypeStr == "SInt64")//Int64
                {
                    value = a_Stream.ReadInt64();
                }
                else if (varTypeStr == "UInt64" || varTypeStr == "unsigned long long")//UInt64
                {
                    value = a_Stream.ReadUInt64();
                }
                else if (varTypeStr == "float")//float
                {
                    value = a_Stream.ReadSingle();
                }
                else if (varTypeStr == "double")//double
                {
                    value = a_Stream.ReadDouble();
                }
                else if (varTypeStr == "bool")//bool
                {
                    value = a_Stream.ReadBoolean();
                }
                else if (varTypeStr == "string")//string
                {
                    append = false;
                    var str = a_Stream.ReadAlignedString(a_Stream.ReadInt32());
                    sb.AppendFormat("{0}{1} {2} = \"{3}\"\r\n", (new string('\t', level)), varTypeStr, varNameStr, str);
                    i += 3;//skip
                }
                else if (varTypeStr == "Array")//Array
                {
                    append = false;
                    if ((members[i - 1].Flag & 0x4000) != 0)
                        align = true;
                    sb.AppendFormat("{0}{1} {2}\r\n", (new string('\t', level)), varTypeStr, varNameStr);
                    var size = a_Stream.ReadInt32();
                    sb.AppendFormat("{0}{1} {2} = {3}\r\n", (new string('\t', level)), "int", "size", size);
                    var array = ReadArray(members, level, i);
                    for (int j = 0; j < size; j++)
                    {
                        sb.AppendFormat("{0}[{1}]\r\n", (new string('\t', level + 1)), j);
                        ReadClreplacedStruct(sb, array, a_Stream);
                    }
                    i += array.Count + 1;//skip
                }
                else if (varTypeStr == "TypelessData")
                {
                    append = false;
                    var size = a_Stream.ReadInt32();
                    a_Stream.ReadBytes(size);
                    i += 2;
                    sb.AppendFormat("{0}{1} {2}\r\n", (new string('\t', level)), varTypeStr, varNameStr);
                    sb.AppendFormat("{0}{1} {2} = {3}\r\n", (new string('\t', level)), "int", "size", size);
                }
                else
                {
                    append = false;
                    if (align)
                    {
                        align = false;
                        SetAlignBefore(members, level, i + 1);
                    }
                    sb.AppendFormat("{0}{1} {2}\r\n", (new string('\t', level)), varTypeStr, varNameStr);
                }
                if (append)
                    sb.AppendFormat("{0}{1} {2} = {3}\r\n", (new string('\t', level)), varTypeStr, varNameStr, value);
                if (align)
                    a_Stream.AlignStream(4);
            }
        }

19 View Source File : HealthMonitor.cs
License : MIT License
Project Creator : 0ffffffffh

private string RebuildArgList(string argList, string extras)
        {
            if (string.IsNullOrEmpty(extras))
                return argList;

            StringBuilder sb = new StringBuilder();
            string s;
            Dictionary<string, string> eArgs = Helper.ParseOptions(argList);
            Dictionary<string, string> extraDict = Helper.ParseOptions(extras);

            foreach (var key in extraDict.Keys)
            {
                if (eArgs.ContainsKey(key))
                {
                    eArgs[key] = extraDict[key];
                }
                else
                {
                    eArgs.Add(key, extraDict[key]);
                }
            }


            extraDict.Clear();
            extraDict = null;

            foreach (var key in eArgs.Keys)
            {
                sb.AppendFormat("{0} {1} ", key, eArgs[key]);
            }

            s = sb.ToString().TrimEnd();

            eArgs.Clear();
            eArgs = null;

            sb.Clear();
            sb = null;

            return s;
        }

19 View Source File : InternalTalk.cs
License : MIT License
Project Creator : 0ffffffffh

public void SendTalkData(Dictionary<string, string> data)
        {
            StringBuilder sb = new StringBuilder();

            foreach (var key in data.Keys)
            {
                sb.AppendFormat("{0}={1};", key, data[key]);
            }

            SendPacket(sb.ToString());

            sb.Clear();
            sb = null;
        }

19 View Source File : MySqlDbAdapter.cs
License : MIT License
Project Creator : 17MKH

public override string GeneratePagingSql(string select, string table, string where, string sort, int skip, int take, string groupBy = null, string having = null)
    {
        var sqlBuilder = new StringBuilder();
        sqlBuilder.AppendFormat("SELECT {0} FROM {1}", select, table);
        if (where.NotNull())
            sqlBuilder.AppendFormat(" {0}", where);

        if (groupBy.NotNull())
            sqlBuilder.Append(groupBy);

        if (having.NotNull())
            sqlBuilder.Append(having);

        if (sort.NotNull())
            sqlBuilder.AppendFormat("{0}", sort);

        if (skip == 0)
            sqlBuilder.AppendFormat(" LIMIT {0}", take);
        else
            sqlBuilder.AppendFormat(" LIMIT {0},{1}", skip, take);

        return sqlBuilder.ToString();
    }

19 View Source File : FileContainerItem.cs
License : MIT License
Project Creator : actions

public static string EnsurePathFormat(string path)
        {
            if (string.IsNullOrWhiteSpace(path))
            {
                return string.Empty;
            }

            // We always make sure that the path is rooted
            StringBuilder sb = new StringBuilder();
            String[] components = path.Split(new char[] { '\\', '/' }, StringSplitOptions.RemoveEmptyEntries);

            if (components.Length == 0)
            {
                return string.Empty;
            }

            for (int i = 0; i < components.Length; i++)
            {
                sb.AppendFormat("{0}{1}", components[i], i == components.Length - 1 ? String.Empty : "/");
            }

            return sb.ToString();
        }

19 View Source File : DatabaseEngine.cs
License : GNU General Public License v3.0
Project Creator : aiportal

private void DumpException(Exception ex, string sql, params object[] pramsArray)
		{
			StringBuilder sb = new StringBuilder();
			if (pramsArray != null)
			{
				foreach (object prams in pramsArray)
				{
					if (prams != null)
					{
						System.Reflection.PropertyInfo[] props = prams.GetType().GetProperties();
						//props.ToList().ForEach(p => sb.AppendFormat("{0} = {1},", p.Name, p.GetValue(prams, null)));
						foreach (var p in props)
							sb.AppendFormat("{0} = {1},", p.Name, p.GetValue(prams, null));
					}
				}
			}
			TraceLogger.Instance.WriteLineError(string.Format(
@"Exception at DatabaseEngine.
sql : {0}
parameters : {1}
exception : {2}", sql, sb.ToString(), ex.Message));
			TraceLogger.Instance.WriteException(ex);
		}

See More Examples