/// <summary> /// Read file containing the modification tags template /// </summary> public static void Import() { _template = new ModificationTagTemplate(); string currentProperty = null; var sb = new StringBuilder(); Utils.ForEachLine(Config.FileModificationTags, DataResources.ModificationTags, (i, line) => { if (line.EndsWith("=>")) { if (!string.IsNullOrEmpty(currentProperty)) { _template.SetValueOf(currentProperty, sb.TrimEnd(2).ToString()); } sb.Clear(); currentProperty = line.Replace("=>", "").Trim(); } else { sb.AppendLine(line); } }, Encoding.Default); if (!string.IsNullOrEmpty(currentProperty)) { _template.SetValueOf(currentProperty, sb.TrimEnd(2).ToString()); } }
/// <summary> /// 将Table的数据转化为JsonResult. /// </summary> /// <param name="data">按DataTable的分页数据</param> /// <returns>JsonResult对象</returns> public static JsonResult ToJsonResultTable(this DataSet data) { JsonResult result = new TextJsonResult(); StringBuilder sbJson = new StringBuilder(); StringBuilder sbRows = new StringBuilder(); sbRows.Append("["); JavaScriptSerializer serializer = new JavaScriptSerializer(); foreach (DataRow row in data.Tables[0].Rows) { sbRows.Append("{"); foreach (DataColumn column in data.Tables[0].Columns) { sbRows.AppendFormat("\"{0}\":{1},", column.ColumnName, serializer.Serialize(row[column])); } sbRows.TrimEnd(','); sbRows.Append("},"); } sbRows.TrimEnd(','); sbRows.Append("]"); sbJson.AppendFormat("{{\"rows\":{0}}}", sbRows); result.Data = sbJson; result.JsonRequestBehavior = JsonRequestBehavior.AllowGet; return(result); }
/// <summary> /// 将PagedTable的数据转化为JsonResult. /// </summary> /// <param name="data">按DataTable的分页数据</param> /// <returns>JsonResult对象</returns> public static JsonResult ToJsonResult(this PagedTable data) { JsonResult result = new TextJsonResult(); StringBuilder sbJson = new StringBuilder(); StringBuilder sbRows = new StringBuilder(); sbRows.Append("["); JavaScriptSerializer serializer = new JavaScriptSerializer(); foreach (DataRow row in data.Table.Rows) { sbRows.Append("{"); foreach (DataColumn column in data.Table.Columns) { sbRows.AppendFormat("\"{0}\":{1},", column.ColumnName, serializer.Serialize(row[column])); } sbRows.TrimEnd(','); sbRows.Append("},"); } sbRows.TrimEnd(','); sbRows.Append("]"); sbJson.AppendFormat("{{\"page\":{0},\"total\":{1},\"records\":{2},\"rows\":{3}}}", data.CurrentPageIndex, data.TotalPageCount, data.TotalItemCount, sbRows); result.Data = sbJson; result.JsonRequestBehavior = JsonRequestBehavior.AllowGet; return(result); }
public void TriemEndTest() { StringBuilder sb; sb = new StringBuilder("asdfgef"); Assert.Equal("asdfgef", sb.TrimEnd('a').ToString()); Assert.Equal("asdfge", sb.TrimEnd('f').ToString()); sb.Append(" "); Assert.Equal("asdfge", sb.TrimEnd().ToString()); Assert.Equal("asdf", sb.TrimEnd(new[] { 'g', 'e' }).ToString()); Assert.Equal(sb.TrimEnd("asdf").ToString(), string.Empty); }
public void TriemEndTest() { StringBuilder sb; sb = new StringBuilder("asdfgef"); Assert.Equal(sb.TrimEnd('a').ToString(), "asdfgef"); Assert.Equal(sb.TrimEnd('f').ToString(), "asdfge"); sb.Append(" "); Assert.Equal(sb.TrimEnd().ToString(), "asdfge"); Assert.Equal(sb.TrimEnd(new[] { 'g', 'e' }).ToString(), "asdf"); Assert.Equal(sb.TrimEnd("asdf").ToString(), string.Empty); }
public void TrimEnd() { var sb = new StringBuilder(" This is a test. "); sb.TrimEnd(); Assert.Equal(" This is a test.", sb.ToString()); sb.Clear(); sb.Append(" This is a test. "); sb.TrimEnd(' ', '.'); Assert.Equal(" This is a test", sb.ToString()); }
private static void Next(StringBuilder sb, int i, int last) { if (i < last) { sb.TrimEnd(", "); sb.Append(" }"); sb.AppendLine(","); } else { sb.TrimEnd(", "); sb.AppendLine(" }"); } }
public string CreateSql(Process process) { var builder = new StringBuilder(); builder.AppendFormat("CREATE VIEW {0} AS\r\n", process.OutputConnection.Enclose(process.Star)); builder.AppendFormat("SELECT\r\n d.TflKey,\r\n d.TflBatchId,\r\n b.TflUpdate,\r\n"); var l = process.OutputConnection.L; var r = process.OutputConnection.R; var typedFields = new StarFields(process).TypedFields(); builder.AppendLine(string.Concat(new FieldSqlWriter(typedFields[StarFieldType.Master]).Alias(l, r).PrependEntityOutput(process.OutputConnection, "d").Prepend(" ").Write(",\r\n"), ",")); if (typedFields[StarFieldType.Foreign].Any()) { builder.AppendLine(string.Concat(new FieldSqlWriter(typedFields[StarFieldType.Foreign]).Alias(l, r).PrependEntityOutput(process.OutputConnection, "d").IsNull().ToAlias(l, r).Prepend(" ").Write(",\r\n"), ",")); } if (typedFields[StarFieldType.Other].Any()) { builder.AppendLine(string.Concat(new FieldSqlWriter(typedFields[StarFieldType.Other]).Alias(l, r).PrependEntityOutput(process.OutputConnection).IsNull().ToAlias(l, r).Prepend(" ").Write(",\r\n"), ",")); } builder.TrimEnd("\r\n,"); builder.AppendLine(); builder.AppendFormat("FROM {0} d\r\n", process.OutputConnection.Enclose(process.MasterEntity.OutputName())); builder.AppendFormat("INNER JOIN TflBatch b ON (d.TflBatchId = b.TflBatchId AND b.ProcessName = '{0}')\r\n", process.Name); foreach (var entity in process.Entities.Where(e => !e.IsMaster())) { builder.AppendFormat("LEFT OUTER JOIN {0} ON (", entity.OutputName()); foreach (var join in entity.RelationshipToMaster.First().Join.ToArray()) { builder.AppendFormat( "d.{0} = {1}.{2} AND ", process.OutputConnection.Enclose(join.LeftField.Alias), entity.OutputName(), process.OutputConnection.Enclose(join.RightField.Alias)); } builder.TrimEnd(" AND "); builder.AppendLine(")"); } builder.Append(";"); return(builder.ToString()); }
/// <summary> /// 获取表的Sql脚本 /// </summary> /// <param name="table"></param> /// <returns></returns> public override string GetTableSqlText(SOTable table) { List <SOColumn> columnnList = table.ColumnList; StringBuilder sb = new StringBuilder(); sb.AppendLine("create table [dbo].[" + table.Name + "] ("); foreach (SOColumn item in columnnList) { sb.AppendFormat("\t[{0}] {1}", item.Name, item.NativeType); if (item.PrimaryKey) { sb.Append(" PRIMARY KEY "); } if (item.Identify) { sb.Append(" identity "); } else if (!item.Identify) { sb.Append(" not null "); if (item.DefaultValue != null && item.DefaultValue != "") { sb.Append(" default " + item.DefaultValue); } } sb.Append(",\r\n"); } sb = sb.TrimEnd(",\r\n"); sb.AppendLine("\r\n)"); return(sb.ToString()); }
protected void AppendMethod(MethodBase method) { var type = method.DeclaringType; if (type != null) { AppendFullType(type); Builder.Append(".").Append(method.Name).Append("("); foreach (var p in method.GetParameters()) { if (p.IsIn) { Builder.Append("ref "); } if (p.IsOut) { Builder.Append("out "); } AppendFullType(p.ParameterType); Builder.Append(", "); } Builder.TrimEnd(", "); Builder.Append(")"); } }
public void Append(string endOfLine = null) { if (!_info.Eof) { var opCode = _info.Reader.ReadOpCode(); var opProcessor = GetOpProcessor(opCode.OperandType, _builder, _info); _builder.Append(opCode.Name).Append(" "); opProcessor.ReadOperand(); AppendIlBytes(); _builder.TrimEnd(" "); if (endOfLine != null) { _builder.Append(endOfLine); } } }
private void AppendMethod(StringBuilder builder, MethodBase method) { var type = method.DeclaringType; if (type != null) { AppendFullType(builder, type); builder.Append(".").Append(method.Name).Append("("); foreach (var p in method.GetParameters()) { if (p.IsIn) { builder.Append("ref "); } if (p.IsOut) { builder.Append("out "); } AppendFullType(builder, p.ParameterType); builder.Append(", "); } builder.TrimEnd(", "); builder.Append(")"); } }
public void TrimStringBuidler() { StringBuilder sb = new StringBuilder("blah "); sb.TrimEnd(); Assert.AreEqual("blah", sb.ToString()); }
public override void IndentLines(TextDocument document, int beginLine, int endLine) { if (!SupportMultiLinesIndent(document)) { base.IndentLines(document, beginLine, endLine); return; } DocumentLine line = document.GetLineByNumber(beginLine); int offset = line?.Offset ?? -1; int length = CalcSegmentLength(line, endLine); if ((offset == -1) || (length == 0)) { return; } IndentationCompletedArg eventArg = PrepareIndentationCompletedArg(document); GherkinSimpleParser parser = new GherkinSimpleParser(document); string formatted_text = parser.Format(beginLine, endLine); if (endLine == document.LineCount) { StringBuilder sb = new StringBuilder(formatted_text); sb.TrimEnd().AppendLine(); formatted_text = sb.ToString(); } document.Replace(offset, length, formatted_text); EventAggregator <IndentationCompletedArg> .Instance.Publish(MainEditor, eventArg); }
internal EndRankingChainer(Chainer prev) : base(prev) { Build = (buildContext, buildArgs) => { StringBuilder sql = new StringBuilder(); Chainer node = GetPrev <RankingChainer>(); while (node != this) { var append = node.Build(buildContext, buildArgs); TryThrow(buildContext); if (append != null) { sql.Append(append); } node = node.Next; } return(Text.GenerateSql(200) .Append(sql.TrimEnd()) .Append(Text.RightBracket) .ToString()); }; }
public static StringBuilder Trim(this StringBuilder builder, params char[] remove) { builder.TrimEnd(remove); builder.TrimStart(remove); return(builder); }
public static StringBuilder Trim(this StringBuilder builder, char remove = ' ') { builder.TrimEnd(remove); builder.TrimStart(remove); return(builder); }
public override string CompInspectStringExtra() { StringBuilder ret = new StringBuilder(); if (parent.Map == null) { return(base.CompInspectStringExtra()); } if (isSecurityServer) { ret.AppendLine("ATPP_SecurityServersSynthesis".Translate(Utils.GCATPP.getNbSlotSecurisedAvailable(), Utils.GCATPP.getNbThingsConnected())) .AppendLine("ATTP_SecuritySlotsAdded".Translate(Utils.nbSecuritySlotsGeneratedBy((Building)parent))); } if (isHackingServer) { ret.AppendLine("ATPP_HackingServersSynthesis".Translate(Utils.GCATPP.getNbHackingPoints(), Utils.GCATPP.getNbHackingSlotAvailable())) .AppendLine("ATTP_HackingProducedPoints".Translate(Utils.nbHackingPointsGeneratedBy((Building)parent))) .AppendLine("ATTP_HackingSlotsAdded".Translate(Utils.nbHackingSlotsGeneratedBy((Building)parent))); } if (isSkillServer) { ret.AppendLine("ATPP_SkillServersSynthesis".Translate(Utils.GCATPP.getNbSkillPoints(), Utils.GCATPP.getNbSkillSlotAvailable())) .AppendLine("ATTP_SkillProducedPoints".Translate(Utils.nbSkillPointsGeneratedBy((Building)parent))) .AppendLine("ATTP_SkillSlotsAdded".Translate(Utils.nbSkillSlotsGeneratedBy((Building)parent))); } return(ret.TrimEnd().Append(base.CompInspectStringExtra()).ToString()); }
public static string DumpAIState(AIController ai) { var str = new StringBuilder(); ai.StateManager.BuildDebugText(str); return(str.TrimEnd().ToString()); }
/// <summary> /// Removes the given string from the end of a <see cref="StringBuilder"/> instance. /// </summary> /// <param name="sb">The <see cref="StringBuilder"/> instance.</param> /// <param name="trimString"> /// A <see cref="string"/> to trim. /// </param> /// <param name="trimmed"> /// When the method returns, will be set to <see langword="true"/> if anything was trimmed, /// or <see langword="false"/> if not. /// </param> /// <returns> /// The trimmed <see cref="StringBuilder"/> instance. /// </returns> public static StringBuilder TrimEnd(this StringBuilder sb, string trimString, out bool trimmed) { trimmed = false; if (string.IsNullOrEmpty(trimString)) { return(sb); } if (string.IsNullOrWhiteSpace(trimString)) { var length = sb.Length; sb = sb.TrimEnd(); trimmed = sb.Length != length; return(sb); } do { var offset = sb.Length - trimString.Length; for (var i = 0; i < sb.Length - offset; i++) { if (sb[offset + i] != trimString[i]) { return(sb); } } sb.Length -= trimString.Length; trimmed = true; }while (sb.Length >= trimString.Length); return(sb); }
/// <summary> /// Renders the flag enum. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="flagEnum">The flag enum.</param> /// <returns></returns> public static string RenderFlagEnum <T>(T flagEnum) where T : struct, IConvertible, IComparable, IFormattable { var bitWiseValues = flagEnum.GetEnumFlagValues(); if (bitWiseValues.Count < 1) { return(string.Empty); } else if (bitWiseValues.Count == 1) { return(string.Format("{0} ({1})", flagEnum.ToString(), flagEnum.ToInt32(null))); } else { StringBuilder builder = new StringBuilder(); foreach (var item in bitWiseValues) { builder.AppendFormat("{0} ({1}), ", item.ToString(), item.ToInt32(null)); } builder.TrimEnd(); builder.RemoveLastIfMatch(','); return(builder.ToString()); } }
/// <summary> /// Generates a detailed error message /// </summary> /// <param name="autoprefixerException">Autoprefixer exception</param> /// <param name="omitMessage">Flag for whether to omit message</param> /// <returns>Detailed error message</returns> public static string GenerateErrorDetails(AutoprefixerException autoprefixerException, bool omitMessage = false) { if (autoprefixerException == null) { throw new ArgumentNullException(nameof(autoprefixerException)); } var stringBuilderPool = StringBuilderPool.Shared; StringBuilder detailsBuilder = stringBuilderPool.Rent(); WriteCommonErrorDetails(detailsBuilder, autoprefixerException, omitMessage); var autoprefixerProcessingException = autoprefixerException as AutoprefixerProcessingException; if (autoprefixerProcessingException != null) { WriteProcessingErrorDetails(detailsBuilder, autoprefixerProcessingException); } detailsBuilder.TrimEnd(); string errorDetails = detailsBuilder.ToString(); stringBuilderPool.Return(detailsBuilder); return(errorDetails); }
/// <summary> /// Returns the exception to be thrown when <see cref="Mock.VerifyNoOtherCalls(Mock)"/> finds invocations that have not been verified. /// </summary> internal static MockException UnverifiedInvocations( Mock mock, IEnumerable <Invocation> invocations ) { var message = new StringBuilder(); message .AppendLine( string.Format(CultureInfo.CurrentCulture, Resources.UnverifiedInvocations, mock) ) .TrimEnd() .AppendLine() .AppendLine(); foreach (var invocation in invocations) { message.AppendIndented(invocation.ToString(), count: 3).TrimEnd().AppendLine(); } return(new MockException( MockExceptionReasons.UnverifiedInvocations, message.TrimEnd().ToString() )); }
private void ProcessFrame(StringBuilder sb, StackFrame frame) { var m = frame.GetMethod(); sb.Append(" in ").Append(m.DeclaringType).Append(".").Append(m.Name); var x = frame.GetFileLineNumber(); var y = frame.GetFileColumnNumber(); if (x != 0 && y != 0) { sb.Append(" at (").Append(x).Append(",").Append(y).Append(")"); } sb.Append(", "); var n = frame.GetILOffset(); if (n > 0) { sb.Append("#").Append(n).Append(": "); var info = new RuntimeOpInfo(m, n); var p = new OpCodeProcessor(sb, info, false); p.Append("; "); p.Append(";"); sb.TrimEnd(" "); } sb.AppendLine(); }
/// <summary> /// Generates a detailed error message /// </summary> /// <param name="sassException">Sass exception</param> /// <param name="omitMessage">Flag for whether to omit message</param> /// <returns>Detailed error message</returns> public static string GenerateErrorDetails(SassException sassException, bool omitMessage = false) { if (sassException == null) { throw new ArgumentNullException(nameof(sassException)); } var stringBuilderPool = StringBuilderPool.Shared; StringBuilder detailsBuilder = stringBuilderPool.Rent(); WriteCommonErrorDetails(detailsBuilder, sassException, omitMessage); var sassСompilationException = sassException as SassCompilationException; if (sassСompilationException != null) { WriteCompilationErrorDetails(detailsBuilder, sassСompilationException); } detailsBuilder.TrimEnd(); string errorDetails = detailsBuilder.ToString(); stringBuilderPool.Return(detailsBuilder); return(errorDetails); }
public static string IndentLines([NotNull] this string value, int indentWidth, char indentCharacter = ' ', Encoding encoding = default) { if (value == null) { throw new ArgumentNullException(nameof(value)); } if (indentWidth < 0) { throw new ArgumentOutOfRangeException(nameof(indentWidth)); } var output = new StringBuilder(); using (var valueStream = new MemoryStream((encoding ?? Encoding.UTF8).GetBytes(value))) using (var valueReader = new StreamReader(valueStream)) { while (valueReader.ReadLine() is var line && line != null) { output .Append(new string(indentCharacter, indentWidth)) .AppendLine(line); } } return (output .TrimEnd(Environment.NewLine) .ToString()); }
public void ListHomes() { if (!EssentialsPlugin.Instance.Config.EnableHomes) { Context.Respond("Homes are not enabled for this server!"); return; } var Account = PlayerAccounts.GetAccount(Context.Player.SteamUserId); var Rank = RanksAndPermissionsModule.GetRankData(Account.Rank); if (Rank == null || Account == null) { Context.Respond("Error loading required information. Home not deleted!"); return; } if (Account.Homes.Count == 0) { Context.Respond("You do not have any homes!"); return; } StringBuilder sb = new StringBuilder(); sb.Append("List of homes: "); foreach (var homes in Account.Homes) { sb.Append($"'{homes.Key}', "); } sb.TrimEnd(2); Context.Respond(sb.ToString()); }
/// <summary> /// Returns the exception to be thrown when <see cref="Mock.Verify"/> finds no invocations (or the wrong number of invocations) that match the specified expectation. /// </summary> internal static MockException NoMatchingCalls( Mock rootMock, LambdaExpression expression, string failMessage, Times times, int callCount) { var message = new StringBuilder(); message.AppendLine(times.GetExceptionMessage(failMessage, expression.PartialMatcherAwareEval().ToStringFixed(), callCount)) .AppendLine(Resources.PerformedInvocations) .AppendLine(); var visitedMocks = new HashSet <Mock>(); var mocks = new Queue <Mock>(); mocks.Enqueue(rootMock); while (mocks.Any()) { var mock = mocks.Dequeue(); if (visitedMocks.Contains(mock)) { continue; } visitedMocks.Add(mock); message.AppendLine(mock == rootMock ? $" {mock} ({expression.Parameters[0].Name}):" : $" {mock}:"); var invocations = mock.MutableInvocations.ToArray(); if (invocations.Any()) { message.AppendLine(); foreach (var invocation in invocations) { message.Append($" {invocation}"); if (invocation.Method.ReturnType != typeof(void) && Unwrap.ResultIfCompletedTask(invocation.ReturnValue) is IMocked mocked) { var innerMock = mocked.Mock; mocks.Enqueue(innerMock); message.Append($" => {innerMock}"); } message.AppendLine(); } } else { message.AppendLine($" {Resources.NoInvocationsPerformed}"); } message.AppendLine(); } return(new MockException(MockExceptionReasons.NoMatchingCalls, message.TrimEnd().AppendLine().ToString())); }
/// <summary> /// Returns a StringBuilder object to be written for a Fixed Length type file. /// </summary> /// <typeparam name="T">Type of List of items</typeparam> /// <param name="listOfObjects">List of items</param> /// <returns>StringBuilder Object to be written into the flat file</returns> private StringBuilder CreateFixedLengthTypeFile <T>(List <T> listOfObjects) { StringBuilder stringBuilder = new StringBuilder(); listOfObjects.ForEach(item => { item.GetType().GetProperties().ToList().ForEach(property => { if (!IsNullOrEmpty(property.GetValue(item, null))) { object lengthAttribute = property.GetCustomAttributes(false).First(); int padValue = Convert.ToInt16(lengthAttribute.GetType().GetProperty("Length").GetValue(lengthAttribute, null)); if (padValue >= property.GetValue(item, null).ToString().Length) { stringBuilder.Append(property.GetValue(item, null).ToString().Trim().PadRight(padValue)); } else { stringBuilder.Append(property.GetValue(item, null).ToString().Truncate(padValue)); } } }); stringBuilder.TrimEnd().AppendLine(); }); return(stringBuilder); }
/// <summary> /// Generates a detailed error message /// </summary> /// <param name="jsScriptException">JS script exception</param> /// <param name="omitMessage">Flag for whether to omit message</param> /// <returns>Detailed error message</returns> public static string GenerateErrorDetails(JsScriptException jsScriptException, bool omitMessage = false) { if (jsScriptException == null) { throw new ArgumentNullException(nameof(jsScriptException)); } var stringBuilderPool = StringBuilderPool.Shared; StringBuilder detailsBuilder = stringBuilderPool.Rent(); WriteCommonErrorDetails(detailsBuilder, jsScriptException, omitMessage); WriteScriptErrorDetails(detailsBuilder, jsScriptException); var jsRuntimeException = jsScriptException as JsRuntimeException; if (jsRuntimeException != null) { WriteRuntimeErrorDetails(detailsBuilder, jsRuntimeException); } detailsBuilder.TrimEnd(); string errorDetails = detailsBuilder.ToString(); stringBuilderPool.Return(detailsBuilder); return(errorDetails); }
public void TrimEnd(string str, char c, string expected) { var actual = new StringBuilder(str); actual.TrimEnd(c); Assert.Equal(expected, actual.ToString()); }
internal string ToString(string sufix) { StringBuilder info = new StringBuilder(); info.AppendFormat("Name: {0} {1}", this.FirstName, this.LastName).AppendLine(); info.AppendLine(sufix).Replace(Environment.NewLine, Environment.NewLine + SuffixIndentation); return info.TrimEnd().ToString(); }
public override string ToString() { StringBuilder info = new StringBuilder(); info.AppendLine("# School: " + this.Name); info.AppendLine(this.classes.ToString<Class>()); return info.TrimEnd().ToString(); }
public override string ToString() { StringBuilder info = new StringBuilder(); info.AppendLine(base.ToString()); info.AppendLine(this.disciplines.ToString<Discipline>()); return info.TrimEnd().ToString(); }
public void Process( XmlReader xmlReader, StringBuilder output, ElementProcessContext elementProcessContext) { if (elementProcessContext.Current.IsPreservingSpace) { output.Append("</").Append(xmlReader.Name).Append(">"); } else if (elementProcessContext.Current.IsSignificantWhiteSpace && !output.IsNewLine()) { output.Append("</").Append(xmlReader.Name).Append(">"); } else if ((elementProcessContext.Current.ContentType == ContentTypeEnum.None) && this.options.RemoveEndingTagOfEmptyElement) { // Shrink the current element, if it has no content. // E.g., <Element> </Element> => <Element /> output = output.TrimEnd(' ', '\t', '\r', '\n'); int bracketIndex = output.LastIndexOf('>'); output.Insert(bracketIndex, '/'); if ((output[bracketIndex - 1] != '\t') && (output[bracketIndex - 1] != ' ') && this.options.SpaceBeforeClosingSlash) { output.Insert(bracketIndex, ' '); } } else if ((elementProcessContext.Current.ContentType == ContentTypeEnum.SingleLineTextOnly) && !elementProcessContext.Current.IsMultlineStartTag) { int bracketIndex = output.LastIndexOf('>'); string text = output.Substring((bracketIndex + 1), (output.Length - bracketIndex - 1)).Trim(); output.Length = (bracketIndex + 1); output.Append(text).Append("</").Append(xmlReader.Name).Append(">"); } else { string currentIndentString = this.indentService.GetIndentString(xmlReader.Depth); if (!output.IsNewLine()) { output.Append(Environment.NewLine); } output.Append(currentIndentString).Append("</").Append(xmlReader.Name).Append(">"); } elementProcessContext.Pop(); }
public override string ToString() { if (string.IsNullOrEmpty(TableName)) throw new ArgumentException("TableName must be set."); var sb = new StringBuilder("INSERT INTO "); AddTableInfo(sb, SchemaName, TableName); sb.Append(" ("); Columns.ForEach(c => sb.AppendFormat(QUOTE_FORMAT, c).Append(",")); sb.TrimEnd(','); sb.Append(") VALUES ("); Columns.ForEach(c => sb.AppendFormat(PARAM_FORMAT, c).Append(",")); sb.TrimEnd(','); sb.Append(")"); return sb.ToString(); }
protected string ToString(string suffix) { StringBuilder info = new StringBuilder(); info.AppendFormat("Name: {0} {1}", this.firstName, this.lastName).AppendLine(); info.AppendLine(suffix).Replace( Environment.NewLine, Environment.NewLine ); return info.TrimEnd().ToString(); }
public void Process(XmlReader xmlReader, StringBuilder output, ElementProcessContext elementProcessContext) { if (elementProcessContext.Current.IsPreservingSpace) { output.Append("</").Append(xmlReader.Name).Append(">"); } else if (elementProcessContext.Current.IsSignificantWhiteSpace && !output.IsNewLine()) { output.Append("</").Append(xmlReader.Name).Append(">"); } // Shrink the current element, if it has no content. // E.g., <Element> </Element> => <Element /> else if (elementProcessContext.Current.ContentType == ContentTypeEnum.NONE && _options.RemoveEndingTagOfEmptyElement) { #region shrink element with no content output = output.TrimEnd(' ', '\t', '\r', '\n'); int bracketIndex = output.LastIndexOf('>'); output.Insert(bracketIndex, '/'); if (output[bracketIndex - 1] != '\t' && output[bracketIndex - 1] != ' ' && _options.SpaceBeforeClosingSlash) { output.Insert(bracketIndex, ' '); } #endregion shrink element with no content } else if (elementProcessContext.Current.ContentType == ContentTypeEnum.SINGLE_LINE_TEXT_ONLY && elementProcessContext.Current.IsMultlineStartTag == false) { int bracketIndex = output.LastIndexOf('>'); string text = output.Substring(bracketIndex + 1, output.Length - bracketIndex - 1).Trim(); output.Length = bracketIndex + 1; output.Append(text).Append("</").Append(xmlReader.Name).Append(">"); } else { string currentIndentString = _indentService.GetIndentString(xmlReader.Depth); if (!output.IsNewLine()) { output.Append(Environment.NewLine); } output.Append(currentIndentString).Append("</").Append(xmlReader.Name).Append(">"); } elementProcessContext.Pop(); }
protected void Page_Load(object sender, EventArgs e) { try { DataEntities ent = new DataEntities(); long chapterid = WS.RequestString("cid").ToInt64(); BookChapter bc = (from l in ent.BookChapter where l.ID == chapterid select l).FirstOrDefault(); bc.ClickCount = bc.ClickCount > 0 ? bc.ClickCount + 1 : 1; ent.SaveChanges(); ent.Dispose(); //写入Cookie List<Cook> cookies = new List<Cook>(); if (Voodoo.Cookies.Cookies.GetCookie("history") != null) { string[] chapters = Voodoo.Cookies.Cookies.GetCookie("history").Value.Split(','); foreach (string chapter in chapters) { string[] arr_chapter = chapter.Split('|'); cookies.Add(new Cook() { id = arr_chapter[0].ToInt64(), time = arr_chapter[1].ToDateTime(), bookid = arr_chapter[2].ToInt32() }); } } cookies = cookies.Where(p => p.bookid != bc.BookID).OrderByDescending(p => p.time).Take(4).ToList(); cookies.Add(new Cook() { id = chapterid, time = DateTime.Now, bookid=bc.BookID }); StringBuilder sb = new StringBuilder(); foreach (Cook c in cookies) { sb.Append(string.Format("{0}|{1}|{2},", c.id, c.time.ToString(), c.bookid.ToS())); } sb = sb.TrimEnd(','); HttpCookie _cookie = new HttpCookie("history", sb.ToString()); _cookie.Expires = DateTime.Now.AddYears(1); Voodoo.Cookies.Cookies.SetCookie(_cookie); }//end try catch { Voodoo.Cookies.Cookies.Remove("history"); } }
public override string ToString() { if (string.IsNullOrEmpty(TableName)) throw new ArgumentException("TableName must be set."); var sb = new StringBuilder("UPDATE "); AddTableInfo(sb, SchemaName, TableName); sb.Append(" SET "); Columns.IterateOver((i, c) => sb.AppendFormat(UPDATE_FORMAT, c).Append(",")); sb.TrimEnd(','); whereHelper.ClauseBuilder = sb; whereHelper.AppendWhere(); return sb.ToString(); }
private string InnerSerialize(CfgNode node) { var meta = CfgMetadataCache.GetMetadata(node.GetType()); var builder = new StringBuilder(); if (meta.All(kv => kv.Value.ListType == null)) { builder.Append("{"); SerializeAttributes(meta, node, builder); builder.TrimEnd(", "); builder.Append(" }"); } else { builder.AppendLine("{"); SerializeAttributes(meta, node, builder); SerializeElements(meta, node, builder, 1); builder.AppendLine(); builder.Append("}"); } return builder.ToString(); }
/// <summary> /// 获取表的Sql脚本 /// </summary> /// <param name="table"></param> /// <returns></returns> public override string GetTableSqlText(SOTable table) { List<SOColumn> columnnList = table.ColumnList; StringBuilder sb = new StringBuilder(); sb.AppendLine("create table [dbo].[" + table.Name + "] ("); foreach(SOColumn item in columnnList) { sb.AppendFormat("\t[{0}] {1}", item.Name, item.NativeType); if (item.PrimaryKey) { sb.Append(" PRIMARY KEY "); } if (item.Identify) { sb.Append(" identity "); } else if (!item.Identify) { sb.Append(" not null "); if (item.DefaultValue != null && item.DefaultValue != "") { sb.Append(" default " + item.DefaultValue); } } sb.Append(",\r\n"); } sb = sb.TrimEnd(",\r\n"); sb.AppendLine("\r\n)"); return sb.ToString() ; }
public override string ToString() { if (string.IsNullOrEmpty(TableName)) throw new ArgumentException("TableName must be set."); var sb = new StringBuilder("SELECT "); if (0 == Columns.Count) { sb.Append("*"); } else { Columns.ForEach(c => sb.Append(c).Append(",")); sb.TrimEnd(','); } sb.Append(" FROM "); AddTableInfo(sb, SchemaName, TableName); whereHelper.ClauseBuilder = sb; whereHelper.AppendWhere(); return sb.ToString(); }
private void ProcessEndElement(XmlReader xmlReader, StringBuilder output) { if (this.ElementProcessStatusStack.Peek().IsPreservingSpace) { output.Append("</").Append(xmlReader.Name).Append(">"); } else if (this.ElementProcessStatusStack.Peek().IsSignificantWhiteSpace && !output.IsNewLine()) { output.Append("</").Append(xmlReader.Name).Append(">"); } // Shrink the current element, if it has no content. // E.g., <Element> </Element> => <Element /> else if ((ContentTypeEnum.None == this.ElementProcessStatusStack.Peek().ContentType) && Options.RemoveEndingTagOfEmptyElement) { #region shrink element with no content output = output.TrimEnd(' ', '\t', '\r', '\n'); int bracketIndex = output.LastIndexOf('>'); output.Insert(bracketIndex, '/'); if ((output[bracketIndex - 1] != '\t') && (output[bracketIndex - 1] != ' ') && Options.SpaceBeforeClosingSlash) { output.Insert(bracketIndex, ' '); } #endregion shrink element with no content } else if ((ContentTypeEnum.SingleLineTextOnly == this.ElementProcessStatusStack.Peek().ContentType) && !this.ElementProcessStatusStack.Peek().IsMultlineStartTag) { int bracketIndex = output.LastIndexOf('>'); string text = output.Substring(bracketIndex + 1, output.Length - bracketIndex - 1).Trim(); output.Length = bracketIndex + 1; output.Append(text).Append("</").Append(xmlReader.Name).Append(">"); } else { string currentIndentString = this.GetIndentString(xmlReader.Depth); if (!output.IsNewLine()) { output.Append(Environment.NewLine); } output.Append(currentIndentString).Append("</").Append(xmlReader.Name).Append(">"); } }
private void ProcessEndElement(XmlReader xmlReader, StringBuilder output) { // Shrink the current element, if it has no content. // E.g., <Element> </Element> => <Element /> if (ContentTypeEnum.NONE == _elementProcessStatusStack.Peek().ContentType && Options.RemoveEndingTagOfEmptyElement) { #region shrink element with no content output = output.TrimEnd(' ', '\t', '\r', '\n'); int bracketIndex = output.LastIndexOf('>'); output.Insert(bracketIndex, '/'); if (output[bracketIndex - 1] != '\t' && output[bracketIndex - 1] != ' ' && Options.SpaceBeforeClosingSlash) { output.Insert(bracketIndex, ' '); } #endregion shrink element with no content } else if (ContentTypeEnum.SINGLE_LINE_TEXT_ONLY == _elementProcessStatusStack.Peek().ContentType && false == _elementProcessStatusStack.Peek().IsMultlineStartTag) { int bracketIndex = output.LastIndexOf('>'); string text = output.Substring(bracketIndex + 1, output.Length - bracketIndex - 1).Trim(); output.Length = bracketIndex + 1; output.Append(text).Append("</").Append(xmlReader.Name).Append(">"); } else { string currentIndentString = GetIndentString(xmlReader.Depth); if (!output.IsNewLine()) { output.Append(Environment.NewLine); } output.Append(currentIndentString).Append("</").Append(xmlReader.Name).Append(">"); } }
private void AddColumns(StringBuilder sb) { var pks = new List<Column>(); Columns.ForEach( c => { AddColumnDefinition(sb, c); sb.AppendLine(","); if (c.Property.Match(ColumnProperty.PrimaryKey)) { pks.Add(c); } }); if (0 != pks.Count) { var pksSb = new StringBuilder(); pks.ForEach(c => pksSb.AppendFormat(PK_FORMAT, c.Name).AppendLine(",")); pksSb.TrimEnd().TrimEnd(','); sb.AppendFormat(PK_BLOCK, pksSb).AppendLine(); } sb.TrimEnd().TrimEnd(','); }
/// <summary> /// 友情链接 /// </summary> /// <returns></returns> public static string getlink(string n) { using (DataEntities ent = new DataEntities()) { StringBuilder sb = new StringBuilder(""); var links =// LinkView.GetModelList("id>0 order by [Index]"); (from l in ent.Link orderby l.Index select l).ToList(); foreach (var l in links) { sb.AppendLine(string.Format("<a href=\"{0}\" target=\"_blank\">{1}</a>|", l.Url, l.LinkTitle)); } return sb.TrimEnd('|').ToString(); } }
/// <summary> /// 轮播Flash /// </summary> /// <param name="ClassID"></param> /// <param name="count"></param> /// <param name="width"></param> /// <param name="height"></param> /// <param name="showTitle"></param> /// <param name="titleLength"></param> /// <param name="interval"></param> /// <param name="ExtSql"></param> /// <param name="Order"></param> /// <returns></returns> public static string cmsflashpic(string ClassID, string count, string width, string height, string showTitle, string titleLength, string interval, string ExtSql, string Order) { DataEntities ent = new DataEntities(); StringBuilder sb = new StringBuilder(); sb.AppendLine("<!--开始FLASH-->"); sb.AppendLine("<div class=\"flash\">"); sb.AppendLine("<script type=\"text/javascript\">"); sb.AppendLine("<!--"); sb.AppendLine(string.Format("var interval_time={0};", interval)); sb.AppendLine(string.Format("var focus_width={0};", width)); sb.AppendLine(string.Format("var focus_height={0};", height)); if (showTitle.ToInt32() > 0) { sb.AppendLine("var text_height=20;"); } else { sb.AppendLine("var text_height=0;"); } sb.AppendLine("var text_align=\"center\";"); sb.AppendLine("var swf_height = focus_height+text_height;"); sb.AppendLine("var swfpath=\"/e/data/images/pixviewer.swf\";"); sb.AppendLine("var swfpatha=\"/e/data/images/pixviewer.swf\";"); StringBuilder sb_pics = new StringBuilder(); StringBuilder sb_links = new StringBuilder(); StringBuilder sb_texts = new StringBuilder(); #region 图片变量 sb_pics.Append("var pics=\""); sb_links.Append("var links=\""); sb_texts.Append("var texts=\""); string str_sql = string.Format("(ZtID='{0}' or ClassID='{1}') and len(TitleImage)>0", ClassID, ClassID); if (ExtSql.Length > 0) { str_sql += " and " + ExtSql; } if (Order.Length > 0) { str_sql += " order by " + Order; } List<News> newses = //NewsView.GetModelList(str_sql, count.ToInt32()); ent.CreateQuery<News>(string.Format("select top {0} * from News where {1}", count, str_sql)).ToList(); newses = newses.Where(p => p.TitleImage.IndexOf(".gif") < 0).ToList();//不支持GIF文件 foreach (News n in newses) { sb_pics.Append(n.TitleImage + "|"); sb_links.Append(BasePage.GetNewsUrl(n, n.GetClass()) + "|"); sb_texts.Append(n.Title.CutString(titleLength.ToInt32()) + "|"); } sb_pics = sb_pics.TrimEnd('|'); sb_links = sb_links.TrimEnd('|'); sb_texts = sb_texts.TrimEnd('|'); sb_pics.Append("\";\n"); sb_links.Append("\";\n"); sb_texts.Append("\";\n"); sb.Append(sb_pics.ToString()); sb.Append(sb_links.ToString()); sb.Append(sb_texts.ToString()); #endregion #region 输出Flash sb.AppendLine("document.write('<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" codebase=\"http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0\" width=\"'+ focus_width +'\" height=\"'+ swf_height +'\">'); "); sb.AppendLine("document.write('<param name=\"movie\" value=\"'+swfpath+'\"><param name=\"quality\" value=\"high\"><param name=\"bgcolor\" value=\"#ffffff\">'); "); sb.AppendLine("document.write('<param name=\"menu\" value=\"false\"><param name=wmode value=\"opaque\">'); "); sb.AppendLine("document.write('<param name=\"FlashVars\" value=\"pics='+pics+'&links='+links+'&texts='+texts+'&borderwidth='+focus_width+'&borderheight='+focus_height+'&textheight='+text_height+'&text_align='+text_align+'&interval_time='+interval_time+'\">'); "); sb.AppendLine("document.write('<embed src=\"'+swfpath+'\" wmode=\"opaque\" FlashVars=\"pics='+pics+'&links='+links+'&texts='+texts+'&borderwidth='+focus_width+'&borderheight='+focus_height+'&textheight='+text_height+'&text_align='+text_align+'&interval_time='+interval_time+'\" menu=\"false\" bgcolor=\"#ffffff\" quality=\"high\" width=\"'+ focus_width +'\" height=\"'+ swf_height +'\" allowScriptAccess=\"sameDomain\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" />');"); sb.AppendLine("document.write('</object>');"); #endregion sb.AppendLine("//-->"); sb.AppendLine("</script>"); sb.AppendLine("</div>"); ent.Dispose(); return sb.ToString(); }