Replace() public method

public Replace ( char oldChar, char newChar ) : StringBuilder
oldChar char
newChar char
return StringBuilder
Exemplo n.º 1
0
        public string Compile(bool minify)
        {
            var js = jslastvalid;
            var html = htmllastvalid;

            // Merge fields
            var output = new StringBuilder(html);
            output.Replace("%resourcepath%", Program.BlobPathResource);
            output.Replace("%build%", Program.Config.Configuration.Build.ToString());
            output.Replace("%buildserial%", Program.Config.Configuration.BuildSerial.ToString());
            html = output.ToString();

            // Minify
            if (minify) {
                js = Minify.MinifyJS(js);
                html = Minify.MinifyHTML(html);
            }

            // Add JS
            var doc = new HtmlDocument();
            doc.LoadHtml(html);
            doc.GetElementbyId("_script_").AppendChild(doc.CreateComment(js));

            return doc.DocumentNode.OuterHtml;
        }
Exemplo n.º 2
0
        protected void InserirControle(string acao)
        {
            try
            {
                System.Text.StringBuilder sql = new System.Text.StringBuilder();
                sql.Append("INSERT INTO cCotaFormaPagamento (ID, Versao, Acao, TimeStamp, UsuarioID) ");
                sql.Append("VALUES (@ID,@V,'@A','@TS',@U)");
                sql.Replace("@ID", this.Control.ID.ToString());

                if (!acao.Equals("I"))
                {
                    this.Control.Versao++;
                }

                sql.Replace("@V", this.Control.Versao.ToString());
                sql.Replace("@A", acao);
                sql.Replace("@TS", DateTime.Now.ToString("yyyyMMddHHmmssffff"));
                sql.Replace("@U", this.Control.UsuarioID.ToString());

                bd.Executar(sql.ToString());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public static void UsingStringBuilder()
        {
            var greetingBuilder =
                new StringBuilder("Hello from all the guys at Wrox Press. ", 150);
            greetingBuilder.AppendFormat("We do hope you enjoy this book as much as we " +
                "enjoyed writing it");

            WriteLine("Not Encoded:\n" + greetingBuilder);

            for (int i = 'z'; i >= 'a'; i--)
            {
                char old1 = (char)i;
                char new1 = (char)(i + 1);
                greetingBuilder = greetingBuilder.Replace(old1, new1);
            }

            for (int i = 'Z'; i >= 'A'; i--)
            {
                char old1 = (char)i;
                char new1 = (char)(i + 1);
                greetingBuilder = greetingBuilder.Replace(old1, new1);
            }

            WriteLine("Encoded:\n" + greetingBuilder);

        }
Exemplo n.º 4
0
        static void Main(string[] args)
        {
            // String s = "hello";
            System.Text.StringBuilder s = new System.Text.StringBuilder("hello");
            long start = DateTime.Now.Ticks;

            for (int i = 0; i < 20000; i++)
            {
                s = s.Append("hello");
            }
            for (int i = 0; i < 11; i++)
            {
                if (i % 2 == 0)
                {
                    // s = s.Replace('o', 'a');
                    s.Replace('o', 'a');
                }
                else
                {
                    // s = s.Replace('a', 'o');
                    s.Replace('a', 'o');
                }
            }
            // s = s.Remove(20, s.Length - 20);
            s.Remove(20, s.Length - 20);
            long end = DateTime.Now.Ticks;

            Console.WriteLine("s: {0}, delay time: {1}", s, end - start);
        }
Exemplo n.º 5
0
        public bool InserirControle(BD bd, string acao)
        {
            try
            {
                System.Text.StringBuilder sql = new System.Text.StringBuilder();
                sql.Append("INSERT INTO cEventoTipos (ID, Versao, Acao, TimeStamp, UsuarioID) ");
                sql.Append("VALUES (@ID,@V,'@A','@TS',@U)");
                sql.Replace("@ID", this.Control.ID.ToString());

                if (!acao.Equals("I"))
                {
                    this.Control.Versao++;
                }

                sql.Replace("@V", this.Control.Versao.ToString());
                sql.Replace("@A", acao);
                sql.Replace("@TS", DateTime.Now.ToString("yyyyMMddHHmmssffff"));
                sql.Replace("@U", this.Control.UsuarioID.ToString());

                int x = bd.Executar(sql.ToString());

                bool result = (x == 1);
                return(result);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /*	Write a program that replaces all occurrences of the sub-string start with the sub-string
        finish in a text file.
            Ensure it will work with large files (e.g. 100 MB).*/
        static void Main()
        {
            string path = "test.txt";
            StringBuilder builder = new StringBuilder();

            try
            {
                StreamReader reader = new StreamReader(path);

                using (reader)
                {
                    string line = reader.ReadLine();

                    while (line != null)
                    {
                        builder.AppendLine(line);
                        line = reader.ReadLine();
                    }

                    reader.Close();
                }

                builder = builder.Replace("start", "finish");
                builder = builder.Replace("Start", "Finish");

                WriteToFile(builder, path);

                Console.WriteLine(builder.ToString());
            }
            catch (Exception)
            {
                Console.WriteLine("Error! File can not be found!");
            }
        }
        public ActionResult Create(Comment comment)
        {
            StringBuilder sbComments = new StringBuilder();

            // Encode the text that is coming from comments textbox
            sbComments.Append(HttpUtility.HtmlEncode(comment.Comments));

            // Only decode bold and underline tags
            sbComments.Replace("&lt;b&gt;", "<b>");
            sbComments.Replace("&lt;/b&gt;", "</b>");
            sbComments.Replace("&lt;u&gt;", "<u>");
            sbComments.Replace("&lt;/u&gt;", "</u>");
            comment.Comments = sbComments.ToString();

            // HTML encode the text that is coming from name textbox
            string strEncodedName = HttpUtility.HtmlEncode(comment.Name);
            comment.Name = strEncodedName;

            if (ModelState.IsValid)
            {
                db.Comments.Add(comment);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(comment);
        }
Exemplo n.º 8
0
        public string SanitizeHTML(string content)
        {
            // Check to see if the incoming contant contains <script> or </script>.
            // These are unsafe HTML tags.
            var tag1 = "<script>";
            var tag2 = "</script>";

            if (content.Contains(tag1) || content.Contains(tag2))
            {
                var sanitize = new StringBuilder(content);

                // The Replace() Method replaces within a substring of an instance all occurances of a specified character
                // with another character
                sanitize.Replace("<script>", "&lt;script&gt;");
                sanitize.Replace("</script>", "&lt/script&gt;");

                // The 'sanitize' is an object of the class Stringbuilder. In order to return a string to the
                // Main method, perform the ToString() method on the object 'sanitize'.
                var result = sanitize.ToString();

                //Assert Assumption that sanitize.ToString() in fact changed
                Debug.Assert(result is string, "The variable 'result' is not a string");
                return result;
            }

            // If the content does not contain any harmful HTML tags, return the content unchanged
            return content;
        }
Exemplo n.º 9
0
 public static byte[] GetBytes(string pkt)
 {
     var r = new StringReader(pkt);
     var sb = new StringBuilder();
     string str;
     while((str = r.ReadLine()) != null) {
         int i = 0;
         try {
             i = Convert.ToInt32(str.Substring(0, 4), 16);
         }
         catch {
         }
         if(i == 0) {
             if(sb.Length > 0) {
                 sb.Replace(" ", "").Replace("-", "").Replace("\r", "").Replace("|", "");
                 return HexToBytes(sb.ToString());
             }
             sb.Length = 0;
         }
         string[] strArr3 = str.Split(':');
         if(strArr3.Length > 2) {
             sb.Append(strArr3[1]);
         }
     }
     if(sb.Length > 0) {
         sb.Replace(" ", "").Replace("-", "").Replace("\r", "").Replace("|", "");
         return HexToBytes(sb.ToString());
     }
     return null;
 }
		public override string GetUpdateCommand()
		{
            var sb = new StringBuilder();
						sb.Append("UPDATE `" + TableName + "` SET ");
			if(spell_id != null)
			{
				sb.AppendLine("`spell_id`='" + spell_id.Value.ToString() + "'");
			}
			if(quest_start != null)
			{
				sb.AppendLine("`quest_start`='" + quest_start.Value.ToString() + "'");
			}
			if(quest_start_active != null)
			{
				sb.AppendLine("`quest_start_active`='" + quest_start_active.Value.ToString() + "'");
			}
			if(quest_end != null)
			{
				sb.AppendLine("`quest_end`='" + quest_end.Value.ToString() + "'");
			}
			if(cast_flags != null)
			{
				sb.AppendLine("`cast_flags`='" + cast_flags.Value.ToString() + "'");
			}
				sb = sb.Replace("\r\n", ", ");
				sb.Append(" WHERE `npc_entry`='" + npc_entry.Value.ToString() + "';");
				sb = sb.Replace(",  WHERE", " WHERE");

            return sb.ToString();
		}
Exemplo n.º 11
0
 static StringBuilder ReplaceHtmlEscapes(StringBuilder sb)
 {
     sb = sb.Replace("\"", "&quot;");
     sb = sb.Replace("<", "&lt;");
     sb = sb.Replace(">", "&gt;");
     return sb;
 }
        /// <summary>
        /// 引数の文字列式を、CANDataの数値に置き換えた文字列を返す
        /// </summary>
        /// <param name="Formula">計算式</param>
        /// <param name="Data">CANデータ</param>
        public string DecodeFormula(string Formula, FormMain.CanData data)
        {
            //計算式
            System.Text.StringBuilder exp = new System.Text.StringBuilder(Formula);

            string str;
            byte   nibble = (byte)(0x0F);

            //式中のLoData1~LoData8の文字列を、数値に置き換える
            for (int i = 0; i < 8; i++)
            {
                //Lower 4bitは、Higher 4bitを0でマスクするだけ
                str = (nibble & data.data[i]).ToString();
                exp = exp.Replace("LoData" + (i + 1).ToString(), str);
            }

            //式中のHiData1~HiData8の文字列を、数値に置き換える
            for (int i = 0; i < 8; i++)
            {
                //Higher 4bitは、4bit右シフトするだけ
                str = (data.data[i] >> 4).ToString();
                exp = exp.Replace("HiData" + (i + 1).ToString(), str);
            }

            //式中のData1~Data8の文字列を、数値に置き換える
            //Data1~Data8の置き換えを、LoDataやHiDataの前に実行すると、LoData1の中のData1のみ置換されてうまく動かない事に注意
            for (int i = 0; i < 8; i++)
            {
                str = data.data[i].ToString();
                exp = exp.Replace("Data" + (i + 1).ToString(), str);
            }

            return(exp.ToString());
        }
Exemplo n.º 13
0
        public override string GetUpdateCommand()
        {
            var sb = new StringBuilder();
                        sb.Append("UPDATE `" + TableName + "` SET ");
            if(parent != null)
            {
                sb.AppendLine("`parent`='" + parent.Value.ToString() + "'");
            }
            if(levelmin != null)
            {
                sb.AppendLine("`levelmin`='" + levelmin.Value.ToString() + "'");
            }
            if(levelmax != null)
            {
                sb.AppendLine("`levelmax`='" + levelmax.Value.ToString() + "'");
            }
            if(scriptname != null)
            {
                sb.AppendLine("`scriptname`='" + scriptname.ToSQL() + "'");
            }
                sb = sb.Replace("\r\n", ", ");
                sb.Append(" WHERE `map`='" + map.Value.ToString() + "';");
                sb = sb.Replace(",  WHERE", " WHERE");

            return sb.ToString();
        }
Exemplo n.º 14
0
		public override string GetUpdateCommand()
		{
            var sb = new StringBuilder();
						sb.Append("UPDATE `" + TableName + "` SET ");
			if(position_x != null)
			{
				sb.AppendLine("`position_x`='" + ((Decimal)position_x.Value).ToString() + "'");
			}
			if(position_y != null)
			{
				sb.AppendLine("`position_y`='" + ((Decimal)position_y.Value).ToString() + "'");
			}
			if(position_z != null)
			{
				sb.AppendLine("`position_z`='" + ((Decimal)position_z.Value).ToString() + "'");
			}
			if(orientation != null)
			{
				sb.AppendLine("`orientation`='" + ((Decimal)orientation.Value).ToString() + "'");
			}
			if(spawntimesecs != null)
			{
				sb.AppendLine("`spawntimesecs`='" + spawntimesecs.Value.ToString() + "'");
			}
			if(comment != null)
			{
				sb.AppendLine("`comment`='" + comment.ToSQL() + "'");
			}
				sb = sb.Replace("\r\n", ", ");
				sb.Append(" WHERE `id`='" + id.Value.ToString() + "';");
				sb = sb.Replace(",  WHERE", " WHERE");

            return sb.ToString();
		}
Exemplo n.º 15
0
        /// <summary>
        /// Obtiene el seteo de parametro que se envia a un store procedure  para Aplication Block,
        /// en forma de batch.-
        ///
        /// </summary>
        /// <param name="pTableName">Nombre de tabla</param>
        /// <param name="pColumnName">Nombre de columna</param>
        /// <param name="pType">Tipo de SQL Server</param>
        ///<example>
        /// <code>
        ///
        ///   #region [[Property_Name]]
        ///   public [TYPENAME] [Property_Name]
        ///     {
        ///      get { return _[Property_Name]; }
        ///      set { _[Property_Name] = value;  }
        ///     }
        ///   #endregion
        ///
        /// </code>
        /// </example>
        /// <returns>string</returns>
        internal static string GetCsharpProperty(Column pColumn)
        {
            string wTypeName = pColumn.DataType.Name.ToUpper();

            if (pColumn.DataType.SqlDataType.ToString().Equals("UserDefinedDataType"))
            {
                wTypeName = UserDefinedTypes.GetUserDefinedType(pColumn.DataType.Name).SystemType.ToUpper();
            }

            System.Text.StringBuilder str = new System.Text.StringBuilder(_Entity_Property_tt);



            switch (wTypeName)
            {
            case "IMAGE":
            case "VARBINARY":
            case "BINARY":

                str = new System.Text.StringBuilder(_Entity_Property_TemplateBinary_tt);
                //str.Replace(CommonConstants.CONST_TYPENAME, "Byte[]");
                break;
            }



            str.Replace(CommonConstants.CONST_TYPENAME, FwkGeneratorHelper.GetCSharpType(pColumn));
            str.Replace("[NullToken]", GetNullableToken(pColumn));
            str.Replace(CommonConstants.CONST_ENTITY_PROPERTY_NAME, pColumn.Name);
            str.AppendLine(Environment.NewLine);

            return(str.ToString());
        }
Exemplo n.º 16
0
        protected void CombineIndex()
        {
            var rootPath = RootPath;

            //file table
            var viewList = new List<string>() { "/Views/Home.html", "/Views/Lobby.html",
                                                "/Views/Games.html", "/Views/Create.html",
                                                "/Views/Community.html", "/Views/Play.html" };

            StringBuilder indexTemplate = new StringBuilder(),
                viewCollection = new StringBuilder();

            //read template
            indexTemplate.Append(File.ReadAllText(rootPath + "/Views/Main.html"));

            foreach (var view in viewList)
            {
                viewCollection.Append(File.ReadAllText(rootPath + view));
            }

            indexTemplate.Replace("@view_placeholder", viewCollection.ToString());

            //dialogs fast hack
            indexTemplate.Replace("@additional_placeholder", File.ReadAllText(rootPath + "/Views/Dialogs.html"));

            using (StreamWriter index = new StreamWriter(rootPath + "/index.html", false))
            {
                index.Write(indexTemplate.ToString());
            }
        }
 static void Main(string[] args)
 {
     //We are given a string containing a list of forbidden words and a text containing
     //some of these words. Write a program that replaces the forbidden words with asterisks.Example:
     //Microsoft announced its next generation PHP compiler today.
     //It is based on .NET Framework 4.0 and is implemented as a dynamic language in CLR.
     //Words: "PHP, CLR, Microsoft"
     //The expected result:
     //********* announced its next generation *** compiler today.
     //It is based on .NET Framework 4.0 and is implemented as a dynamic language in ***.
     string text = "Microsoft announced its next generation PHP compiler today."+
         "It is based on .NET Framework 4.0 and is implemented as a dynamic language in CLR.";
     string wordOne = "Microsoft";
     StringBuilder b = new StringBuilder();
     for (int i = 0; i < wordOne.Length; i++)
         b.Append("*");
     string starsOne = b.ToString();
     b.Clear();
     string wordTwo = "PHP";
     for (int i = 0; i < wordTwo.Length; i++)
         b.Append("*");
     string starsTwo = b.ToString();
     b.Clear();
     string wordThree = "CLR";
     for (int i = 0; i < wordThree.Length; i++)
         b.Append("*");
     string starsThree = b.ToString();
     b.Clear();
     StringBuilder sb = new StringBuilder(text);
     sb.Replace(wordOne, starsOne);
     sb.Replace(wordTwo, starsTwo);
     sb.Replace(wordThree, starsThree);
     Console.WriteLine(sb.ToString());
     //text.IndexOf(wordOne);
 }
Exemplo n.º 18
0
        public static string ToCsv(this DataTable dataTable)
        {
            var sbData = new StringBuilder();

            // Only return Null if there is no structure.
            if (dataTable.Columns.Count == 0)
                return null;

            foreach (var col in dataTable.Columns)
            {
                if (col == null)
                    sbData.Append(",");
                else
                    sbData.Append("\"" + col.ToString().Replace("\"", "\"\"") + "\",");
            }

            sbData.Replace(",", System.Environment.NewLine, sbData.Length - 1, 1);

            foreach (DataRow dr in dataTable.Rows)
            {
                foreach (var column in dr.ItemArray)
                {
                    if (column == null)
                        sbData.Append(",");
                    else
                        sbData.Append("\"" + column.ToString().Replace("\"", "\"\"") + "\",");
                }
                sbData.Replace(",", System.Environment.NewLine, sbData.Length - 1, 1);
            }

            return sbData.ToString();
        }
Exemplo n.º 19
0
 private string FixBase64ForImage(string ImageText)
 {
     System.Text.StringBuilder sbText = new System.Text.StringBuilder(ImageText, ImageText.Length);
     sbText.Replace("/r/n", String.Empty);
     sbText.Replace(" ", String.Empty);
     return(sbText.ToString());
 }
Exemplo n.º 20
0
 /// <summary>
 /// 发送找回密码短信
 /// </summary>
 /// <param name="to">接收手机</param>
 /// <param name="code">验证值</param>
 /// <returns></returns>
 public static bool SendFindPwdMobile(string to, string code)
 {
     StringBuilder body = new StringBuilder(_smsconfiginfo.FindPwdBody);
     body.Replace("{shopname}", _shopconfiginfo.ShopName);
     body.Replace("{code}", code);
     return _ismsstrategy.Send(to, body.ToString());
 }
Exemplo n.º 21
0
        protected override void RegisterClientScripts()
        {
            base.RegisterClientScripts();

            //Style Sheet
            LiteralControl include = new LiteralControl("<link href='css/YUI/calendar.css' rel='stylesheet' type='text/css' />");
            this.Page.Header.Controls.Add(include);

            //scripts
            //RegisterIncludeScript("QueryBuilder", "Sage.SalesLogix.Client.GroupBuilder.jscript.querybuilder.js", true);
            RegisterIncludeScript("Yahoo_yahoo", "jscript/YUI/yahoo.js", false);
            RegisterIncludeScript("Yahoo_event", "jscript/YUI/event.js", false);
            RegisterIncludeScript("TimeObject", "jscript/timeobjs.js", false);

            if (!Page.ClientScript.IsClientScriptBlockRegistered("QBAddCondition"))
            {
                string vScript = ScriptHelper.UnpackEmbeddedResourceToString("jscript.QBAddCondition.js");
                StringBuilder vJS = new StringBuilder(vScript);

                vJS.Replace("@DateValueClientID", DateValue.ClientID + "_TXT");
                vJS.Replace("@DateValueFormat", DateValue.DateFormat);

                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "QBAddCondition", vJS.ToString(), true);
            }
        }
Exemplo n.º 22
0
        public async void WriteAsync(DataTable data, string outputFile)
        {
            StringBuilder fileContent = new StringBuilder();

            foreach (var col in data.Columns)
            {
                fileContent.Append("\"" + col.ToString() + "\";");
            }

            fileContent.Replace(";", System.Environment.NewLine, fileContent.Length - 1, 1);



            foreach (DataRow dr in data.Rows)
            {

                foreach (var column in dr.ItemArray)
                {
                    fileContent.Append("\"" + column.ToString() + "\";");
                }

                fileContent.Replace(";", System.Environment.NewLine, fileContent.Length - 1, 1);
            }

            await Task.Run(() => System.IO.File.WriteAllText(outputFile, fileContent.ToString(), Encoding.Unicode));

        }
Exemplo n.º 23
0
        /// <summary>
        /// 生成播放Flv格式文件的HTML代码
        /// </summary>
        /// <param name="url">Flv格式文件的URL</param>
        /// <param name="width">播放控件的显示宽度</param>
        /// <param name="height">播放控件的显示高度</param>
        /// <returns></returns>
        public static string MakeFlvHtml(string url, int width, int height)
        {
            string fileName = AppPath.CurrentAppPath() + "content\\FlashTemplate.txt";
            var objReader = new StreamReader(fileName);
            string sLine = "";
            var arrText = new ArrayList();
            while (sLine != null)
            {
                sLine = objReader.ReadLine();
                if (sLine != null)
                    arrText.Add(sLine);
            }
            objReader.Close();

            var buff = new StringBuilder();
            foreach (string sOutput in arrText)
            {
                buff.Append(sOutput);
                buff.Append(Environment.NewLine);
            }
            buff.Replace("{source}", url);
            buff.Replace("{width}", width + "");
            buff.Replace("{height}", height + "");

            return buff.ToString();
        }
Exemplo n.º 24
0
	public static void Main(){

		string line;
		string temptab = "      \"temp\" : \"";
		string datetab = "      \"date\" : \"";

		System.IO.StreamReader file = new System.IO.StreamReader("bedroom.json");
		int ctr = 0;
		while((line = file.ReadLine()) != null)
		{
			
			if (line.Contains("temp") || line.Contains("date")){


				StringBuilder b = new StringBuilder(line);
				b.Replace(temptab, "");
				b.Replace(datetab, "");
				b.Replace("\"", "").Replace(",", "");

				if (ctr % 2 ==0){
					Console.Write(b + ",");
				}else {
					Console.WriteLine(b);
				}
				ctr++;
			}	   
		}
		file.Close();
		}
Exemplo n.º 25
0
        /// <summary>
        /// 发送电子邮件
        /// </summary>
        /// <param name="from">发件邮箱地址</param>
        /// <param name="password">邮箱密码</param>
        /// <param name="to">收件人地址</param>
        /// <param name="subject">邮件标题</param>
        /// <param name="body">邮件正文</param>
        /// <param name="smtpHost">SMTP服务器</param>
        /// <returns>发送邮件是否成功</returns>
        public static void SentMail(string from, string loginName, string password, string to, string subject, string body, string smtpHost, string toUser)
        {
            MailMessage message = new MailMessage();
            message.From = new MailAddress(from, "浩奇广告联盟", Encoding.GetEncoding("UTF-8"));

            message.Subject = subject;
            message.IsBodyHtml = true;
            message.BodyEncoding = System.Text.Encoding.UTF8;

            message.To.Add(new MailAddress(to));

            #region 读取模版
            StringBuilder sb = new StringBuilder();
            string t = Voodoo.IO.File.Read("~/Config/mail.htm", Voodoo.IO.File.EnCode.UTF8);
            if (string.IsNullOrEmpty(t))
            {
                t = "";
            }
            sb.Append(t);
            sb = sb.Replace("{Title}", subject);
            sb = sb.Replace("{Content}", body);
            sb = sb.Replace("{ToUser}", toUser);
            sb = sb.Replace("{Time}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            sb = sb.Replace("{ToMail}", to);
            message.Body = sb.ToString();
            #endregion

            //message.Body = body;

            SmtpClient client = new SmtpClient();
            client.Host = smtpHost;
            client.Credentials = new System.Net.NetworkCredential(loginName, password);
            client.Send(message);
        }
Exemplo n.º 26
0
        private static string GenMethodReturn(Table pTable, MethodActionType t)
        {
            StringBuilder wBuilderReturn = null;
            switch (t)
            {
                case MethodActionType.Insert:
                    {
                        Column pPK = FwkGeneratorHelper.GetPrimaryKey(pTable);
                        if (pPK != null)
                        {
                            wBuilderReturn = new StringBuilder(FwkGeneratorHelper.TemplateDocument.GetTemplate("InsertReturn").Content);
                            wBuilderReturn.Replace(CommonConstants.CONST_ENTITY_PROPERTY_NAME, pPK.Name);
                            wBuilderReturn.Replace(CommonConstants.CONST_TYPENAME, FwkGeneratorHelper.GetCSharpType(pPK));

                            return wBuilderReturn.ToString();
                        }
                        else
                            return "  wDataBase.ExecuteNonQuery(wCmd);";
                    }
                case MethodActionType.Update:
                    return "  wDataBase.ExecuteNonQuery(wCmd);";

                case MethodActionType.SearchByParam:

                    wBuilderReturn = new StringBuilder(FwkGeneratorHelper.TemplateDocument.GetTemplate("SearchReturn").Content);

                    return wBuilderReturn.ToString();
                case MethodActionType.Delete:
                    return  "  wDataBase.ExecuteNonQuery(wCmd);";

            }

            return string.Empty;

        }
Exemplo n.º 27
0
 /// <summary>
 /// 安全中心发送验证手机短信
 /// </summary>
 /// <param name="to">接收手机</param>
 /// <param name="code">验证值</param>
 /// <returns></returns>
 public static bool SendSCVerifySMS(string to, string code)
 {
     StringBuilder body = new StringBuilder(_smsconfiginfo.SCVerifyBody);
     body.Replace("{mallname}", _mallconfiginfo.MallName);
     body.Replace("{code}", code);
     return _ismsstrategy.Send(to, body.ToString());
 }
Exemplo n.º 28
0
        public override string GetUpdateCommand()
        {
            var sb = new StringBuilder();
                        sb.Append("UPDATE `" + TableName + "` SET ");
            if(path_rotation0 != null)
            {
                sb.AppendLine("`path_rotation0`='" + ((Decimal)path_rotation0.Value).ToString() + "'");
            }
            if(path_rotation1 != null)
            {
                sb.AppendLine("`path_rotation1`='" + ((Decimal)path_rotation1.Value).ToString() + "'");
            }
            if(path_rotation2 != null)
            {
                sb.AppendLine("`path_rotation2`='" + ((Decimal)path_rotation2.Value).ToString() + "'");
            }
            if(path_rotation3 != null)
            {
                sb.AppendLine("`path_rotation3`='" + ((Decimal)path_rotation3.Value).ToString() + "'");
            }
                sb = sb.Replace("\r\n", ", ");
                sb.Append(" WHERE `guid`='" + guid.Value.ToString() + "';");
                sb = sb.Replace(",  WHERE", " WHERE");

            return sb.ToString();
        }
Exemplo n.º 29
0
        public override string GetUpdateCommand()
        {
            var sb = new StringBuilder();
                        sb.Append("UPDATE `" + TableName + "` SET ");
            if(prev_spell != null)
            {
                sb.AppendLine("`prev_spell`='" + prev_spell.Value.ToString() + "'");
            }
            if(first_spell != null)
            {
                sb.AppendLine("`first_spell`='" + first_spell.Value.ToString() + "'");
            }
            if(rank != null)
            {
                sb.AppendLine("`rank`='" + rank.Value.ToString() + "'");
            }
            if(req_spell != null)
            {
                sb.AppendLine("`req_spell`='" + req_spell.Value.ToString() + "'");
            }
                sb = sb.Replace("\r\n", ", ");
                sb.Append(" WHERE `spell_id`='" + spell_id.Value.ToString() + "';");
                sb = sb.Replace(",  WHERE", " WHERE");

            return sb.ToString();
        }
Exemplo n.º 30
0
        //does the formatting job
        private string FormatCode(string source, bool lineNumbers,
            bool alternate, bool embedStyleSheet, bool subCode)
        {
            //replace special characters
            StringBuilder sb = new StringBuilder(source);

            sb.Replace("&", "&amp;");
            sb.Replace("<", "&lt;");
            sb.Replace(">", "&gt;");
            sb.Replace("\t", string.Empty.PadRight(this.TabSpaces));

            source = sb.ToString();
            
            sb = new StringBuilder();

            if (embedStyleSheet)
            {
                sb.Append("<style type=\"text/css\">\n");
                sb.Append(GetCssString());
                sb.Append("</style>\n");
            }

            //have to use a <pre> because IE below ver 6 does not understand 
            //the "white-space: pre" CSS value
            if (!subCode)
                sb.Append("<pre class=\"csharpcode\">");
            sb.Append(source);
            if (!subCode)
                sb.Append("</pre>");

            return sb.ToString();
        }
		public override string GetUpdateCommand()
		{
            var sb = new StringBuilder();
						sb.Append("UPDATE `" + TableName + "` SET ");
			if(entry_id != null)
			{
				sb.AppendLine("`entry_id`='" + entry_id.Value.ToString() + "'");
			}
			if(modelid != null)
			{
				sb.AppendLine("`modelid`='" + modelid.Value.ToString() + "'");
			}
			if(equipment_id != null)
			{
				sb.AppendLine("`equipment_id`='" + equipment_id.Value.ToString() + "'");
			}
			if(spell_start != null)
			{
				sb.AppendLine("`spell_start`='" + spell_start.Value.ToString() + "'");
			}
			if(spell_end != null)
			{
				sb.AppendLine("`spell_end`='" + spell_end.Value.ToString() + "'");
			}
			if(event_ != null)
			{
				sb.AppendLine("`event`='" + event_.Value.ToString() + "'");
			}
				sb = sb.Replace("\r\n", ", ");
				sb.Append(" WHERE `guid`='" + guid.Value.ToString() + "';");
				sb = sb.Replace(",  WHERE", " WHERE");

            return sb.ToString();
		}
Exemplo n.º 32
0
		public override string GetUpdateCommand()
		{
            var sb = new StringBuilder();
						sb.Append("UPDATE `" + TableName + "` SET ");
			if(racemask != null)
			{
				sb.AppendLine("`racemask`='" + racemask.Value.ToString() + "'");
			}
			if(quest != null)
			{
				sb.AppendLine("`quest`='" + quest.Value.ToString() + "'");
			}
			if(mailtemplateid != null)
			{
				sb.AppendLine("`mailtemplateid`='" + mailtemplateid.Value.ToString() + "'");
			}
			if(senderentry != null)
			{
				sb.AppendLine("`senderentry`='" + senderentry.Value.ToString() + "'");
			}
				sb = sb.Replace("\r\n", ", ");
				sb.Append(" WHERE `event`='" + event_.Value.ToString() + "';");
				sb = sb.Replace(",  WHERE", " WHERE");

            return sb.ToString();
		}
Exemplo n.º 33
0
        //private static string GetHeaderInfo(string text)
        //{
        //    if (text.StartsWith(prefix))
        //    {
        //        int last = text.IndexOf(suffix);
        //        string info = text.Substring(prefix.Length, last);
        //        return info;
        //    }
        //    return string.Empty;
        //}
        public static void DocumentOpenedEvent(Document document)
        {
            //是新打开的文件
            if (newOpenDocNameList.Contains(document.Name))
            {
                //清除新打开的记录
                newOpenDocNameList.Remove(document.Name);

                //只对.cs结尾的文件添加
                if (document.FullName.ToLower().EndsWith(".cs")
                    || document.FullName.ToLower().EndsWith(".js")
                    || document.FullName.ToLower().EndsWith(".css")
                    )
                {

                    //添加文件头信息
                    StringBuilder templete = new StringBuilder(BaseUCSetting.SettingModel.AutoHeaderModel.AutoHeaderTemplete);
                    if (!string.IsNullOrEmpty(templete.ToString()))
                    {
                        templete = templete.Replace("[CurrentTime]", DateTime.Now.ToString());
                        templete = templete.Replace("[User]", Environment.UserName);
                        //templete.Insert(0, prefix + "\n");
                        //templete.Append("\n " + suffix + "\n");

                        VSDocument.Insert(document, 1, 1, templete.ToString());
                    }
                }
            }

            // VsOutput.ShowGeneralMessage(document.Name + " 打开了");
        }
Exemplo n.º 34
0
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    public static string SantiseWindowsPath (string path)
    {
      // 
      // Sanitise a Windows path.
      // 

      string expandedPath;

      if (path.Contains ("~"))
      {
        expandedPath = GetLongPathName (path);
      }
      else
      {
        expandedPath = path;
      }

      StringBuilder workingBuffer = new StringBuilder (expandedPath);

      workingBuffer.Replace (@"\\", "/");

      workingBuffer.Replace (@"\", "/");

      return QuoteIfNeeded (EscapePath (workingBuffer.ToString ()));
    }
Exemplo n.º 35
0
 internal static string Generate_SVC(string pServiceName, string prjName)
 {
     StringBuilder wClassContainer = new StringBuilder(_SVC_tt);
     wClassContainer.Replace(CommonConstants.CONST_SERVICE_NAME, pServiceName);
     wClassContainer.Replace(CommonConstants.CONST_FwkProject_NAME, prjName);
     return wClassContainer.ToString();
 }
Exemplo n.º 36
0
        public override string GetUpdateCommand()
        {
            var sb = new StringBuilder();
                        sb.Append("UPDATE `" + TableName + "` SET ");
            if(x != null)
            {
                sb.AppendLine("`x`='" + ((Decimal)x.Value).ToString() + "'");
            }
            if(y != null)
            {
                sb.AppendLine("`y`='" + ((Decimal)y.Value).ToString() + "'");
            }
            if(icon != null)
            {
                sb.AppendLine("`icon`='" + icon.Value.ToString() + "'");
            }
            if(flags != null)
            {
                sb.AppendLine("`flags`='" + flags.Value.ToString() + "'");
            }
            if(data != null)
            {
                sb.AppendLine("`data`='" + data.Value.ToString() + "'");
            }
            if(icon_name != null)
            {
                sb.AppendLine("`icon_name`='" + icon_name.ToSQL() + "'");
            }
                sb = sb.Replace("\r\n", ", ");
                sb.Append(" WHERE `entry`='" + entry.Value.ToString() + "';");
                sb = sb.Replace(",  WHERE", " WHERE");

            return sb.ToString();
        }
Exemplo n.º 37
0
        private string FixBase64ForImage(string Image)
        {
            var sbText = new System.Text.StringBuilder(Image, Image.Length);

            sbText.Replace("\r\n", String.Empty);
            sbText.Replace(" ", String.Empty);
            return(sbText.ToString());
        }
Exemplo n.º 38
0
 public static string FraudNotification(string content, string AuthCode)
 {
     //[SITEALIAS];[TRANSACTIONID]
     sBody = new StringBuilder(content);
     sBody.Replace("[TRANSACTIONID]", AuthCode);
     sBody.Replace("[SITEALIAS]", SiteAlias);
     return(sBody.ToString());
 }
Exemplo n.º 39
0
        /// <summary>
        /// Clears clipboard and copy a HTML fragment to the clipboard, providing additional meta-information.
        /// </summary>
        /// <param name="htmlFragment">a html fragment</param>
        /// <param name="title">optional title of the HTML document (can be null)</param>
        /// <param name="sourceUrl">optional Source URL of the HTML document, for resolving relative links (can be null)</param>
        public static void CopyToClipboard(string htmlFragment, string title, Uri sourceUrl)
        {
            if (title == null)
            {
                title = "From Clipboard";
            }

            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            // Builds the CF_HTML header. See format specification here:
            // http://msdn.microsoft.com/library/default.asp?url=/workshop/networking/clipboard/htmlclipboard.asp

            // The string contains index references to other spots in the string, so we need placeholders so we can compute the offsets.
            // The <<<<<<<_ strings are just placeholders. We'll backpatch them actual values afterwards.
            // The string layout (<<<) also ensures that it can't appear in the body of the html because the <
            // character must be escaped.
            string header =
                @"Version:0.9
StartHTML:<<<<<<<1
EndHTML:<<<<<<<2
StartFragment:<<<<<<<3
EndFragment:<<<<<<<4
";

            sb.Append(header);

            if (sourceUrl != null)
            {
                sb.AppendFormat("SourceURL:{0}", sourceUrl);
            }
            int startHtml = sb.Length;

            const string pre = @"<html><body><!--StartFragment-->";

            sb.Append(pre);
            int fragmentStart = sb.Length;

            sb.Append(htmlFragment);
            int fragmentEnd = sb.Length;

            const string post = @"<!--EndFragment--></body></html>";

            sb.Append(post);
            int endHtml = sb.Length;

            // Backpatch offsets
            sb.Replace("<<<<<<<1", To8DigitString(startHtml));
            sb.Replace("<<<<<<<2", To8DigitString(endHtml));
            sb.Replace("<<<<<<<3", To8DigitString(fragmentStart));
            sb.Replace("<<<<<<<4", To8DigitString(fragmentEnd));


            // Finally copy to clipboard.
            string data = sb.ToString();

            Clipboard.Clear();
            Clipboard.SetText(data, TextDataFormat.Html);
        }
 private void FilterWindowsText(System.Text.StringBuilder strWindowsText)
 {
     if (strWindowsText.Length > 225)
     {
         strWindowsText = strWindowsText.Append(" ¡­");
     }
     strWindowsText = strWindowsText.Replace("  ", "");
     strWindowsText = strWindowsText.Replace('\n', '¨L');
 }
Exemplo n.º 41
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="pTypeNameOld"></param>
        /// <param name="pTypeNameNew"></param>
        /// <param name="pXml"></param>
        /// <returns></returns>
        public static string ReplaseTypeNameForSerialization(Type pTypeNameOld, Type pTypeNameNew, String pXml)
        {
            System.Text.StringBuilder strXml = new System.Text.StringBuilder(pXml);

            strXml.Replace("<" + pTypeNameOld.Name + ">", "<" + pTypeNameNew.Name + ">");
            strXml.Replace("</" + pTypeNameOld.Name + @">", "</" + pTypeNameNew.Name + @">");

            return(strXml.ToString());
        }
Exemplo n.º 42
0
    private string SanitizeReceivedJson(string uglyJson)
    {
        var sb = new System.Text.StringBuilder(uglyJson);

        sb.Replace("\\\t", "\t");
        sb.Replace("\\\n", "\n");
        sb.Replace("\\\r", "\r");
        return(sb.ToString());
    }
Exemplo n.º 43
0
        public static void CopyToClipboard(string htmlFragment, string title, Uri sourceUrl)
        {
            if (title == null)
            {
                title = "From Clipboard";
            }

            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            string header =
                @"Format:HTML Format
                            Version:1.0
                            StartHTML:<<<<<<<1
                            EndHTML:<<<<<<<2
                            StartFragment:<<<<<<<3
                            EndFragment:<<<<<<<4
                            StartSelection:<<<<<<<3
                            EndSelection:<<<<<<<3
                            ";

            string pre =
                @"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">
                    <HTML><HEAD><TITLE>" + title + @"</TITLE>
                    <meta http-equiv=""content-type"" content=""text/html; charset=" + Encoding.UTF8.WebName + @""" />
                    </HEAD><BODY><!--StartFragment-->";

            string post = @"<!--EndFragment--></BODY></HTML>";

            sb.Append(header);
            if (sourceUrl != null)
            {
                sb.AppendFormat("SourceURL:{0}", sourceUrl);
            }
            int startHTML = sb.Length;

            sb.Append(pre);
            int fragmentStart = sb.Length;

            sb.Append(htmlFragment);
            int fragmentEnd = sb.Length;

            sb.Append(post);
            int endHTML = sb.Length;

            // Backpatch offsets
            sb.Replace("<<<<<<<1", To8DigitString(startHTML));
            sb.Replace("<<<<<<<2", To8DigitString(endHTML));
            sb.Replace("<<<<<<<3", To8DigitString(fragmentStart));
            sb.Replace("<<<<<<<4", To8DigitString(fragmentEnd));

            //Finally copy to clipboard.
            Clipboard.Clear();
            DataObject obj = new DataObject();

            obj.SetData(DataFormats.Html, new System.IO.MemoryStream(Encoding.UTF8.GetBytes(sb.ToString())));
            Clipboard.SetDataObject(obj, true);
        }
Exemplo n.º 44
0
 public static string AdminRefundNotification(string content, SupportDetail supportdetail)
 {
     //[SITEALIAS];[ACTION];[ORDERNUMBER];[FULLNAME]
     sBody = new StringBuilder(content);
     sBody.Replace("[FULLNAME]", supportdetail.SupportRequest.User.FirstName + " " + supportdetail.SupportRequest.User.LastName);
     sBody.Replace("[ORDERNUMBER]", string.IsNullOrEmpty(supportdetail.SupportRequest.OrderDetail.ExternalOrderID) ? "Invoice# " + supportdetail.SupportRequest.OrderDetail.InvoiceNumber : "Order# " + supportdetail.SupportRequest.OrderDetail.ExternalOrderID);
     sBody.Replace("[INCIDENTID]", "SSL-" + supportdetail.SupportRequest.ID);
     sBody.Replace("[SITEALIAS]", SiteAlias);
     return(sBody.ToString());
 }
Exemplo n.º 45
0
        internal static string GenerateFilename(string pattern)
        {
            DateTime now = DateTime.Now;

            System.Text.StringBuilder result = new System.Text.StringBuilder();
            int expressionStart = -1;

            for (int x = 0; x < pattern.Length; x++)
            {
                switch (pattern.Substring(x, 1))
                {
                case "<":
                    expressionStart = x;
                    break;

                case ">":
                    if (expressionStart != -1)
                    {
                        result.Append(
                            now.ToString(pattern.Substring(expressionStart + 1, x - expressionStart - 1), CultureInfo.CurrentCulture)
                            );
                        expressionStart = -1;
                    }
                    break;

                default:
                    if (expressionStart == -1)
                    {
                        result.Append(pattern.Substring(x, 1));
                    }
                    break;
                }
            }

            // remove invalid path chars
            char[] invalidChars = Path.GetInvalidPathChars();
            foreach (char c in invalidChars)
            {
                result = result.Replace(c, '-');
            }
            char[] moreInvalidChars = new char[] { '\\', '/', ':', '*', '?', '"', '<', '>', '|' };
            foreach (char c in moreInvalidChars)
            {
                result = result.Replace(c, '-');
            }

            string temp = result.ToString().Trim();

            if (temp.Length == 0)
            {
                temp = DateTime.Now.ToString("webcam <yyyy-MM-dd HH.mm>.jpg", CultureInfo.InvariantCulture);
            }

            return(temp);
        }
Exemplo n.º 46
0
 public static string ContactUsEmail(string content, dynamic d)
 {
     string[] strVal = d as string[];
     sBody = new StringBuilder(content);
     sBody.Replace("[COMPANYNAME]", Convert.ToString(strVal[0]));
     sBody.Replace("[FULLNAME]", Convert.ToString(strVal[1]));
     sBody.Replace("[PHONE]", Convert.ToString(strVal[2]));
     sBody.Replace("[EMAIL]", Convert.ToString(strVal[3]));
     sBody.Replace("[COMMENTS]", Convert.ToString(strVal[4]));
     return(sBody.ToString());
 }
Exemplo n.º 47
0
        public static string ChangePassword(string content, User rowUser, string SiteSupportEmail)
        {
            sBody = new StringBuilder(content);
            sBody.Replace("[FULLNAME]", rowUser.FirstName + " " + rowUser.LastName);
            sBody.Replace("[SITEALIAS]", SiteAlias);
            sBody.Replace("[SUPPORTMAIL]", SiteSupportEmail);
            sBody.Replace("[DATE]", Convert.ToString(DateTimeWithZone.CurrentTimeZone));


            return(sBody.ToString());
        }
Exemplo n.º 48
0
        public static string SafeJson(string json)
        {
            StringBuilder sb = new System.Text.StringBuilder(json);

            sb = sb.Replace("\t", "");
            sb = sb.Replace("\r", "");
            sb = sb.Replace("\n", "");
            sb = sb.Replace("\f", "");
            sb = sb.Replace(@"\", @"\\");
            return(sb.ToString());
        }
Exemplo n.º 49
0
        public string createTags(string tags)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder(tags.ToLower());
            sb.Replace("\"", " ");
            sb.Replace(",", " ");
            sb.Replace("&amp", " ");
            sb.Replace("&", " ");
            string result = UTF8_Encode(removeHTMLtab(sb.ToString(), ""));

            return(result);
        }
Exemplo n.º 50
0
 public static string FixBase64ForImage(string image)
 {
     try
     {
         System.Text.StringBuilder sbText = new System.Text.StringBuilder(image, image.Length);
         sbText.Replace("\r\n", String.Empty); sbText.Replace(" ", String.Empty);
         return(sbText.ToString());
     }
     catch (Exception)
     {
         throw;
     }
 }
        /// <summary>
        /// ファイル名などに使えない特殊文字を別の文字に置き換える
        /// </summary>
        /// <param name="orig"></param>
        /// <returns></returns>
        private static string filterSpecialChar(string orig)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder(orig);
            sb.Replace("(", "(");
            sb.Replace(")", ")");
            // sb.Replace("(", "〈");
            // sb.Replace(")", "〉");
            sb.Replace(" ", "_");
            // sb.Replace("-", "_");
            sb.Replace("^", "^");
            sb.Replace("?", "");

            return(sb.ToString());
        }
Exemplo n.º 52
0
        public static string ForgotPassword(string content, User rowUser, string action = "")
        {
            //[SITEALIAS];[RESETLINK];[FULLNAME]
            sBody = new StringBuilder(content);

            string strPath = SiteAlias + (!string.IsNullOrEmpty(action) ? action : "passwordreset?token=");

            strPath += HttpUtility.HtmlEncode(WBSSLStore.CryptorEngine.Encrypt(rowUser.ID.ToString() + SettingConstants.Seprate + rowUser.PasswordHash, true));

            sBody.Replace("[RESETLINK]", strPath);
            sBody.Replace("[FULLNAME]", rowUser.FirstName + " " + rowUser.LastName);
            sBody.Replace("[SITEALIAS]", SiteAlias);
            return(sBody.ToString());
        }
Exemplo n.º 53
0
        public static string RFQEmails(string content, int type, dynamic d)
        {
            string[] strVal = d as string[];
            sBody = new StringBuilder(content);
            sBody.Replace("[FULLNAME]", Convert.ToString(strVal[0]));
            sBody.Replace("[PHONE]", Convert.ToString(strVal[1]));
            sBody.Replace("[EMAIL]", Convert.ToString(strVal[2]));

            if (type != 0)
            {
                sBody.Replace("[COMMENTS]", Convert.ToString(strVal[3]));
            }

            return(sBody.ToString());
        }
Exemplo n.º 54
0
        /// <summary>
        /// 将Html代码转换为纯文本
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        public static string ToTextString(string html)
        {
            if (string.IsNullOrEmpty(html))
            {
                return(html);
            }

            System.Text.StringBuilder sb = new System.Text.StringBuilder(System.Web.HttpContext.Current.Server.HtmlDecode(html));
            sb.Replace("<br>", "\r\n");
            sb.Replace("&nbsp;", " ");

            sb.Replace("<", "&lt;");
            sb.Replace(">", "&gt;");
            return(sb.ToString());
        }
Exemplo n.º 55
0
        /// <summary>
        /// 将纯文本转换为Html代码
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string ToHtmlString(string text)
        {
            if (string.IsNullOrEmpty(text))
            {
                return(text);
            }

            System.Text.StringBuilder sb = new System.Text.StringBuilder(System.Web.HttpContext.Current.Server.HtmlEncode(text));

            sb.Replace("&lt;", "<");
            sb.Replace("&gt;", ">");
            sb.Replace("\r\n", "<br>");
            sb.Replace(" ", "&nbsp;");
            return(sb.ToString());
        }
Exemplo n.º 56
0
        public static string escapeXML(string orig)
        {
            if (orig == null)
            {
                return("");
            }

            System.Text.StringBuilder sb = new System.Text.StringBuilder(orig);
            sb.Replace("&", "&amp;");
            sb.Replace("<", "&lt;");
            sb.Replace(">", "&gt;");
            sb.Replace("\"", "&quot;");
            sb.Replace("'", "&apos;");
            return(sb.ToString());
        }
Exemplo n.º 57
0
        static void Main(string[] args)
        {
            var builder = new System.Text.StringBuilder("Hello World");

            builder.Append('-', 10);
            builder.AppendLine();
            builder.Append("Header");
            builder.AppendLine();
            builder.Append('-', 10);

            // Or because Append returns type StringBuilder method can be chained together
            //builder.Append('-', 10)
            //       .AppendLine()
            //       .Append("Header")
            //       .AppendLine()
            //       .Append('-', 10);


            // The following methods can also be chained together as well.
            builder.Replace('-', '+');

            builder.Remove(0, 10);

            builder.Insert(0, new string('-', 10));

            Console.WriteLine(builder);

            // Can access StringBuilder just like array or string
            Console.WriteLine("First Char: " + builder[0]);
        }
Exemplo n.º 58
0
        /// <summary>
        /// Converts a string to camel case.
        /// Camel case is defined as "compound words or phrases in which the
        /// elements are joined without spaces, with each element//s initial letter
        /// capitalized within the compound and the first letter is either upper or
        /// lower case".
        /// </summary>
        /// <param name="value">
        /// The string to convert.
        /// </param>
        /// <param name="lowerCamelCase">
        /// Denotes whether lower camel case is required.
        /// When set to true, the first character of the string will be lower case,
        /// otherwise the first character of the string will be uppercase.
        /// </param>
        /// <returns>
        /// A string in camel case format.
        /// </returns>
        /// <remarks>
        /// camelCase (camel case or camel-case)—also known as medial capitals[1]—is
        /// the practice of writing compound words or phrases in which the elements
        /// are joined without spaces, with each element//s initial letter capitalized
        /// within the compound and the first letter is either upper or lower case—as
        /// in "LaBelle", BackColor, "McDonald//s", LeeAndrea, or "iPod". The name
        /// comes from the uppercase "bumps" in the middle of the compound word,
        /// suggestive of the humps of a camel. The practice is known by many
        /// other names.
        /// </remarks>
        public static string ToCamelCase(this string value, bool lowerCamelCase = false)
        {
            var result = new System.Text.StringBuilder();

            if (value != null)
            {
                var blnNextOneShouldBeUpper = false;
                for (var id = 0; id <= (value.Trim().Length - 1); id++)
                {
                    var str = value.Substring(id, 1);
                    if (id == 0)
                    {
                        result.Append(lowerCamelCase ? str.ToLower() : str.ToUpper());
                    }
                    else
                    {
                        result.Append(blnNextOneShouldBeUpper ? str.ToUpper() : str.ToLower());
                        blnNextOneShouldBeUpper = str == " ";
                    }
                }
            }

            result = result.Replace(" ", string.Empty);
            return(result.ToString());
        }
Exemplo n.º 59
0
        public override bool CreateExcelFile(CompositeDataBoundControl dataBound, string filename, HttpResponse Response)
        {
            try
            {
                GridView gv = (GridView)dataBound;
                this.RemoveHeaderFormat(gv);

                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                StringWriter   sw            = new StringWriter(sb);
                HtmlTextWriter htw           = new HtmlTextWriter(sw);
                Page           page          = new Page();
                HtmlForm       form          = new HtmlForm();
                gv.EnableViewState         = false;
                page.EnableEventValidation = false;
                page.DesignerInitialize();
                page.Controls.Add(form);
                form.Controls.Add(gv);
                page.RenderControl(htw);

                Response.Clear();
                Response.Buffer      = true;
                Response.ContentType = "application/vnd.ms-excel";
                Response.AddHeader("Content-Disposition", "attachment;filename=" + filename + ".xls");
                Response.Charset = "UTF-8";
                sb = sb.Replace("<caption>", string.Empty).Replace("Resultado", string.Empty).Replace("</caption>", string.Empty);
                Response.Write(sb.ToString());
                Response.End();
                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
Exemplo n.º 60
0
        //public static string GenPagging(PagingEntity pagingInfo)
        //{
        //    int pageNum = (int)Math.Ceiling((double)pagingInfo.Count / pagingInfo.PageSize);
        //    if (pageNum * pagingInfo.PageSize < pagingInfo.Count)
        //    {
        //        pageNum++;
        //    }
        //    pagingInfo.LinkSite = pagingInfo.LinkSite.TrimEnd('/') + "/";
        //    string buildlink = "<li class='inline ml5'><a href='{0}{1}' class='pt5 pb5 pl10 border-gray pr10 none-underline box-shadow radius {2}' title='{4}'>{3}</a></li>";

        //    const string strTrang = "p";
        //    string currentPage = pagingInfo.PageIndex.ToString(); // trang tiện tại
        //    string htmlPage = "";
        //    int iCurrentPage = 0;
        //    if (pagingInfo.PageIndex <= 0) iCurrentPage = 1;
        //    else iCurrentPage = pagingInfo.PageIndex;
        //    string active;
        //    if (pageNum <= 4)
        //    {
        //        if (pageNum != 1)
        //        {
        //            for (int i = 1; i <= pageNum; i++)
        //            {
        //                active = currentPage == i.ToString() ? "active" : "";
        //                if (i == 1) htmlPage += String.Format(buildlink, pagingInfo.LinkSite.TrimEnd('/'), string.Empty, active, i, "Trang " + i);
        //                else htmlPage += String.Format(buildlink, pagingInfo.LinkSite, strTrang + i, active, i, "Trang " + i);
        //            }
        //        }
        //    }
        //    else
        //    {
        //        if (iCurrentPage > 1)
        //        {
        //            htmlPage += String.Format(buildlink, pagingInfo.LinkSite.TrimEnd('/'), string.Empty, "no-number", "Trang đầu", "Trang đầu");

        //        }
        //        else
        //        {
        //            for (int i = 1; i <= 3; i++)
        //            {
        //                active = currentPage == i.ToString() ? "active" : "";
        //                if (i == 1) htmlPage += String.Format(buildlink, pagingInfo.LinkSite.TrimEnd('/'), string.Empty, active, i, "Trang " + i);
        //                else htmlPage += String.Format(buildlink, pagingInfo.LinkSite, strTrang + i, active, i, "Trang " + i);
        //            }
        //            htmlPage += String.Format(buildlink, pagingInfo.LinkSite, strTrang + "4", "no-number", "Trang tiếp", "Trang tiếp");
        //        }
        //        if (iCurrentPage > 1 && iCurrentPage < pageNum)
        //        {
        //            if (iCurrentPage > 2)
        //            {
        //                if (iCurrentPage - 2 == 1)
        //                    htmlPage += String.Format(buildlink, pagingInfo.LinkSite.TrimEnd('/'), string.Empty, "no-number", "Trang trước", "Trang trước");
        //                else htmlPage += String.Format(buildlink, pagingInfo.LinkSite, strTrang + (iCurrentPage - 2), "no-number", "Trang trước", "Trang trước");

        //            }
        //            for (int i = (iCurrentPage - 1); i <= (iCurrentPage + 1); i++)
        //            {
        //                active = currentPage == i.ToString() ? "active" : "";
        //                if (i == 1) htmlPage += String.Format(buildlink, pagingInfo.LinkSite.TrimEnd('/'), string.Empty, active, i, "Trang " + i);
        //                else htmlPage += String.Format(buildlink, pagingInfo.LinkSite, strTrang + i, active, i, "Trang " + i);
        //            }
        //            if (iCurrentPage <= pageNum - 2)
        //            {
        //                htmlPage += String.Format(buildlink, pagingInfo.LinkSite, strTrang + (iCurrentPage + 2), "no-number", "Trang tiếp", "Trang tiếp");
        //            }
        //        }
        //        int intCurrentPage = 0;
        //        int.TryParse(currentPage, out intCurrentPage);
        //        if (intCurrentPage == 0) intCurrentPage = 1;
        //        if (intCurrentPage < pageNum)
        //        {
        //            htmlPage += String.Format(buildlink, pagingInfo.LinkSite, strTrang + pageNum, "no-number", "Trang cuối", "Trang cuối");
        //        }
        //        else
        //        {
        //            if (pageNum - 4 == 1)
        //                htmlPage += String.Format(buildlink, pagingInfo.LinkSite.TrimEnd('/'), string.Empty, "no-number", "Trang trước", "Trang trước");
        //            else
        //                htmlPage += String.Format(buildlink, pagingInfo.LinkSite, strTrang + (pageNum - 4), "no-number", "Trang trước", "Trang trước");
        //            int j = 3;
        //            for (int i = pageNum; i >= pageNum - 3; i--)
        //            {
        //                active = currentPage == (pageNum - j).ToString() ? "active" : "";
        //                if (pageNum - j == 1)
        //                    htmlPage += String.Format(buildlink, pagingInfo.LinkSite, strTrang + (pageNum - j), active, pageNum - j, "Trang " + (pageNum - j));
        //                else
        //                    htmlPage += String.Format(buildlink, pagingInfo.LinkSite, strTrang + (pageNum - j), active, pageNum - j, "Trang " + (pageNum - j));
        //                j--;
        //            }
        //        }
        //    }
        //    htmlPage = string.Format("<div class='page'><ul class='paging tr'>{0}</ul></div>", htmlPage);
        //    return htmlPage;
        //}

        public static string MySubStringNotHtml(string input, int length)
        {
            if (string.IsNullOrEmpty(input))
            {
                return(string.Empty);
            }

            String regex  = "<a(.*?)</a>";
            Match  math   = Regex.Match(input, regex);
            String result = string.Empty;

            if (math.Success)
            {
                result = math.Groups[0].Value;
                input  = Regex.Replace(input, "<a(.*?)</a>", "_temphtml_");
            }
            System.Text.StringBuilder __returnStr = new System.Text.StringBuilder();
            string[] __separator = new string[] { " " };
            string[] __arrStr    = input.Split(__separator, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < __arrStr.Length; i++)
            {
                if (i < length && i < __arrStr.Length)
                {
                    __returnStr.Append(__arrStr[i] + " ");
                }
                else
                {
                    break;
                }
            }
            return(__returnStr.Replace("_temphtml_", result).ToString());
        }