Remove() public method

public Remove ( int startIndex, int length ) : StringBuilder
startIndex int
length int
return StringBuilder
Example #1
1
        static void Main()
        {
            string inputStr = Console.ReadLine();
            string multipleString = "";
            while (inputStr != "END")
            {
                multipleString += inputStr;
                inputStr = Console.ReadLine();
            }
            string pattern = @"(?<=<a).*?\s*href\s*=\s*((""[^""]*""(?=>))|('[^']*'(?=>))|([\w\/\:\.]+\.\w{3})|(\/[^'""]*?(?=>)))";
               //string pattern = @"(?s)(?:<a)(?:[\s\n_0-9a-zA-Z=""()]*?.*?)(?:href([\s\n]*)?=(?:['""\s\n]*)?)([a-zA-Z:#\/._\-0-9!?=^+]*(\([""'a-zA-Z\s.()0-9]*\))?)(?:[\s\na-zA-Z=""()0-9]*.*?)?(?:\>)";
            MatchCollection collection = Regex.Matches(multipleString, pattern);
            List<string> resultStrings = new List<string>();
            foreach (Match match in collection)
            {
                StringBuilder tempStr = new StringBuilder(match.Groups[2].Value);
                if (tempStr[0] == '"' || tempStr[0] == '\'')
                {
                    tempStr.Remove(0,1);
                }
                if (tempStr[tempStr.Length-1] == '"' || tempStr[tempStr.Length-1] == '\'')
                {
                    tempStr.Remove(tempStr.Length-1,1);
                }
                resultStrings.Add(tempStr.ToString());
                Console.WriteLine(tempStr);

            }
            //Console.WriteLine(string.Join("\r\n",resultStrings));
        }
Example #2
0
        public static string ReturnJson(bool bResult, int strErrorCode, string strErrorMsg, Dictionary <string, object> Dictionary)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("{");
            sb.Append(string.Format("\"result\":\"{0}\",\"errMsg\":\"{1}\", \"errCode\":\"{2}\",", Convert.ToString(bResult).ToLower(), strErrorMsg, strErrorCode));
            sb.Append("\"data\":[{");
            try
            {
                if (Dictionary != null && Dictionary.Keys.Count > 0)
                {
                    foreach (KeyValuePair <string, object> Temp in Dictionary)
                    {
                        sb.Append(string.Format("\"{0}\":\"{1}\",", Temp.Key, Convert.ToString(Temp.Value)));
                    }
                    sb.Remove(sb.Length - 1, 1);
                }
                sb.Append("}]}");
            }
            catch
            {
                sb.Remove(0, sb.Length);
                sb.Append("{");
                sb.Append(string.Format("\"result\":\"{0}\",\"errMsg\":\"{1}\", \"errCode\":\"{2}\",", Convert.ToString(bResult).ToLower(), strErrorMsg, strErrorCode));
                sb.Append("\"data\":[]");
                sb.Append("}");
            }

            return(sb.ToString().Replace("\r", "").Replace("\n", ""));
        }
Example #3
0
        private void _run()
        {
            _log.Info("sina level1 行情接收器开始运行");
            bool isSent = false;
            if (aliases.Count != 0)
            {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < aliases.Count; i++)
                {
                    isSent = false;
                    sb.Append(aliases[i]);
                    sb.Append(",");

                    if (i % n == (n - 1))
                    {
                        sb.Remove(sb.Length - 1, 1);
                        t_ReqSymbols.Add(sb.ToString());
                        sb.Clear();
                        isSent = true;
                    }
                }
                if (!isSent)
                {
                    sb.Remove(sb.Length - 1, 1);
                    t_ReqSymbols.Add(sb.ToString());
                }
            }

            foreach (string item in t_ReqSymbols)
            {
                _sendRequest(item);
            }
        }
Example #4
0
        /// 某个用户带权限功菜单列表
        /// </summary>
        /// <param name="guid">用户guid</param>
        /// <returns></returns>
        public string getJsonTree(string guid)
        {
            DataTable dt_main = dal.GetRole_menu_right("fatherid=0 and ui_role_id='" + guid + "'  order by menuorder").Tables[0];

            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("[{\"text\":\"导航菜单\",\"children\":[");
            if (dt_main.Rows.Count > 0)
            {
                for (int i = 0; i < dt_main.Rows.Count; i++)
                {
                    sb.Append("{\"id\":\"" + dt_main.Rows[i]["ui_menu_id"].ToString() + "\",\"text\":\"" + dt_main.Rows[i]["menuname"].ToString() + "\",\"iconCls\":\"" + dt_main.Rows[i]["icon"].ToString() + "\",\"children\":[");
                    //
                    string    sqlwhere = string.Format("fatherid={0} and  ui_role_id='{1}' order by menuorder", dt_main.Rows[i]["ui_menu_id"].ToString(), guid);
                    DataTable dt_list  = dal.GetRole_menu_right(sqlwhere).Tables[0];
                    for (int j = 0; j < dt_list.Rows.Count; j++)
                    {
                        sb.Append("{\"id\":\"" + dt_list.Rows[j]["ui_menu_id"].ToString() + "\",\"text\":\"" + dt_list.Rows[j]["menuname"].ToString() + "\",\"iconCls\":\"" + dt_list.Rows[j]["icon"].ToString() + "\",\"checked\":" + dt_list.Rows[j]["roleright"].ToString() + "},");
                    }
                    if (dt_list.Rows.Count > 0)
                    {
                        sb.Remove(sb.Length - 1, 1);
                    }
                    sb.Append("]},");
                }
                sb.Remove(sb.Length - 1, 1);
            }

            sb.Append("]}]");
            return(sb.ToString());
        }
        public static string DataTableToJson(DataTable table, params string[] columnsToParse)
        {
            if (table == null || table.Rows.Count == 0)
                return "{\"total\":0,\"rows\":[]}";

            StringBuilder sb = new StringBuilder();
            sb.Append("{\"total\":").Append(table.Rows.Count).Append(",");
            sb.Append("\"rows\":[");

            foreach (DataRow row in table.Rows)
            {
                sb.Append("{");

                if (columnsToParse.Count() == 0)
                {
                    columnsToParse = ParserHelper.GetColumnName(table);
                }
                foreach (string column in columnsToParse)
                {
                    string m_ColumnValue = GetConfigInfo.FormatDecimalPlaces(row[column], table.Columns[column].DataType);  //增加保留小数点功能
                    sb.Append("\"").Append(column).Append("\":").Append("\"").Append(m_ColumnValue.Trim()).Append("\",");
                }
                sb.Remove(sb.Length - 1, 1);
                sb.Append("},");
            }
            sb.Remove(sb.Length - 1, 1);
            sb.Append("]}");

            return sb.ToString();
        }
Example #6
0
        public static string FromUpcA(string value)
        {
            if (!Regex.IsMatch(value, @"^[01]\d{2}([012]0{4}\d{3}|[3-9]0{4}\d{2}|\d{4}0{4}\d|\d{5}0{4}[5-9])"))
                throw new ArgumentException("UPC A code cannot be compressed.");

            StringBuilder result = new StringBuilder(value);

            if (result[5] != '0')
                result.Remove(6, 4);
            else if (result[4] != '0')
            {
                result.Remove(5, 5);
                result.Insert(6, "4");
            }
            else if (result[3] != '2' && result[3] != '1' && result[3] != '0')
            {
                result.Remove(4, 5);
                result.Insert(6, "3");
            }
            else
            {
                result.Insert(11, result[3]);
                result.Remove(3, 5);
            }

            return result.ToString();
        }
Example #7
0
        /// <summary>
        /// datatable 转化为 json
        /// </summary>
        /// <param name="table"></param>
        /// <param name="columnsToParse"></param>
        /// <returns></returns>
        public static string DataTableToJson(DataTable table, params string[] columnsToParse)
        {
            if (table == null || table.Rows.Count == 0)
                return "{\"total\":0,\"rows\":[]}";

            StringBuilder sb = new StringBuilder();
            sb.Append("{\"total\":").Append(table.Rows.Count).Append(",");
            sb.Append("\"rows\":[");

            foreach (DataRow row in table.Rows)
            {
                sb.Append("{");

                foreach (string column in columnsToParse)
                {
                    sb.Append("\"").Append(column).Append("\":").Append("\"").Append(row[column].ToString().Trim()).Append("\",");
                }
                sb.Remove(sb.Length - 1, 1);
                sb.Append("},");
            }
            sb.Remove(sb.Length - 1, 1);
            sb.Append("]}");

            return sb.ToString();
        }
Example #8
0
        public static string InsertCharacterInStringAtSpecifiedInterval(string InputString,
                                                                        int Interval,
                                                                        char InsertCharacter)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            for (int i = 0; i < InputString.Length; i = i + Interval)
            {
                int getMe = Interval;
                if (i + Interval > InputString.Length)
                {
                    getMe = (InputString.Length - i);
                }

                sb.Append(InputString.Substring(i, getMe));
                sb.Append(InsertCharacter);
            }

            if (sb[0] == InsertCharacter)
            {
                sb = sb.Remove(0, 1);
            }

            if (sb[sb.Length - 1] == InsertCharacter)
            {
                sb = sb.Remove(sb.Length - 1, 1);
            }

            return(sb.ToString());
        }
        protected string NormalizePhoneNumber(string phoneNumber)
        {
            StringBuilder normalizedNumber = new StringBuilder();
            foreach (char symbol in phoneNumber)
            {
                if (char.IsDigit(symbol) || (symbol == '+'))
                {
                    normalizedNumber.Append(symbol);
                }
            }

            if (normalizedNumber.Length >= 2 && normalizedNumber[0] == '0' && normalizedNumber[1] == '0')
            {
                normalizedNumber.Remove(0, 1);
                normalizedNumber[0] = '+';
            }

            while (normalizedNumber.Length > 0 && normalizedNumber[0] == '0')
            {
                normalizedNumber.Remove(0, 1);
            }

            if (normalizedNumber.Length > 0 && normalizedNumber[0] != '+')
            {
                normalizedNumber.Insert(0, DefaultCountryCode);
            }

            return normalizedNumber.ToString();
        }
Example #10
0
 private static string BuildName(List<ObjectCommandPropertyValue> propValues)
 {
     StringBuilder builder = new StringBuilder();
     foreach (ObjectCommandPropertyValue value2 in propValues)
     {
         if ((value2 != null) && (value2.PropertyValue != null))
         {
             ICollection propertyValue = value2.PropertyValue as ICollection;
             if (propertyValue != null)
             {
                 builder.Append("{");
                 int length = builder.Length;
                 foreach (object obj2 in propertyValue)
                 {
                     builder.Append(string.Format(CultureInfo.InvariantCulture, "{0}, ", new object[] { obj2.ToString() }));
                 }
                 builder = (builder.Length > length) ? builder.Remove(builder.Length - 2, 2) : builder;
                 builder.Append("}, ");
             }
             else
             {
                 builder.Append(string.Format(CultureInfo.InvariantCulture, "{0}, ", new object[] { value2.PropertyValue.ToString() }));
             }
         }
     }
     if (builder.Length < 2)
     {
         return string.Empty;
     }
     return builder.Remove(builder.Length - 2, 2).ToString();
 }
Example #11
0
        /// <summary>
        /// 根据操作员权限所对应的json格式字符串
        /// </summary>
        /// <returns></returns>
        public string getJsonMenu(Guid userid)
        {
            DataTable dt_main = dal.getUserMenu(userid);

            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            DataRow[] rows = dt_main.Select("fatherid=0");

            if (rows.Length > 0)
            {
                sb.Append("{ \"menus\": [");
                for (int i = 0; i < rows.Length; i++)
                {
                    DataRow[] r_list = dt_main.Select(string.Format(" fatherid={0}", rows[i]["ui_menu_id"]));
                    if (r_list.Length > 0)
                    {
                        sb.Append("{ \"menuid\": \"" + rows[i]["ui_menu_id"].ToString() + "\", \"icon\": \"" + rows[i]["icon"].ToString() + "\", \"menuname\": \"" + rows[i]["menuname"].ToString() + "\",\"menus\": [");
                        for (int j = 0; j < r_list.Length; j++)
                        {
                            sb.Append("{ \"menuid\": \"" + r_list[j]["ui_menu_id"].ToString() + "\", \"menuname\": \"" + r_list[j]["menuname"].ToString() + "\", \"icon\": \"" + r_list[j]["icon"].ToString() + "\", \"url\": \"" + r_list[j]["url"].ToString() + "\" },");
                        }
                        //去,
                        sb.Remove(sb.Length - 1, 1);
                        sb.Append("]},");
                    }
                }
                //去,
                sb.Remove(sb.Length - 1, 1);
                sb.Append("]}");
            }
            return(sb.ToString());
        }
Example #12
0
        public static void ExportToCsv(System.Web.HttpResponse response, DataTable exportData, string exportName)
        {
            response.Clear();
            byte[] BOM = { 0xEF, 0xBB, 0xBF }; // UTF-8 BOM karakterleri
            response.BinaryWrite(BOM);
            StringBuilder sb = new StringBuilder();
            foreach (DataColumn dc in exportData.Columns)
            {
                sb.Append((char)(34) + dc.ColumnName + (char)(34));
                sb.Append(";");
            }
            sb = sb.Remove(sb.Length - 1, 1);
            sb.AppendLine();
            foreach (DataRow dr in exportData.Rows)
            {

                for (int i = 0; i < exportData.Columns.Count; i++)
                {
                    sb.Append(dr[i].ToString().Replace(';', ',').Replace('\n', ' ').Replace('\t', ' ').Replace('\r', ' '));
                    sb.Append(";");
                }
                sb = sb.Remove(sb.Length - 1, 1);
                sb.AppendLine();
            }
            response.ContentType = "text/csv";
            response.AppendHeader("Content-Disposition", "attachment; filename=" + exportName + ".csv");
            response.Write(sb.ToString());
            response.End();
        }
        private static string ConvertToCanonical(string number)
        {
            StringBuilder sb = new StringBuilder();

                foreach (char ch in number)
                {
                    if (char.IsDigit(ch) || (ch == '+'))
                    {
                        sb.Append(ch);
                    }
                }

                if (sb.Length >= 2 && sb[0] == '0' && sb[1] == '0')
                {
                    sb.Remove(0, 1);
                    sb[0] = '+';
                }

                while (sb.Length > 0 && sb[0] == '0')
                {
                    sb.Remove(0, 1);
                }

                if (sb.Length > 0 && sb[0] != '+')
                {
                    sb.Insert(0, code);
                }

            return sb.ToString();
        }
        public static string ReadLine(this Stream ns)
        {
            var builder = new StringBuilder();

            byte cur = 0;
            byte prev = 0;

            while (true)
            {
                if (cur == 10)
                {
                    if (prev == 13)
                    {
                        // Remove /r/n
                        builder.Remove(builder.Length - 2, 2);
                    }
                    else
                    {
                        // Remove /n
                        builder.Remove(builder.Length - 1, 1);
                    }
                    break;
                }

                prev = cur;
                cur = (byte)ns.ReadByte();

                builder.Append((char)cur);
            }

            return builder.ToString();
        }
Example #15
0
 /// <summary>  
 /// dataTable中的全部记录转换成Json格式  
 /// </summary>  
 /// <param name="dt"></param>  
 /// <returns></returns>  
 // public static string DataTable2Json(DataTable dt,)
 //{
 //    return DataTable2JsonAfterRow(dt, 0,row);
 // }
 /// <summary>
 /// 
 /// 
 /// </summary>
 /// <param name="dt"></param>
 /// <param name="after">起行+1</param>
 /// <returns></returns>
 public static string DataTable2JsonAfterRow(DataTable dt, int after ,int row,int total)
 {
     StringBuilder jsonBuilder = new StringBuilder();
       if (dt.Rows.Count == 0)
       {
       jsonBuilder.Append("{\"total\":" + total.ToString());
       jsonBuilder.Append(",\"rows\":[]}");
       return jsonBuilder.ToString();
       }
       jsonBuilder.Append("{\"total\":"+total.ToString());
       jsonBuilder.Append(dt.TableName);
       jsonBuilder.Append(",\"rows\":[");
       for (int i = after; i < dt.Rows.Count; i++)
       {
       jsonBuilder.Append("{");
       for (int j = 0; j < dt.Columns.Count; j++)
       {
       jsonBuilder.Append("\"");
       jsonBuilder.Append(dt.Columns[j].ColumnName);
       jsonBuilder.Append("\":\"");
       jsonBuilder.Append(dt.Rows[i][j].ToString());
       jsonBuilder.Append("\",");
       }
       jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
       jsonBuilder.Append("},");
       }
       jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
       jsonBuilder.Append("]");
       jsonBuilder.Append("}");
       return jsonBuilder.ToString();
 }
Example #16
0
        /// <summary>
        /// Converts input phone string to its canonical variant.
        /// </summary>
        /// <param name="phoneNumberString">Phone number string.</param> 
        /// <returns>Converted phone string.</returns>
        private static string ConvertToCanonical(string phoneNumberString)
        {
            var resultNumber = new StringBuilder();

            resultNumber.Clear();
            foreach (char character in phoneNumberString)
            {
                if (char.IsDigit(character) || (character == '+'))
                {
                    resultNumber.Append(character);
                }
            }
            if (resultNumber.Length >= 2 && resultNumber[0] == '0' && resultNumber[1] == '0')
            {
                resultNumber.Remove(0, 1);
                resultNumber[0] = '+';
            }
            while (resultNumber.Length > 0 && resultNumber[0] == '0')
            {
                resultNumber.Remove(0, 1);
            }
            if (resultNumber.Length > 0 && resultNumber[0] != '+')
            {
                resultNumber.Insert(0, DefaultCountryCode);
            }

            return resultNumber.ToString();
        }
Example #17
0
        static void Main(string[] args)
        {
            string text = Console.ReadLine();

            int start = text.IndexOf("<upcase>");
            int end = text.IndexOf("</upcase>") + 9;

            while(start != -1 && end != -1)
            {
                StringBuilder sb = new StringBuilder(text);
                for(int i= start; i<end; i++)
                {
                    if(sb[i] >= 'a' && sb[i]<='z')
                    {
                        sb[i] -= (char)32;
                    }
                }

                sb = sb.Remove(end - 9, 9);
                sb = sb.Remove(start, 8);
                text = sb.ToString();
                start = text.IndexOf("<upcase>");
                end = text.IndexOf("</upcase>") + 9;
            }

            Console.WriteLine(text);
        }
        /// <summary>Creates a regular expression that represents a comma-delimited list of the given regular expression pattern.</summary>
        /// <param name="expression">The regular expression.</param>
        /// <returns>A new regular expression.</returns>
        private static string CreateListRegularExpression(string expression)
        {
            var emailRegularExpressionBuilder = new StringBuilder(expression);
            var prefixBuilder = new StringBuilder();
            if (emailRegularExpressionBuilder[0] == '^')
            {
                prefixBuilder.Append('^');
                emailRegularExpressionBuilder.Remove(0, 1);
            }

            if (emailRegularExpressionBuilder.ToString(0, 2).Equals(@"\b", StringComparison.Ordinal))
            {
                prefixBuilder.Append(@"\b");
                emailRegularExpressionBuilder.Remove(0, 2);
            }

            var suffixBuilder = new StringBuilder();
            if (emailRegularExpressionBuilder[emailRegularExpressionBuilder.Length - 1] == '$')
            {
                suffixBuilder.Append('$');
                emailRegularExpressionBuilder.Remove(emailRegularExpressionBuilder.Length - 1, 1);
            }

            if (emailRegularExpressionBuilder.ToString(emailRegularExpressionBuilder.Length - 2, 2)
                                             .Equals(@"\b", StringComparison.Ordinal))
            {
                suffixBuilder.Append(@"\b");
                emailRegularExpressionBuilder.Remove(emailRegularExpressionBuilder.Length - 2, 2);
            }

            return string.Format(CultureInfo.InvariantCulture, @"{0}{1}(?:,\s*{1})*{2}", prefixBuilder, emailRegularExpressionBuilder, suffixBuilder);
        }
        public byte[] ToBytes()
        {
            int totalLen = 0;
            byte[] bytes = new byte[TOTAL_WIDTH];

            StringBuilder sb = new StringBuilder();
            sb = sb.Append(CommonDataHelper.FillSpecifyWidthFigure(QUERY_TYPE, 1));
            CommonDataHelper.ResetByteBuffer(sb, ref bytes, ref totalLen, true);
            sb.Remove(0, sb.Length);
            sb = sb.Append(CommonDataHelper.FillSpecifyWidthString(ACCOUNT_DATE, 8));
            CommonDataHelper.ResetByteBuffer(sb, ref bytes, ref totalLen, true);
            sb.Remove(0, sb.Length);
            sb = sb.Append(CommonDataHelper.FillSpecifyWidthString(NOTICE_NO, 20));
            CommonDataHelper.ResetByteBuffer(sb, ref bytes, ref totalLen, true);
            sb.Remove(0, sb.Length);
            sb = sb.Append(CommonDataHelper.FillSpecifyWidthFigure(NOTICE_TYPE, 1));
            CommonDataHelper.ResetByteBuffer(sb, ref bytes, ref totalLen, true);
            sb.Remove(0, sb.Length);
            sb = sb.Append(CommonDataHelper.FillSpecifyWidthFigure(BUSINESS_TYPE, 1));
            CommonDataHelper.ResetByteBuffer(sb, ref bytes, ref totalLen, true);
            sb.Remove(0, sb.Length);
            sb = sb.Append(CommonDataHelper.FillSpecifyWidthString(RESERVE, 256));
            CommonDataHelper.ResetByteBuffer(sb, ref bytes, ref totalLen, true);
            sb.Remove(0, sb.Length);

            return bytes;
        }
Example #20
0
 private static StringBuilder MoveToBack(StringBuilder test, Tuple<int, int> location){
     var charToMoveToBack = test[location.Item1];
     test = test.Remove(location.Item1, 1);
     test = test.Remove(location.Item2 - 1, 1);
     test = test.Append(charToMoveToBack.ToString());
     return test;
 }
        public byte[] ToBytes()
        {
            int totalLen = 0;
            byte[] bytes = new byte[TOTAL_WIDTH];
            StringBuilder sb = new StringBuilder();
            sb = sb.Append(CommonDataHelper.FillSpecifyWidthString(RecordID, 8));
            CommonDataHelper.ResetByteBuffer(sb, ref bytes, ref totalLen, true);
            sb.Remove(0, sb.Length);
            sb = sb.Append(CommonDataHelper.FillSpecifyWidthFigure(RecordLength, 8));
            CommonDataHelper.ResetByteBuffer(sb, ref bytes, ref totalLen, true);
            sb.Remove(0, sb.Length);
            sb = sb.Append(CommonDataHelper.FillSpecifyWidthFigure(RecordNumber, 8));
            CommonDataHelper.ResetByteBuffer(sb, ref bytes, ref totalLen, true);
            sb.Remove(0, sb.Length);
            if (RecordCollection != null)
            {
                foreach (var record in RecordCollection)
                {
                    Array.Copy(record.ToBytes(), 0, bytes, totalLen, record.TOTAL_WIDTH);
                    totalLen += record.TOTAL_WIDTH;
                }                
            }
            return bytes;

        }
        /*
         * 插入新供应商
         */
        public void insertSupplier(Dictionary<String,String> supplierInformationDict)
        {
            StringBuilder sqlText = new StringBuilder("insert into supplier(");
            foreach (var item in supplierInformationDict)
            {
                sqlText.Append(item.Key);
                sqlText.Append(",");
            }
            sqlText.Remove(sqlText.Length-1,1);     //移除,(多余的逗号)
            sqlText.Append(") values(");

            SqlParameter[] sqlParameter = new SqlParameter[supplierInformationDict.Count];
            int index = 0;
            foreach (var item in supplierInformationDict)
            {
                sqlText.Append("@");
                sqlText.Append(item.Key);
                sqlText.Append(",");

                if (index != supplierInformationDict.Count - 1)
                {
                    sqlParameter[index] = new SqlParameter("@" + item.Key, SqlDbType.VarChar);
                }
                else
                {
                    sqlParameter[index] = new SqlParameter("@" + item.Key, SqlDbType.DateTime);
                }
                sqlParameter[index].Value = item.Value;
                index++;
            }
            sqlText.Remove(sqlText.Length - 1, 1);     //移除,(多余的逗号)
            sqlText.Append(")");

            DBHelper.ExecuteNonQuery(sqlText.ToString(),sqlParameter);
        }
Example #23
0
        public static string DataTable2Json(System.Data.DataTable dt, int total = 0)
        {
            System.Text.StringBuilder jsonBuilder = new System.Text.StringBuilder();
            jsonBuilder.Append("{");
            if (total == 0)
            {
                jsonBuilder.AppendFormat("\"total\":{0}, ", dt.Rows.Count);
            }
            else
            {
                jsonBuilder.AppendFormat("\"total\":{0}, ", total);
            }

            jsonBuilder.Append("\"rows\":[ ");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                jsonBuilder.Append("{");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    jsonBuilder.Append("\"");
                    jsonBuilder.Append(dt.Columns[j].ColumnName);
                    jsonBuilder.Append("\":\"");
                    jsonBuilder.Append(dt.Rows[i][j].ToString());
                    jsonBuilder.Append("\",");
                }
                jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                jsonBuilder.Append("},");
            }
            jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            jsonBuilder.Append("]");
            jsonBuilder.Append("}");
            return(jsonBuilder.ToString());
        }
Example #24
0
        /// <summary>
        /// DataSet To Json by chuchur 2013年12月24日 09:52:32
        /// </summary>
        /// <param name="ds"></param>
        /// <returns></returns>
        public static string dsToJson(this System.Data.DataSet ds)
        {
            System.Text.StringBuilder str = new System.Text.StringBuilder("[");
            for (int o = 0; o < ds.Tables.Count; o++)
            {
                str.Append("{");
                str.Append(string.Format("\"{0}\":[", ds.Tables[o].TableName));

                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    str.Append("{");
                    for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
                    {
                        str.Append(string.Format("\"{0}\":\"{1}\",", ds.Tables[0].Columns[j].ColumnName, ds.Tables[0].Rows[i][j].ToString()));
                    }
                    str.Remove(str.Length - 1, 1);
                    str.Append("},");
                }
                str.Remove(str.Length - 1, 1);
                str.Append("]},");
            }
            str.Remove(str.Length - 1, 1);
            str.Append("]");
            return(str.ToString());
        }
Example #25
0
        /// <summary>  
        /// dataTable转换成Json格式  
        /// </summary>  
        /// <param name="dt"></param>  
        /// <returns></returns>  
        public static string DataTable2Json(List<Area> ds)
        {
            StringBuilder jsonBuilder = new StringBuilder();
            if (ds != null && ds.Count > 0)
            {
                jsonBuilder.Append("[");
                for (int i = 0; i < ds.Count; i++)
                {
                    jsonBuilder.Append("{");
                    jsonBuilder.Append("\"");
                    jsonBuilder.Append("AreaID");
                    jsonBuilder.Append("\":\"");
                    jsonBuilder.Append(ds[i].AreaID);
                    jsonBuilder.Append("\",");
                    jsonBuilder.Append("\"");
                    jsonBuilder.Append("AreaName");
                    jsonBuilder.Append("\":\"");
                    jsonBuilder.Append(ds[i].AreaName);
                    jsonBuilder.Append("\",");

                    jsonBuilder.Append("\"");
                    jsonBuilder.Append("FaAreaID");
                    jsonBuilder.Append("\":\"");
                    jsonBuilder.Append(ds[i].FaAreaID);
                    jsonBuilder.Append("\",");

                    jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                    jsonBuilder.Append("},");
                }
                jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                jsonBuilder.Append("]");
            }
            return jsonBuilder.ToString();
        }
        public string ConvertPhoneNumber(string num)
        {
            StringBuilder sb = new StringBuilder();

            sb.Clear();
            foreach (char ch in num)
            {
                if (char.IsDigit(ch) || (ch == '+'))
                {
                    sb.Append(ch);
                }
            }

            if (sb.Length >= 2 && sb[0] == '0' && sb[1] == '0')
            {
                sb.Remove(0, 1);
                sb[0] = '+';
            }

            while (sb.Length > 0 && sb[0] == '0')
            {
                sb.Remove(0, 1);
            }

            if (sb.Length > 0 && sb[0] != '+')
            {
                sb.Insert(0, Code);
            }

            return sb.ToString();
        }
        public string ConvertToCanonical(string number)
        {
            var canonicalNumber = new StringBuilder();

            foreach (var ch in number.Where(ch => char.IsDigit(ch) || (ch == '+')))
            {
                canonicalNumber.Append(ch);
            }

            if (canonicalNumber.Length >= 2 && canonicalNumber[0] == '0' && canonicalNumber[1] == '0')
            {
                canonicalNumber.Remove(0, 1);
                canonicalNumber[0] = '+';
            }

            while (canonicalNumber.Length > 0 && canonicalNumber[0] == '0')
            {
                canonicalNumber.Remove(0, 1);
            }

            if (canonicalNumber.Length > 0 && canonicalNumber[0] != '+')
            {
                canonicalNumber.Insert(0, this.countryCode);
            }

            return canonicalNumber.ToString();
        }
Example #28
0
		public static string ToCharacterSeparatedValues(this DataTable table, string delimiter, bool includeHeader)
		{
			var result = new StringBuilder();

			if (includeHeader)
			{
				foreach (DataColumn column in table.Columns)
				{
					result.Append(column.ColumnName);
					result.Append(delimiter);
				}

				result.Remove(result.Length, 0);
				result.AppendLine();
			}

			foreach (DataRow row in table.Rows)
			{
				for (var x = 0; x < table.Columns.Count; x++)
				{
					if (x != 0)
						result.Append(delimiter);

					result.Append(row[table.Columns[x]]);
				}

				result.AppendLine();
			}

			result.Remove(result.Length, 0);
			result.AppendLine();

			return result.ToString();
		}
Example #29
0
 /// <summary>  
 /// dataTable转换成Json格式  
 /// </summary>  
 /// <param name="dt"></param>  
 /// <returns></returns>  
 public static string DataTable2Json(DataTable dt)
 {
     StringBuilder jsonBuilder = new StringBuilder();
     jsonBuilder.Append("{\"");
     jsonBuilder.Append(dt.TableName);
     jsonBuilder.Append("\":[");
     //jsonBuilder.Append("[");
     for (int i = 0; i < dt.Rows.Count; i++)
     {
         jsonBuilder.Append("{");
         for (int j = 0; j < dt.Columns.Count; j++)
         {
             jsonBuilder.Append("\"");
             jsonBuilder.Append(dt.Columns[j].ColumnName);
             jsonBuilder.Append("\":\"");
             jsonBuilder.Append(dt.Rows[i][j].ToString());
             jsonBuilder.Append("\",");
         }
         jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
         jsonBuilder.Append("},");
     }
     jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
     jsonBuilder.Append("]");
     jsonBuilder.Append("}");
     return jsonBuilder.ToString();
 }
Example #30
0
    public static string DataTableToJson(DataTable dt)
    {
        System.Text.StringBuilder jsonBuilder = new System.Text.StringBuilder();
        jsonBuilder.Append("{\"Name\":\"" + dt.TableName + "\",\"Rows");
        jsonBuilder.Append("\":[");
        if (dt.Rows.Count > 0)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                jsonBuilder.Append("{");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    jsonBuilder.Append("\"");
                    jsonBuilder.Append(dt.Columns[j].ColumnName);
                    jsonBuilder.Append("\":\"");
                    jsonBuilder.Append(dt.Rows[i][j].ToString().Replace("\"", "\\\""));
                    jsonBuilder.Append("\",");
                }
                jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                jsonBuilder.Append("},");
            }
        }
        else
        {
            jsonBuilder.Append("[");
        }

        jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
        jsonBuilder.Append("]");
        jsonBuilder.Append("}");
        return(jsonBuilder.ToString());
    }
Example #31
0
        private static string Data2Json(DataTable dt, string tableName)
        {
            var jsonBuilder = new System.Text.StringBuilder();

            jsonBuilder.Append("{");
            jsonBuilder.Append("\"" + tableName + "\":[ ");
            for (var i = 0; i < dt.Rows.Count; i++)
            {
                if (string.IsNullOrEmpty(dt.Rows[i]["DoctorName"].ToString().Trim()))
                {
                    continue;
                }
                jsonBuilder.Append("{");
                for (var j = 0; j < dt.Columns.Count; j++)
                {
                    jsonBuilder.Append("\"");
                    jsonBuilder.Append(dt.Columns[j].ColumnName);
                    jsonBuilder.Append("\":\"");
                    jsonBuilder.Append(dt.Rows[i][j].ToString());
                    jsonBuilder.Append("\",");
                }

                jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                jsonBuilder.Append("},");
            }

            jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            jsonBuilder.Append("]");
            jsonBuilder.Append("}");
            return(jsonBuilder.ToString());
        }
Example #32
0
 /// <summary>
 /// 得到json树
 /// </summary>
 /// <param name="tabel"></param>
 /// <param name="idCol"></param>
 /// <param name="txtCol"></param>
 /// <param name="rela"></param>
 /// <param name="pId"></param>
 /// <param name="szCheckItems">选中的ID号集合</param>
 /// <returns></returns>
 public static string GetTreeGridJsonByTable(DataTable dt, string idCol, string txtCol, string rela, object pId, string szCheckItems)
 {
     System.Text.StringBuilder jsonBuilder = new System.Text.StringBuilder();
     jsonBuilder.Append("{");
     jsonBuilder.AppendFormat("\"total\":{0}, ", dt.Rows.Count);
     jsonBuilder.Append("\"rows\":[ ");
     for (int i = 0; i < dt.Rows.Count; i++)
     {
         jsonBuilder.Append("{");
         for (int j = 0; j < dt.Columns.Count; j++)
         {
             jsonBuilder.Append("\"");
             jsonBuilder.Append(dt.Columns[j].ColumnName);
             jsonBuilder.Append("\":\"");
             jsonBuilder.Append(dt.Rows[i][j].ToString());
             jsonBuilder.Append("\",");
         }
         jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
         jsonBuilder.Append("},");
     }
     jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
     jsonBuilder.Append("]");
     jsonBuilder.Append("}");
     return(jsonBuilder.ToString());
 }
        public byte[] ToBytes()
        {
            int totalLen = 0;
            byte[] bytes = new byte[TOTAL_WIDTH];

            StringBuilder sb = new StringBuilder();
            sb = sb.Append(CommonDataHelper.FillSpecifyWidthString(SignType, 1));
            CommonDataHelper.ResetByteBuffer(sb, ref bytes, ref totalLen, true);
            sb.Remove(0, sb.Length);
            sb = sb.Append(CommonDataHelper.FillSpecifyWidthString(ORG_NO, 6));
            CommonDataHelper.ResetByteBuffer(sb, ref bytes, ref totalLen, true);
            sb.Remove(0, sb.Length);
            sb = sb.Append(CommonDataHelper.FillSpecifyWidthString(STF_NO, 7));
            CommonDataHelper.ResetByteBuffer(sb, ref bytes, ref totalLen, true);
            sb.Remove(0, sb.Length);
            
            if (PIN_BLK == null)
            {
                PIN_BLK = new byte[24];
            }
            Array.Copy(PIN_BLK, 0, bytes, totalLen, PIN_BLK.Length);
            totalLen += 24;
            sb = sb.Append(CommonDataHelper.FillSpecifyWidthString(CARD_NO, 20));
            CommonDataHelper.ResetByteBuffer(sb, ref bytes, ref totalLen, true);
            sb.Remove(0, sb.Length);
            sb = sb.Append(CommonDataHelper.FillSpecifyWidthString(SystemDate, 8));
            CommonDataHelper.ResetByteBuffer(sb, ref bytes, ref totalLen, true);
            sb.Remove(0, sb.Length);
            return bytes;
        }
Example #34
0
    /// <summary>
    /// DataTable转换为json字符串
    /// </summary>
    /// <param name="dt"></param>
    /// <returns></returns>
    protected string DataTable2Json(DataTable dt)
    {
        System.Text.StringBuilder jsonBuilder = new System.Text.StringBuilder();
        jsonBuilder.Append("[");
        if (dt.Rows.Count == 0)
        {
            jsonBuilder.Append("]");
            return(jsonBuilder.ToString());
        }

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            jsonBuilder.Append("{");
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                //jsonBuilder.Append("\"");
                jsonBuilder.Append(dt.Columns[j].ColumnName);
                jsonBuilder.Append(":\"");
                try
                {
                    jsonBuilder.Append(GetSafeJSONString(dt.Rows[i][j].ToString()));  //.Replace("\"","\\\""));
                }
                catch
                {
                    jsonBuilder.Append("");
                }
                jsonBuilder.Append("\",");
            }
            jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            jsonBuilder.Append("},");
        }
        jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
        jsonBuilder.Append("]");
        return(jsonBuilder.ToString());
    }
Example #35
0
		/// <summary>
		/// Detects untokenized fields and sets as NotAnalyzed in analyzer
		/// </summary>
		private static string PreProcessUntokenizedTerms(PerFieldAnalyzerWrapper analyzer, string query, Analyzer keywordAnlyzer)
		{
			var untokenizedMatches = untokenizedQuery.Matches(query);
			if (untokenizedMatches.Count < 1)
			{
				return query;
			}

			var sb = new StringBuilder(query);

			// KeywordAnalyzer will not tokenize the values

			// process in reverse order to leverage match string indexes
			for (int i=untokenizedMatches.Count; i>0; i--)
			{
				Match match = untokenizedMatches[i-1];

				// specify that term for this field should not be tokenized
				analyzer.AddAnalyzer(match.Groups[1].Value, keywordAnlyzer);

				Group term = match.Groups[2];

				// remove enclosing "[[" "]]" from term value (again in reverse order)
				sb.Remove(term.Index+term.Length-2, 2);
				sb.Remove(term.Index, 2);
			}

			return sb.ToString();
		}
Example #36
0
        public static string RandomPassword(int length)
        {
            var sb = new StringBuilder();

            sb.Append("1");
            sb.Append("A");
            sb.Append("a");
            sb.Append("!");

            for (var i = 0; i < length; i++)
            {
                sb.Append(
                    Convert.ToChar(Convert.ToInt32(Math.Floor((26 * DataHelper.Random.NextDouble()) + 65))));
            }

            if (sb.Length > 10)
            {
                sb.Append(DateTime.Now.ToString("hhMMssffff"));
                sb.Remove(0, 10);
            }
            else if (sb.Length > 6)
            {
                sb.Append(DateTime.Now.ToString("hhMMss"));
                sb.Remove(0, 6);
            }

            return sb.ToString();
        }
Example #37
0
		private static string CreateInsertSqlString(Table table, IDictionary<string, object> parameters)
		{
			var sb = new StringBuilder();
			sb.AppendLine("IF NOT EXISTS (SELECT * FROM {0} WHERE {1})".Put(table.Name, table.Columns.Where(c => c.IsPrimaryKey).Select(c => "{0} = @{0}".Put(c.Name)).Join(" AND ")));
			sb.AppendLine("BEGIN");
			sb.Append("INSERT INTO ");
			sb.Append(table.Name);
			sb.Append(" (");
			foreach (var par in parameters)
			{
				sb.Append("[");
				sb.Append(par.Key);
				sb.Append("],");
			}
			sb.Remove(sb.Length - 1, 1);
			sb.Append(") VALUES (");
			foreach (var par in parameters)
			{
				sb.Append("@");
				sb.Append(par.Key);
				sb.Append(",");
			}
			sb.Remove(sb.Length - 1, 1);
			sb.AppendLine(")");
			sb.Append("END");
			return sb.ToString();
		}
        public void Insert(string Table, List<string> ColumnNames, List<Object> Values)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("INSERT INTO ");
            sb.Append(Table);
            sb.Append(" (");
            foreach (string column in ColumnNames)
            {
                sb.Append(column);
                sb.Append(",");
            }
            sb.Remove(sb.Length - 1, 1);
            sb.Append(") VALUES (");

            foreach (object value in Values)
            {
                if (value.GetType() == typeof(double) || value.GetType() == typeof(int))
                {
                    sb.Append(value.ToString().Replace(',', '.') + ",");
                }
                else
                {
                    sb.Append("'" + value + "',");

                }
            }
            sb.Remove(sb.Length - 1, 1);
            sb.Append(")");
            Execute(sb.ToString());
        }
        /// <summary>
        /// Arma los filtros que se aplicarán para regenerar
        /// el reporte. Depende de cada implementación del 
        /// IPanelFiltros.
        /// </summary>
        private string armaFiltro()
        {
            var sb = new StringBuilder();

            // Filtros de fecha
            // Si no selecciona ningún filtro, genera una excepción.
            if (chkListaEntidades.CheckedItems.Count != 0 &&
                chkEstadosGestion.CheckedItems.Count != 0)
            {
                // Filtros de entidades
                sb.Append("(");
                foreach (object item in chkListaEntidades.CheckedItems)
                    sb.Append(string.Format("Entidad = '{0}' or ", item));
                sb.Remove(sb.Length - 4, 4);
                sb.Append(")");

                // Filtros de estados de cuenta
                sb.Append(" and (");
                foreach (object item in chkEstadosGestion.CheckedItems)
                    sb.Append(string.Format("Estado = '{0}' or ", item));
                sb.Remove(sb.Length - 4, 4);
                sb.Append(")");

                return sb.ToString();
            }

            throw new Exception(Mensaje.TextoMensaje("REPORTE-NOFILTRO"));
        }
        static void Main()
        {
            StringBuilder cages = new StringBuilder();

            while (true)
            {
                string input = Console.ReadLine();
                if (input == "END")
                {
                    break;
                }
                cages.Append(input);
            }

            int cagesToTake = int.Parse((cages[0] - '0').ToString());
            
            int cagesToRemove = 1;

            while (cagesToTake < cages.Length)
            {
                cages.Remove(0, cagesToRemove);
                BigInteger sum = 0;
                BigInteger product = 1;
                
                for (int i = 0; i < cagesToTake; i++)
                {
                    sum += BigInteger.Parse((cages[i] - '0').ToString());
                    product *= BigInteger.Parse((cages[i] - '0').ToString());
                    cages.Insert(0, "*", 1);
                    cages.Remove(0, 1);
                }
                string digitsToAppend = AppendTheSumAndProduct(cages, sum, product);
               
                cages.Remove(0, cagesToTake);
                cages.Insert(0, digitsToAppend); 

                if (cagesToRemove >= cages.Length)
                {
                    break;
                }

                cagesToRemove++;

                int cagesToSum = cagesToRemove;
                cagesToTake = SumOfDigitsToAppend(digitsToAppend, cagesToRemove);
            }

            for (int i = 0; i < cages.Length; i++)
            {
                if (i != cages.Length - 1)
                {
                    Console.Write("{0} ", cages[i]);
                }
                else
                {
                    Console.WriteLine(cages[i]);
                }
                
            }
        }
Example #41
0
        private string GetTableCreationSqlStmt(TableInfo tableInfo)
        {
            // *** Coyove Patched ***

            System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder(100);
            stringBuilder.AppendFormat("CREATE TABLE \"{0}\" (", tableInfo.Name);
            foreach (ColumnInfo current in tableInfo.Values)
            {
                stringBuilder.AppendFormat("\"{0}\" {1},", current.Name, this.m_DataTypeMap[current.DataType]);
            }
            stringBuilder.Remove(stringBuilder.Length - 1, 1);

            // MySQL does not support setting a text column as the primary key
            // Switched to Postgresql

            if (!DatabaseManager.isExcelExport && tableInfo.PrimaryKeys.Count > 0)
            {
                stringBuilder.AppendFormat(", CONSTRAINT \"PK_{0}\" PRIMARY KEY (", tableInfo.Name);
                for (int i = 0; i < tableInfo.PrimaryKeys.Count; i++)
                {
                    stringBuilder.AppendFormat("\"{0}\",", tableInfo[tableInfo.PrimaryKeys[i]].Name);
                }
                stringBuilder.Remove(stringBuilder.Length - 1, 1);
                stringBuilder.Append(")");
            }

            stringBuilder.Append(")");
            return(stringBuilder.ToString());
        }
        protected override string GetUrl()
        {
            string[] ids = MyHelper.EnumToArray(this.IDs);

            if (ids.Length > 0)
            {
                System.Text.StringBuilder whereClause = new System.Text.StringBuilder();

                if (ids.Length == 1)
                {
                    whereClause.AppendFormat("symbol=\"{0}\"", ids[0]);
                }
                else
                {
                    whereClause.Append("symbol in (");
                    foreach (string id in ids)
                    {
                        if (id.Trim() != string.Empty)
                        {
                            whereClause.AppendFormat("\"{0}\",", MyHelper.CleanYqlParam(id));
                        }
                    }
                    whereClause.Remove(whereClause.Length - 1, 1);
                    whereClause.Append(')');
                }

                if (this.ExpirationDates != null)
                {
                    System.DateTime[] expirations = MyHelper.EnumToArray(this.ExpirationDates);
                    if (ids.Length > 1 & expirations.Length > 1)
                    {
                        throw new NotSupportedException("Multiple IDs and multiple Expiration Dates are not supported");
                    }
                    if (expirations.Length > 0)
                    {
                        if (expirations.Length == 1)
                        {
                            whereClause.AppendFormat(" AND expiration=\"{0}-{1:00}\"", expirations[0].Year, expirations[0].Month);
                        }
                        else
                        {
                            whereClause.Append(" AND expiration in (");
                            foreach (System.DateTime exp in expirations)
                            {
                                whereClause.AppendFormat("\"{0}-{1:00}\",", exp.Year, exp.Month);
                            }
                            whereClause.Remove(whereClause.Length - 1, 1);
                            whereClause.Append(')');
                        }
                    }
                }
                return(MyHelper.YqlUrl("*", "yahoo.finance.options", whereClause.ToString(), null, false));
            }
            else
            {
                throw new NotSupportedException("An empty id list will not be supported.");
            }
        }
Example #43
0
    /// <summary>
    /// DataTable转换为json字符串
    /// </summary>
    /// <param name="dt"></param>
    /// <returns></returns>
    protected string DataTable2Json(DataTable dt)
    {
        System.Text.StringBuilder jsonBuilder = new System.Text.StringBuilder();
        jsonBuilder.Append("[");
        if (dt.Rows.Count == 0)
        {
            jsonBuilder.Append("]");
            return(jsonBuilder.ToString());
        }

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            jsonBuilder.Append("{");
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                //jsonBuilder.Append("\"");
                jsonBuilder.Append(dt.Columns[j].ColumnName);
                jsonBuilder.Append(":\"");
                try
                {
                    /*根据datatable列的数据格式 来格式化字符*/
                    string tmp = string.Empty;
                    if (dt.Columns[j].DataType.ToString() == "System.Int16" || dt.Columns[j].DataType.ToString() == "System.Int32" || dt.Columns[j].DataType.ToString() == "System.Int64")
                    {
                        tmp = dt.Rows[i][j].ToString();
                    }
                    else if (dt.Columns[j].DataType.ToString() == "System.Decimal")
                    {
                        tmp = dt.Rows[i][j].ToString();
                    }
                    else if (dt.Columns[j].DataType.ToString() == "System.DateTime")
                    {
                        if (dt.Rows[i][j] != null && dt.Rows[i][j].ToString() != "")
                        {
                            tmp = (Convert.ToDateTime(dt.Rows[i][j].ToString())).ToString("yyyy-MM-dd");
                        }
                    }
                    else
                    {
                        tmp = dt.Rows[i][j].ToString();
                    }
                    jsonBuilder.Append(GetSafeJSONString(tmp));//.Replace("\"","\\\""));
                }
                catch
                {
                    jsonBuilder.Append("");
                }
                jsonBuilder.Append("\",");
            }
            jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            jsonBuilder.Append("},");
        }
        jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
        jsonBuilder.Append("]");
        return(jsonBuilder.ToString());
    }
Example #44
0
 private void GetAllCategories(System.Web.HttpContext context)
 {
     System.Collections.Generic.IList <CategoryInfo> mainCategories = CategoryBrowser.GetMainCategories();
     if (mainCategories == null || mainCategories.Count == 0)
     {
         context.Response.Write(this.GetErrorJosn(103, "没获取到相应的分类"));
         return;
     }
     System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
     stringBuilder.Append("{\"result\":[");
     foreach (CategoryInfo current in mainCategories)
     {
         stringBuilder.Append("{");
         stringBuilder.AppendFormat("\"cid\":{0},", current.CategoryId);
         stringBuilder.AppendFormat("\"name\":\"{0}\",", current.Name);
         stringBuilder.AppendFormat("\"icon\":\"{0}\",", current.Icon);
         stringBuilder.AppendFormat("\"hasChildren\":\"{0}\",", current.HasChildren.ToString().ToLower());
         stringBuilder.AppendFormat("\"description\":\"{0}\",", this.GetSubCategoryNames(current.CategoryId));
         stringBuilder.Append("\"subs\":[");
         System.Collections.Generic.IList <CategoryInfo> subCategories = CategoryBrowser.GetSubCategories(current.CategoryId);
         if (subCategories != null && subCategories.Count > 0)
         {
             foreach (CategoryInfo current2 in subCategories)
             {
                 stringBuilder.Append("{");
                 stringBuilder.AppendFormat("\"cid\":{0},", current2.CategoryId);
                 stringBuilder.AppendFormat("\"name\":\"{0}\",", current2.Name);
                 stringBuilder.AppendFormat("\"icon\":\"{0}\",", current2.Icon);
                 stringBuilder.AppendFormat("\"hasChildren\":\"{0}\",", current2.HasChildren.ToString().ToLower());
                 stringBuilder.Append("\"subs\":[");
                 System.Collections.Generic.IList <CategoryInfo> subCategories2 = CategoryBrowser.GetSubCategories(current2.CategoryId);
                 if (subCategories2 != null && subCategories2.Count > 0)
                 {
                     foreach (CategoryInfo current3 in subCategories2)
                     {
                         stringBuilder.Append("{");
                         stringBuilder.AppendFormat("\"cid\":{0},", current3.CategoryId);
                         stringBuilder.AppendFormat("\"name\":\"{0}\",", current3.Name);
                         stringBuilder.AppendFormat("\"icon\":\"{0}\"", current3.Icon);
                         stringBuilder.Append("},");
                     }
                     stringBuilder.Remove(stringBuilder.Length - 1, 1);
                 }
                 stringBuilder.Append("]},");
             }
             stringBuilder.Remove(stringBuilder.Length - 1, 1);
         }
         stringBuilder.Append("]},");
     }
     stringBuilder.Remove(stringBuilder.Length - 1, 1);
     stringBuilder.Append("]}");
     context.Response.Write(stringBuilder.ToString());
 }
Example #45
0
 /// <summary>
 /// 将内存中的日志持久化到磁盘
 /// </summary>
 /// <param name="path">文件的存放目录</param>
 private void Persist(System.IO.DirectoryInfo path)
 {
     //读取时加锁
     lock (contentsLockObj)
     {
         using (System.IO.StreamWriter writer = new System.IO.StreamWriter(PreparePath(path), true, Encoding.UTF8))
         {
             writer.WriteLine(contents.ToString());
             writer.Flush();
             writer.Close();
             contents.Remove(0, contents.Length);
             GC.Collect();
         }
     }
 }
Example #46
0
        /// <summary>
        /// 用户流失人数(个人)
        /// </summary>
        /// <param name="starttime"></param>
        /// <param name="endtime"></param>
        /// <param name="errmsg"></param>
        /// <returns></returns>
        public static int GetUserLoss(string starttime, string endtime, out string errmsg)
        {
            List <DataParameter> pars = new List <DataParameter>();

            System.Text.StringBuilder sqlstr     = new System.Text.StringBuilder();
            System.Text.StringBuilder sqluserids = new System.Text.StringBuilder();
            sqlstr.Append("SELECT b.userid from (SELECT * from (SELECT userid,MAX(createdtime) as t from chosen_orderinfo GROUP BY userid asc) as c WHERE 1=1 ");
            if (!string.IsNullOrEmpty(starttime))
            {
                sqlstr.Append(" and c.t >='@starttime'");
                pars.Add(new DataParameter("starttime", starttime));
            }
            if (!string.IsNullOrEmpty(endtime))
            {
                sqlstr.Append(" and c.t<='@endtime' ");
                pars.Add(new DataParameter("endtime", endtime));
            }
            if (string.IsNullOrEmpty(endtime) || string.IsNullOrEmpty(starttime))
            {
                sqlstr.Append(" and c.t>DATE_SUB(CURDATE(), INTERVAL 3 MONTH)");
            }
            sqlstr.Append(") as b");
            List <base_users> list = MySqlHelper.GetDataList <base_users>(sqlstr.ToString(), out errmsg, pars.ToArray());

            sqluserids.Append("SELECT COUNT(*) from base_users where userid not in(");
            foreach (var item in list)
            {
                sqluserids.Append(item.userid + ",");
            }
            sqluserids.Remove(sqluserids.ToString().LastIndexOf(','), 1);
            sqluserids.Append(")");
            return((int)MySqlHelper.GetRecCount(sqluserids.ToString(), out errmsg, pars.ToArray()));
        }
Example #47
0
 public DataSet Select(BOL.Hunaid1BOL c, MySqlConnection conn, MySqlTransaction trans)
 {
     if (c != null)
     {
         StringBuilder qry = new System.Text.StringBuilder();
         qry.Append(@"SELECT `id`, `fisrtName`, `lastName`, `cellNum`, `email` FROM `hunaid` ");
         if (c.Id > 0)
         {
             qry.Append("`id` = " + c.Id + " AND");
         }
         if (!string.IsNullOrEmpty(c.FirstName))
         {
             qry.Append("`firstName` = '" + c.FirstName + "' AND");
         }
         if (!string.IsNullOrEmpty(c.LastName))
         {
             qry.Append("`lastName` = '" + c.LastName + "' AND");
         }
         if (Convert.ToInt32(c.CellNum) > 0)
         {
             qry.Append("`cellNum` = '" + c.CellNum + "' AND");
         }
         else
         {
             qry.Append(" 1 AND");
         }
         qry = qry.Remove(qry.Length - 3, 3);
         return(dbconnect.GetDataset(conn, trans, qry.ToString()));
     }
     return(null);
 }
Example #48
0
    private string GetPrjCode()
    {
        string cmdText = "SELECT prjCode + ',' FROM dbo.Sm_Treasury WHERE tcode != @tcode FOR XML PATH('')";

        SqlParameter[] commandParameters = new SqlParameter[]
        {
            new SqlParameter("@tcode", this.tcode)
        };
        string @string = DBHelper.GetString(SqlHelper.ExecuteScalar(CommandType.Text, cmdText, commandParameters));

        System.Collections.Generic.List <string> list = (
            from s in @string.Split(new char[]
        {
            ','
        })
            where s.Length > 0
            select s).ToList <string>();
        System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
        foreach (string current in list)
        {
            stringBuilder.Append(",'").Append(current).Append("'");
        }
        if (stringBuilder.Length > 0)
        {
            return(stringBuilder.Remove(0, 1).ToString());
        }
        return(string.Empty);
    }
Example #49
0
        private string GetChargeInfo(clsTestApplyItme_VO[] unitItems, string[] strUnits)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            foreach (clsTestApplyItme_VO objTestVO in unitItems)
            {
                foreach (string strUnit in strUnits)
                {
                    if (strUnit == objTestVO.m_strItemID)
                    {
                        sb.Append(objTestVO.m_strItemName == null ? "" : objTestVO.m_strItemName.Trim());
                        sb.Append(">");
                        sb.Append(objTestVO.m_strSpec == null ? "" : objTestVO.m_strSpec.Trim());
                        sb.Append(">");
                        sb.Append(objTestVO.m_decQty.ToString() + "" + objTestVO.m_strUnit);
                        sb.Append(">");
                        sb.Append(objTestVO.m_decTolPrice.ToString());
                        sb.Append(">");
                        sb.Append(objTestVO.m_decDiscount.ToString() + "%");
                        sb.Append("|");
                    }
                }
            }

            if (sb.Length > 0)
            {
                sb.Remove(sb.Length - 1, 1);
            }
            return(sb.ToString());
        }
Example #50
0
        private string PrintDom(HtmlElementCollection elemColl, System.Text.StringBuilder returnStr, Int32 depth)
        {
            System.Text.StringBuilder str = new System.Text.StringBuilder();

            foreach (HtmlElement elem in elemColl)
            {
                string elemName;

                elemName = elem.GetAttribute("ID");
                if (elemName == null || elemName.Length == 0)
                {
                    elemName = elem.GetAttribute("name");
                    if (elemName == null || elemName.Length == 0)
                    {
                        elemName = "<no name>";
                    }
                }

                str.Append(' ', depth * 4);
                str.Append(elemName + ": " + elem.TagName + "(Level " + depth + ")");
                returnStr.AppendLine(str.ToString());

                if (elem.CanHaveChildren)
                {
                    PrintDom(elem.Children, returnStr, depth + 1);
                }

                str.Remove(0, str.Length);
            }

            return(returnStr.ToString());
        }
Example #51
0
        private string PrintDom(HtmlAgilityPack.HtmlNodeCollection elemColl, System.Text.StringBuilder returnStr, Int32 depth)
        {
            System.Text.StringBuilder str = new System.Text.StringBuilder();
            //  IHTMLElement htmlElementCollection = null;

            foreach (HtmlNode elem in elemColl)
            {
                string elemName;

                elemName = elem.GetAttributeValue("ID", "null");
                if (elemName == null || elemName.Length == 0)
                {
                    elemName = elem.GetAttributeValue("name", "null");
                    if (elemName == null || elemName.Length == 0)
                    {
                        elemName = "<no name>";
                    }
                }

                str.Append(' ', depth * 4);
                str.Append(elemName + ": " + elem.Name + "(Level " + depth + ")");
                returnStr.AppendLine(str.ToString());

                if (elem.HasChildNodes)
                {
                    PrintDom(elem.ChildNodes, returnStr, depth + 1);
                }

                str.Remove(0, str.Length);
            }

            return(returnStr.ToString());
        }
        public IDataReader GetDataFromReader(string tableName, List <Column> tableColumns, List <PrimaryKey> tablePrimaryKeys, string whereClause = null)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder(200);
            sb.Append("SELECT ");
            foreach (Column col in tableColumns)
            {
                if (col.ServerDataType == "hierarchyid")
                {
                    sb.Append(string.Format(System.Globalization.CultureInfo.InvariantCulture, "CAST([{0}] AS varbinary(892)) AS [{0}], ", col.ColumnName));
                }
                else
                {
                    sb.Append(string.Format(System.Globalization.CultureInfo.InvariantCulture, "[{0}], ", col.ColumnName));
                }
            }
            sb.Remove(sb.Length - 2, 2);

            sb.AppendFormat(System.Globalization.CultureInfo.InvariantCulture, " From [{0}]", GetSchemaAndTableName(tableName));

            if (!string.IsNullOrEmpty(whereClause))
            {
                sb.AppendFormat(System.Globalization.CultureInfo.InvariantCulture, " WHERE {0}", whereClause);
            }

            sb.Append(SortSelect(tablePrimaryKeys));
            return(ExecuteDataReader(sb.ToString()));
        }
Example #53
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]);
        }
Example #54
0
 public DataSet Select(BOL.customers c, MySqlConnection conn, MySqlTransaction trans)
 {
     if (c != null)
     {
         StringBuilder qry = new System.Text.StringBuilder();
         qry.Append(@"SELECT `customerid`, `firstname`, `lastname`, `status`, `email`, 
         `mobile`, `createdby`, `createdon`, `isdeleted`, `modifyby`, `modifyon` FROM `customers` WHERE ");
         if (c.Customerid > 0)
         {
             qry.Append("`customerid` = " + c.Customerid + " AND");
         }
         if (!string.IsNullOrEmpty(c.Firstname))
         {
             qry.Append("`firstname` = '" + c.Firstname + "' AND");
         }
         if (!string.IsNullOrEmpty(c.Lastname))
         {
             qry.Append("`Lastname` = '" + c.Lastname + "' AND");
         }
         if (!string.IsNullOrEmpty(c.Mobile))
         {
             qry.Append("`Mobile` = '" + c.Mobile + "' AND");
         }
         else
         {
             qry.Append(" 1 AND");
         }
         qry = qry.Remove(qry.Length - 3, 3);
         return(dbconnect.GetDataset(conn, trans, qry.ToString()));
     }
     return(null);
 }
 public string GetUserScoroInfo()
 {
     System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
     System.Data.DataSet       scoreRanking  = FacadeManage.aideTreasureFacade.GetScoreRanking(10);
     if (scoreRanking.Tables[0].Rows.Count > 0)
     {
         stringBuilder.Append("[");
         foreach (System.Data.DataRow dataRow in scoreRanking.Tables[0].Rows)
         {
             stringBuilder.Append(string.Concat(new object[]
             {
                 "{userName:'******',s:'",
                 dataRow["Score"],
                 "'},"
             }));
         }
         stringBuilder.Remove(stringBuilder.Length - 1, 1);
         stringBuilder.Append("]");
     }
     else
     {
         stringBuilder.Append("{}");
     }
     return(stringBuilder.ToString());
 }
Example #56
0
        /// <summary>
        /// 强键值对的数据转换为连接URL参数拼接参数格式
        /// </summary>
        /// <param name="func"></param>
        /// <returns></returns>
        public virtual string ToUrl(CheckUrlKeyCall func)
        {
            System.Text.StringBuilder strb = new System.Text.StringBuilder();
            foreach (var d in this)
            {
                if (string.IsNullOrEmpty(d.Key))
                {
                    continue;
                }
                if (string.IsNullOrEmpty(d.Value))
                {
                    continue;
                }
                if (!func(d.Key))
                {
                    continue;
                }
                strb.Append(string.Format("&{0}={1}", d.Key.Trim(), WebHelper.UrlEncode(d.Value.Trim())));
            }
            if (strb.Length > 0)
            {
                strb = strb.Remove(0, 1);
            }

            return(strb.ToString());
        }
Example #57
0
 public DataSet Select(BOL.OwaisBOL c, MySqlConnection conn, MySqlTransaction trans)
 {
     if (c != null)
     {
         StringBuilder qry = new System.Text.StringBuilder();
         qry.Append(@"SELECT `idNumber`, `firstName`, `lastName`, `status`, `email` FROM `owais` WHERE ");
         if (c.IdNumber > 0)
         {
             qry.Append("`idNumber` = " + c.IdNumber + " AND");
         }
         if (!string.IsNullOrEmpty(c.FirstName))
         {
             qry.Append("`firstName` = '" + c.FirstName + "' AND");
         }
         if (!string.IsNullOrEmpty(c.LastName))
         {
             qry.Append("`lastName` = '" + c.LastName + "' AND");
         }
         if (!string.IsNullOrEmpty(c.Email))
         {
             qry.Append("`email` = '" + c.Email + "' AND");
         }
         else
         {
             qry.Append(" 1 AND");
         }
         qry = qry.Remove(qry.Length - 3, 3);
         return(dbconnect.GetDataset(conn, trans, qry.ToString()));
     }
     return(null);
 }
Example #58
0
 public DataSet Select(BOL.tickethistory obj, MySqlConnection conn, MySqlTransaction trans)
 {
     if (obj != null)
     {
         StringBuilder qry = new System.Text.StringBuilder();
         qry.Append(@"SELECT `tickethistoryid`, `ticketid`, `userid`, `ticketstatusid`,`createdon` FROM `tickethistory` WHERE ");
         if (obj.Tickethistoryid > 0)
         {
             qry.Append("`tickethistoryid` = " + obj.Tickethistoryid + " AND");
         }
         if (obj.Ticketid > 0)
         {
             qry.Append("`ticketid` = " + obj.Ticketid + " AND");
         }
         if (obj.Userid > 0)
         {
             qry.Append("`userid` = " + obj.Userid + " AND");
         }
         if (obj.Ticketstatusid > 0)
         {
             qry.Append("`ticketstatusid` = " + obj.Ticketstatusid + " AND");
         }
         qry = qry.Remove(qry.Length - 3, qry.Length);
         return(dbconnect.GetDataset(conn, trans, qry.ToString()));
     }
     return(null);
 }
Example #59
0
        /// <summary>
        /// 递归将DataTable转化为适合jquery easy ui 控件tree ,combotree 的 json
        /// 该方法最后还要 将结果稍微处理下,将最前面的,"children" 字符去掉.
        /// </summary>
        /// <param name="dt">要转化的表</param>
        /// <param name="pField">表中的父节点字段</param>
        /// <param name="pValue">表中顶层节点的值,没有 可以输入为0</param>
        /// <param name="kField">关键字字段名称</param>
        /// <param name="TextField">要显示的文本 对应的字段</param>
        /// <returns></returns>
        public static string TableToEasyUITreeJson(System.Data.DataTable dt, string pField, string pValue, string kField, string TextField)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            string filter = String.Format(" {0}='{1}' ", pField, pValue);//获取顶级目录.

            System.Data.DataRow[] drs = dt.Select(filter);
            if (drs.Length < 1)
            {
                return("");
            }
            sb.Append(",\"children\":[");
            foreach (System.Data.DataRow dr in drs)
            {
                string pcv = dr[kField].ToString();
                sb.Append("{");
                sb.AppendFormat("\"id\":\"{0}\",", dr[kField].ToString());
                sb.AppendFormat("\"text\":\"{0}\"", dr[TextField].ToString());
                sb.Append(TableToEasyUITreeJson(dt, pField, pcv, kField, TextField).TrimEnd(','));
                sb.Append("},");
            }
            if (sb.ToString().EndsWith(","))
            {
                sb.Remove(sb.Length - 1, 1);
            }
            sb.Append("]");
            return(sb.ToString());
        }
Example #60
0
        public string RemoveVowels(string s)
        {
            var sb = new System.Text.StringBuilder(s);
            var i  = 0;

            while (i < sb.Length)
            {
                if
                (
                    sb[i] == 'a' ||
                    sb[i] == 'e' ||
                    sb[i] == 'i' ||
                    sb[i] == 'o' ||
                    sb[i] == 'u'
                )
                {
                    sb.Remove(i, 1);
                }
                else
                {
                    i++;
                }
            }

            return(sb.ToString());
        }