Example #1
1
        private void ReadTXFNChunk(BinaryReader bin, BlizzHeader chunk)
        {
            //List of BLP filenames
            var blpFilesChunk = bin.ReadBytes((int)chunk.Size);

            var str = new StringBuilder();

            for (var i = 0; i < blpFilesChunk.Length; i++)
            {
                if (blpFilesChunk[i] == '\0')
                {
                    if (str.Length > 1)
                    {
                        str.Replace("..", ".");
                        str.Append(".blp"); //Filenames in TEX dont have have BLP extensions
                        if (!CASC.FileExists(str.ToString()))
                        {
                            new WoWFormatLib.Utils.MissingFile(str.ToString());
                        }
                    }
                    str = new StringBuilder();
                }
                else
                {
                    str.Append((char)blpFilesChunk[i]);
                }
            }
        }
        public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
        {

            if (actionContext.ModelState.IsValid) return;

            var errors = actionContext.ModelState
                .Where(e => e.Value.Errors.Count > 0)
                .Select(e => new Error
                {
                    Name = e.Key,
                    Message = e.Value.Errors.First().ErrorMessage ?? e.Value.Errors.First().Exception.Message
                }).ToArray();

            var strErrors = new StringBuilder();
            foreach (var error in errors)
            {
                var errorM = String.IsNullOrEmpty(error.Message) ? "Invalid Value" : error.Message;
                strErrors.Append(string.Format("[{0}]:{{{1}}}/", error.Name, errorM));
            }
            actionContext.Response = new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.BadRequest,
                ReasonPhrase = strErrors.ToString(),
                Content = new StringContent(strErrors.ToString())
            };
        }
Example #3
0
        static void Main( string[] args )
        {
            if ( args.Length != 1 )
            {
                return;
            }
            string fileName = args[ 0 ];
            StringBuilder fileContent = new StringBuilder( System.IO.File.ReadAllText( fileName ) );

            XmlDocument xdoc = new XmlDocument();
            xdoc.LoadXml( fileContent.ToString() );

            System.Xml.XmlNamespaceManager xmlnsManager = new System.Xml.XmlNamespaceManager( xdoc.NameTable );
            xmlnsManager.AddNamespace( "gpx", "http://www.topografix.com/GPX/1/0" );

            XmlNodeList timeNodes = xdoc.SelectNodes( "//gpx:time", xmlnsManager );
            foreach ( XmlNode timeNode in timeNodes )
            {
                string[] split1 = timeNode.InnerText.Split( 'T' );
                string[] splitDays = split1[ 0 ].Split( '-' );
                string[] splitHours = split1[ 1 ].Replace( "Z", "" ).Split( ':' );

                fileContent.Replace( timeNode.InnerText, new DateTime( int.Parse( splitDays[ 0 ] ), int.Parse( splitDays[ 1 ] ), int.Parse( splitDays[ 2 ] ),
                    int.Parse( splitHours[ 0 ] ), int.Parse( splitHours[ 1 ] ), int.Parse( splitHours[ 2 ] ) ).ToUniversalTime().ToString( "s" ) + "Z" );
            }

            System.IO.File.WriteAllText( fileName.Replace( ".gpx", "-fix.gpx" ), fileContent.ToString() );
        }
Example #4
0
        /// <summary>
        /// Parses the specified <see cref="ISentence"/> object using a given <paramref name="parser"/>.
        /// </summary>
        /// <param name="sentence">The sentence to be parsed.</param>
        /// <param name="parser">The parser.</param>
        /// <param name="numParses">The number parses. Usually 1.</param>
        /// <returns>An array with the parsed results.</returns>
        /// <exception cref="System.ArgumentNullException">
        /// <paramref name="sentence"/>
        /// or
        /// <paramref name="parser"/>
        /// </exception>
        /// <exception cref="System.ArgumentOutOfRangeException">numParses</exception>
        /// <exception cref="System.InvalidOperationException">The sentence is not tokenized.</exception>
        public static Parse[] ParseLine(ISentence sentence, IParser parser, int numParses) {
            if (sentence == null)
                throw new ArgumentNullException("sentence");

            if (parser == null)
                throw new ArgumentNullException("parser");

            if (numParses < 0)
                throw new ArgumentOutOfRangeException("numParses");

            if (sentence.Tokens == null || sentence.Tokens.Count == 0)
                throw new InvalidOperationException("The sentence is not tokenized.");

            var sb = new StringBuilder(sentence.Length);
            for (var i = 0; i < sentence.Tokens.Count; i++) {
                sb.Append(sentence.Tokens[i].Lexeme).Append(' ');
            }
            sb.Remove(sb.Length - 1, 1);

            var start = 0;
            var p = new Parse(sb.ToString(), new Span(0, sb.Length), AbstractBottomUpParser.INC_NODE, 0, 0);

            for (var i = 0; i < sentence.Tokens.Count; i++) {
                p.Insert(
                    new Parse(
                        sb.ToString(), 
                        new Span(start, start + sentence.Tokens[i].Lexeme.Length),
                        AbstractBottomUpParser.TOK_NODE, 0, i));

                start += sentence.Tokens[i].Lexeme.Length + 1;
            }

            return numParses == 1 ? new[] { parser.Parse(p) } : parser.Parse(p, numParses);
        }
Example #5
0
		/// <summary>
		/// Flushes the view data pool.
		/// </summary>
		/// <returns></returns>
		public String FlushViewDataPool( ViewDataDictionary viewData ) {
			if ( WebConfigSettings.GetWebConfigAppSetting( "isFlushDataPool" ) != "true" )
				return "<!-- ViewData isn't configed by appsettings.config. -->";

			var sb = new StringBuilder();

			if ( viewData.Count == 0 ) {
				sb.Append( "<!-- ViewData flushly is configed by appsettings.config but viewData is empty. -->" );

				return sb.ToString();
			}

			sb.Append( "<script language=\"javascript\" type=\"text/javascript\">\r\n" );

			foreach ( var keyValuePair in viewData ) {
				sb.Append( "\t\tvar dataPool_" + keyValuePair.Key + " = " );
				sb.Append( JavaScriptConvert.SerializeObject( keyValuePair.Value ) + ";\r\n" );
			}

			sb.Remove( sb.Length - 2 , 2 );

			sb.Append( "\r\n\t</script>" );

			return sb.ToString();
		}
Example #6
0
        public static double Compute(string expression)
        {
            var exp = expression.Replace(" ", "");
            var cons = new List<string>();
            var sb = new StringBuilder();
            foreach (char c in exp)
            {

                if (c == '+' || c == '-' || c == '*' || c == '/' || c == '(' || c == ')')
                {
                    if (sb.Length > 0)
                    {
                        cons.Add(sb.ToString());
                        sb.Clear();
                    }
                    cons.Add(c.ToString());

                }
                else
                {
                    sb.Append(c);
                }
            }
            if (sb.Length > 0)
            {
                cons.Add(sb.ToString());
            }
            cons.ForEach(Console.WriteLine);
            return 0D;
        }
    static void GetWords(string textLine)
    {
        StringBuilder word = new StringBuilder();
        foreach (char symbol in textLine)
        {
            if (char.IsLetter(symbol))
            {
                word.Append(symbol);
            }
            else
            {
                if (word.Length > 0)
                {
                    AddWordToHashSet(word.ToString());
                }

                word.Clear();
            }
        }

        if (word.Length > 0)
        {
            AddWordToHashSet(word.ToString());
        }
    }
Example #8
0
        public int Update(Model.WebContentType1 model)
        {
            model.Replace4MySQL(); 
            StringBuilder sb = new StringBuilder();
            try
            {
                         WebContentType1 oldModel = GetModel(model);
                        if (model.content_status == 1 && oldModel.content_status != 1)//啟用
                        {
                            WebContentTypeSetupDao _setDao = new WebContentTypeSetupDao(_connStr);
                            WebContentTypeSetup smodel = new WebContentTypeSetup();
                            smodel.site_id = model.site_id;
                            smodel.page_id = model.page_id;
                            smodel.area_id = model.area_id;
                            smodel.web_content_type = "web_content_type1";
                            _setDao.UpdateLimitStatus(smodel);////當前已啟用的個數超過5筆時,使最舊的不啟用,
                        }
                       
                        sb.AppendFormat(@"update web_content_type1  set site_id='{0}',page_id='{1}',area_id='{2}',type_id='{3}',content_title='{4}',content_image='{5}',`content_default`='{6}',content_status='{7}',link_url='{8}',link_page='{9}',link_mode='{10}',update_on='{11}' where content_id={12}",
                            model.site_id, model.page_id, model.area_id, model.type_id, model.content_title, model.content_image, model.content_default, model.content_status, model.link_url, model.link_page, model.link_mode, CommonFunction.DateTimeToString(model.update_on), model.content_id);
                        return _access.execCommand(sb.ToString());
            }
            catch (Exception ex)
            {

                throw new Exception("WebContentType1Dao.Update-->" + ex.Message + sb.ToString(), ex);
            }
          
        }
Example #9
0
        public List<BannerNewsSiteQuery> GetList(BannerNewsSiteQuery bs, out int totalCount)
        {
            StringBuilder sqlfield = new StringBuilder();
            StringBuilder sqlwhere = new StringBuilder();
            StringBuilder sqlorderby = new StringBuilder();
            StringBuilder sql = new StringBuilder();
            sqlfield.AppendLine(@"SELECT	news_site_id,news_site_sort,news_site_status,news_site_mode,news_site_name,news_site_description,news_site_createdate,news_site_updatedate,news_site_ipfrom ");
            sqlfield.AppendLine(@" FROM	banner_news_site where news_site_status = 1 ");
            sql.Append(sqlfield);
            //sql.Append(sqlwhere);
            sqlorderby.AppendFormat(@" ORDER BY news_site_sort DESC ");
            sql.Append(sqlorderby);
            sql.AppendFormat(@" limit {0},{1};", bs.Start, bs.Limit);
            //int totalCount;
            totalCount = 0;
            try
            {
                if (bs.IsPage)
                {
                    DataTable dt = _access.getDataTable("select count(*) from banner_news_site where 1=1 " + sqlwhere);
                    totalCount = int.Parse(dt.Rows[0][0].ToString());
                }
                return _access.getDataTableForObj<BannerNewsSiteQuery>(sql.ToString());
            }
            catch (Exception ex)
            {
                throw new Exception("BannerNewsSiteDao-->GetList" + ex.Message + sql.ToString(), ex);
            }

        }
        public void TestServerToClient()
        {
            IoAcceptor acceptor = new LoopbackAcceptor();
            IoConnector connector = new LoopbackConnector();

            acceptor.SessionOpened += (s, e) => e.Session.Write("B");
            acceptor.MessageSent += (s, e) => e.Session.Close(true);

            acceptor.Bind(new LoopbackEndPoint(1));

            StringBuilder actual = new StringBuilder();

            connector.MessageReceived += (s, e) => actual.Append(e.Message);
            connector.SessionClosed += (s, e) => actual.Append("C");
            connector.SessionOpened += (s, e) => actual.Append("A");

            IConnectFuture future = connector.Connect(new LoopbackEndPoint(1));

            future.Await();
            future.Session.CloseFuture.Await();
            acceptor.Unbind();
            acceptor.Dispose();
            connector.Dispose();

            // sessionClosed() might not be invoked yet
            // even if the connection is closed.
            while (actual.ToString().IndexOf("C") < 0)
            {
                Thread.Yield();
            }

            Assert.AreEqual("ABC", actual.ToString());
        }
		public static string[] Split( string src, char delimiter, params char[] quotedelims )
		{
			ArrayList		strings = new ArrayList();
			StringBuilder	sb = new StringBuilder();
			ArrayList		ar = new ArrayList(quotedelims);
			char			quote_open = Char.MinValue;

			foreach (char c in src) 
			{
				if (c == delimiter && quote_open == Char.MinValue) 
				{
					strings.Add( sb.ToString() );
					sb.Remove( 0, sb.Length );
				}
					
				else if (ar.Contains(c)) 
				{
					if (quote_open == Char.MinValue)
						quote_open = c;
					else if (quote_open == c)
						quote_open = Char.MinValue;
					sb.Append(c);
				}
				else
					sb.Append( c );
			}

			if (sb.Length > 0)
				strings.Add( sb.ToString());

			return (string[])strings.ToArray(typeof(string));
		}
        /// <summary>
        /// Utility method for fetching the install path of a MSI installed product, given the name of that product.
        /// Adapted from: http://stackoverflow.com/questions/3526449/how-to-get-a-list-of-installed-software-products
        /// </summary>
        /// <param name="productName"></param>
        /// <returns></returns>
        public static IEnumerable<string> GetInstallPathOfProduct(string productName)
        {
            StringBuilder productCode = new StringBuilder(39);
            int index = 0;
            while (0 == MsiEnumProducts(index++, productCode))
            {
                Log.Debug("Found ProductCode: {0}", productCode.ToString());
                Int32 productNameLen = 512;
                StringBuilder foundProductName = new StringBuilder(productNameLen);

                MsiGetProductInfo(productCode.ToString(), "ProductName", foundProductName, ref productNameLen);
                Log.Debug("   Product name is: {0}", foundProductName.ToString());

                if (foundProductName.ToString().ToLower().Contains(productName.ToLower()))
                {
                    Log.Debug("   Product name matches: {0}", productName);

                    Int32 installPathLength = 1024;
                    StringBuilder installPath = new StringBuilder(installPathLength);

                    MsiGetProductInfo(productCode.ToString(), "InstallLocation", installPath, ref installPathLength);

                    Log.Debug("   Install path: {0}", installPath.ToString());

                    if (string.IsNullOrWhiteSpace(installPath.ToString()))
                        continue;

                    yield return installPath.ToString();
                }
            }
        }
Example #13
0
        public override string Execute(string[] args, Guid fromAgentID)
		{
            int channel = 0;
            int startIndex = 0;
            
            if (args.Length < 1)
            {
                return "usage: say (optional channel) whatever";
            }
            else if (args.Length > 1)
            {
                if (Int32.TryParse(args[0], out channel))
					startIndex = 1;
            }

            StringBuilder message = new StringBuilder();

			for (int i = startIndex; i < args.Length; i++)
            {
                message.Append(args[i]);
                if (i != args.Length - 1) message.Append(" ");
            }

			Client.Self.Chat(message.ToString(), channel, ChatType.Normal);

            return "Said " + message.ToString();
		}
        /// <summary>
        /// 添加审稿单
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool AddReviewBillContent(ReviewBillContentEntity model, DbTransaction trans = null)
        {
            StringBuilder sqlCommandText = new StringBuilder();
            sqlCommandText.Append(" @CID");
            sqlCommandText.Append(", @JournalID");
            sqlCommandText.Append(", @ItemID");
            sqlCommandText.Append(", @ContentValue");
            sqlCommandText.Append(", @IsChecked");
            sqlCommandText.Append(", @AddUser");

            DbCommand cmd = db.GetSqlStringCommand(String.Format("INSERT INTO dbo.ReviewBillContent ({0},AddDate) VALUES ({1},getdate())", sqlCommandText.ToString().Replace("@", ""), sqlCommandText.ToString()));

            db.AddInParameter(cmd, "@ItemContentID", DbType.Int64, model.ItemContentID);
            db.AddInParameter(cmd, "@CID", DbType.Int64, model.CID);
            db.AddInParameter(cmd, "@JournalID", DbType.Int64, model.JournalID);
            db.AddInParameter(cmd, "@ItemID", DbType.AnsiString, model.ItemID);
            db.AddInParameter(cmd, "@ContentValue", DbType.AnsiString, model.ContentValue);
            db.AddInParameter(cmd, "@IsChecked", DbType.Boolean, model.IsChecked);
            db.AddInParameter(cmd, "@AddUser", DbType.Int64, model.AddUser);
            try
            {
                bool result = false;
                if (trans == null)
                    result = db.ExecuteNonQuery(cmd) > 0;
                else
                    result = db.ExecuteNonQuery(cmd, trans) > 0;
                if (!result)
                    throw new Exception("新增审稿单失败!");
                return result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #15
0
        public string GetNextCommand()
        {
            //try
            //{
                StringBuilder builder = new StringBuilder();
                byte[] b = new byte[1];

                while (this.Receive(b) == 1)
                {
                    string c = ASCIIEncoding.ASCII.GetString(b);

                    builder.Append(c);

                    if (builder.ToString().Contains(CommandSeperator))
                    {
                        return builder.ToString();
                    }
                }
            //}
            //catch (Exception e)
            //{
            //    Close();
            //}

            return null;
        }
Example #16
0
 static string BuildNumberWords(int i)
 {
     StringBuilder sb = new StringBuilder();
     if (i == 1000)
     {
         sb.Append("OneThousand");
         return sb.ToString();
     }
     if (i / 100 > 0)
     {
         sb.Append(string.Format("{0}Hundred", numbers[i/100]));
         if (i % 100 > 0)
             sb.Append("And");
     }
     if (i % 100 == 0)
     {
         return sb.ToString();
     }
     if (i%100 < 20)
     {
         sb.Append(numbers[i%100]);
         return sb.ToString();
     }
     sb.Append(tennumbers[(i%100) / 10]);
     if (i % 10 == 0)
         return sb.ToString();
     sb.Append(numbers[i % 10]);
     return sb.ToString();
 }
    static void Main()
    {
        StringBuilder line = new StringBuilder();
        string pattern = @"(?<![a-zA-Z])[A-Z]+(?![a-zA-Z])";
        Regex regex = new Regex(pattern);

        while (line.ToString() != "END")
        {          
            MatchCollection matches = regex.Matches(line.ToString());

            int offset = 0;
            foreach (Match match in matches)
            {
               string word = match.Value;
               string reversed = Reverse(word);
              
                if (reversed == word)
                {
                    reversed = DoubleEachLetter(reversed);
                }

                int index = match.Index;
                line = line.Remove(index + offset, word.Length);
                line = line.Insert(index + offset, reversed);
                offset += reversed.Length - word.Length;

            }

            Console.WriteLine(SecurityElement.Escape(line.ToString()));
            line = new StringBuilder(Console.ReadLine());
        }
    }
Example #18
0
        public static Dictionary<int, string> GetVolumesForPhysicalDisk(int deviceNumber)
        {
            StringBuilder volName = new StringBuilder(260);
            IntPtr hVolume = FindFirstVolume(volName, volName.Capacity);
            var result = new Dictionary<int, string>();
            if (hVolume == (IntPtr)(-1))
                return result;
            do
            {
                try
                {
                    using (var dev = new DiskDevice(volName.ToString().TrimEnd('\\'), true))
                    {
                        var dn = dev.QueryDeviceNumber();
                        if (dn == null || dn.DeviceNumber != deviceNumber)
                            continue;
                        result[dn.PartitionNumber] = volName.ToString();
                    }
                }
                catch
                {

                }
            } while (FindNextVolume(hVolume, volName, volName.Capacity));

            FindVolumeClose(hVolume);
            return result;
        }
Example #19
0
 public int Insert(Model.WebContentType1 model)
 {
     model.Replace4MySQL();
     StringBuilder sb = new StringBuilder();
     try
     {
             if (model.content_status == 1)//啟用
             {
                 WebContentTypeSetupDao _setDao = new WebContentTypeSetupDao(_connStr);
                 WebContentTypeSetup smodel = new WebContentTypeSetup();
                 smodel.site_id = model.site_id;
                 smodel.page_id = model.page_id;
                 smodel.area_id = model.area_id;
                 smodel.web_content_type = "web_content_type1";
                 _setDao.UpdateLimitStatus(smodel);////當前已啟用的個數超過5筆時,使最舊的不啟用,
             }
           
             sb.AppendFormat(@"insert into web_content_type1(site_id,page_id,area_id,type_id,content_title,content_image,content_default,content_status,link_url,link_page,link_mode,update_on,created_on) 
         values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}')", model.site_id, model.page_id, model.area_id, model.type_id, model.content_title, model.content_image, model.content_default, model.content_status, model.link_url, model.link_page, model.link_mode, CommonFunction.DateTimeToString(model.update_on), CommonFunction.DateTimeToString(model.created_on));
             return _access.execCommand(sb.ToString());
     }
     catch (Exception ex)
     {
         throw new Exception("WebContentType1Dao.Insert-->" + ex.Message + sb.ToString(), ex);
     }
    
 }
Example #20
0
        internal static TestAPIResult TestEndpoint(MVC.Commands.TestAPICommand cmd) {
            var wc = WebRequest.CreateHttp(cmd.EndpointUrl.Trim('/') + "/usages");

            wc.AllowAutoRedirect = false;

            wc.Accept = cmd.Accept;
            wc.Headers.Add("Authorization", string.Format("MetricsEndpoint-Key {0}", cmd.APIKey));

            var sb = new StringBuilder();
            
            try {
                var response = wc.GetResponse() as HttpWebResponse;

                AppendRequest(wc,sb);
                AppendResponse(sb,response);
                
                if(response.StatusCode!=HttpStatusCode.OK) {
                    return TestAPIResult.Failed(sb.ToString());
                }
                return TestAPIResult.IsSuccess(sb.ToString());

            }
            catch(WebException e) {
                AppendRequest(wc,sb);
                AppendResponse(sb,e.Response as HttpWebResponse);

                return TestAPIResult.Failed(sb.ToString());
            }
        }
 /// <summary>
 /// DES加密
 /// </summary>
 /// <param name="str"></param>
 /// <param name="key"></param>
 /// <returns></returns>
 public static string DESEncrypt(string str, string key)
 {
     DESCryptoServiceProvider des = new DESCryptoServiceProvider();
     //把字符串放到byte数组中 
     byte[] inputByteArray = Encoding.Default.GetBytes(str);
     //建立加密对象的密钥和偏移量  
     //原文使用ASCIIEncoding.ASCII方法的GetBytes方法  
     //使得输入密码必须输入英文文本  
     des.Key = ASCIIEncoding.ASCII.GetBytes(key);
     des.IV = ASCIIEncoding.ASCII.GetBytes(key);
     MemoryStream ms = new MemoryStream();
     CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
     //Write  the  byte  array  into  the  crypto  stream  
     //(It  will  end  up  in  the  memory  stream)  
     cs.Write(inputByteArray, 0, inputByteArray.Length);
     cs.FlushFinalBlock();
     //Get  the  data  back  from  the  memory  stream,  and  into  a  string  
     StringBuilder ret = new StringBuilder();
     foreach (byte b in ms.ToArray())
     {
         //Format  as  hex  
         ret.AppendFormat("{0:X2}", b);
     }
     ret.ToString();
     return ret.ToString();
 }
        // ARGH concat and .SPLIT('0') !!!!!!
        static void DecodeInput()
        {
            output = new StringBuilder();

            var curCode = new StringBuilder();

            foreach (var textByte in input)
            {
                foreach (var textBit in textByte)
                {
                    // If 1 add to current code
                    if (textBit == '1') curCode.Append(textBit);

                    // If 0 decode the current char and
                    // reset code.
                    else if (textBit == '0')
                    {
                        // TODO: Possible Errors on empty curCode
                        // ( consequitive zeros )
                        if (curCode.Length > 0)
                        {
                            if (codes.ContainsKey(curCode.ToString()))
                            {
                                output.Append(codes[curCode.ToString()]);
                            }
                            // Check if Key exists ( exceptions )
                        }

                        curCode.Clear();
                    }
                }
            }
        }
        private string GeratePlatformKey(string platformName)
        {
            StringBuilder key = new StringBuilder();
            Random rnd = new Random();
            bool foundKey = false;

            for (int i = 0; i <= 2; i++)
            {
                key.Append(platformName.Substring(rnd.Next(platformName.Length - 1), 1));
            }
            foreach (PlatformData item in this.PlatformList)
            {
                if (item.Abreviation == key.ToString())
                {
                    foundKey = true;
                }
            }
            if (!foundKey)
            {
                return key.ToString();
            }
            else
            {
                return GeratePlatformKey(platformName);
            }
        }
		private string makeWhere(Uri url)
		{
			Stack<string> hostStack = new Stack<string>(url.Host.Split('.'));
			StringBuilder hostBuilder = new StringBuilder('.' + hostStack.Pop());
			string[] pathes = url.Segments;

			StringBuilder sb = new StringBuilder();
			sb.Append("WHERE (");

			bool needOr = false;
			while (hostStack.Count != 0) {
				if (needOr) {
					sb.Append(" OR");
				}

				if (hostStack.Count != 1) {
					hostBuilder.Insert(0, '.' + hostStack.Pop());
					sb.AppendFormat(" host = \"{0}\"", hostBuilder.ToString());
				} else {
					hostBuilder.Insert(0, '%' + hostStack.Pop());
					sb.AppendFormat(" host LIKE \"{0}\"", hostBuilder.ToString());
				}

				needOr = true;
			}

			sb.Append(')');
			return sb.ToString();
		}
Example #25
0
        private void BindData()
        {
            StringBuilder sbSql = new StringBuilder("Select NUMB_SYSLOG,FK_NAME_MENU,FLAG_LOGSORT,FK_NAME_USER,INFO_CONT,INFO_DATE FROM sys_client_syslog WHERE 1=1 ");
            if (txtUserName.Text.Trim() != "")
            {
                sbSql.Append(" AND FK_NAME_USER='" + txtUserName.Text.Trim() + "' ");
            }

            if (cmbOperationType.SelectedIndex > 0)
            {
                sbSql.Append(" AND FLAG_LOGSORT='" + (cmbOperationType.SelectedItem as ComboBoxItem).Content.ToString() + "' ");
            }

            sbSql.Append(" AND INFO_DATE>='" + Convert.ToDateTime(dtpStartDate.SelectedDate).ToShortDateString() + " 00:00:01" + "' AND INFO_DATE<='" + Convert.ToDateTime(dtpEndDate.SelectedDate).ToShortDateString() + " 23:59:59" + "'");

            try
            {
                dbHelper = DBUtility.DbHelperMySQL.CreateDbHelper();
                lvlist.DataContext = dbHelper.GetDataSet(sbSql.ToString()).Tables[0];
                currentTable = dbHelper.GetDataSet(sbSql.ToString()).Tables[0];
            }
            catch (Exception)
            {
                return;
            }
        }
 void ITemplate.Run(ExecuteContext context, TextWriter textWriter)
 {
     var builder = new StringBuilder();
     _executeContextAdapter = new ExecuteContextAdapter(this, context);
     using (var writer = new StringWriter(builder))
     {
         _executeContextAdapter.CurrentWriter = writer;
         OnStart();
         Execute();
         OnEnd();
         _executeContextAdapter.CurrentWriter = null;
     }
     var parent = ResolveLayout(Layout);
     if (parent == null && string.IsNullOrEmpty(Layout))
     {
         var result = builder.ToString();
         textWriter.Write(result);
         return;
     }
     if (parent == null)
     {
         throw new InvalidOperationException("Layout template was not found.");
     }
     parent.SetData(null, ViewBag);
     var exposingParent = parent as ExposingTemplate;
     if (exposingParent == null)
     {
         throw new InvalidOperationException("Unexpected layout template base type.");
     }
     exposingParent._templateVisitor = _templateVisitor;
     var bodyWriter = new TemplateWriter(tw => tw.Write(builder.ToString()));
     _executeContextAdapter.PushBody(bodyWriter);
     _executeContextAdapter.PushSections();
     parent.Run(_executeContextAdapter.Context, textWriter);
 }
        public static string FormatDateTime(DataAvail.Data.DbContext.IDbContextWhereFormatter WhereFormatter, string Where, string[] DateTimeColumns)
        {
            System.Text.StringBuilder sb = new StringBuilder(Where);

            int i = 0;

            foreach (string dtField in DateTimeColumns)
            {
                int fIndex = sb.ToString().IndexOf(i == 0 ? dtField : " " + dtField, i);

                while (fIndex != -1)
                {
                    string str = sb.ToString();

                    fIndex += dtField.Length;

                    //Find first alphabetic character after field's name 
                    char ch = str.ToCharArray().Skip(fIndex).FirstOrDefault(p => char.IsNumber(p));

                    if (ch != char.MinValue)
                    {
                        int dtValF = str.IndexOf(ch, fIndex);

                        if (dtValF != -1)
                        {
                            int dtValE = sb.Length;

                            //Find first not null & not numeric
                            ch = str.ToCharArray().Skip(dtValF).FirstOrDefault(p => char.IsLetter(p));

                            if (ch != char.MinValue)
                                dtValE = str.IndexOf(ch, dtValF);

                            //Substitute invariant value by formatted one

                            string dtVal = str.Substring(dtValF, dtValE - dtValF);

                            System.DateTime dt;

                            if (System.DateTime.TryParse(dtVal, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out dt))
                            {
                                sb.Remove(dtValF, dtValE - dtValF);

                                sb.Insert(dtValF, WhereFormatter.Format(dt) + " ");

                                i = dtValF;

                                fIndex = sb.ToString().IndexOf(dtField, i);

                                continue;
                            }
                        }
                    }

                    fIndex = -1;
                }
            }

            return sb.ToString();
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="flowAuthRoleEntity"></param>
        /// <returns></returns>
        public bool AddFlowAuthRole(FlowAuthRoleEntity flowAuthRoleEntity)
        {
            bool flag = false;
            StringBuilder sqlCommandText = new StringBuilder();
            sqlCommandText.Append(" @JournalID");
            sqlCommandText.Append(", @ActionID");
            sqlCommandText.Append(", @RoleID");

            DbCommand cmd = db.GetSqlStringCommand(String.Format("INSERT INTO dbo.FlowAuthRole ({0}) VALUES ({1})", sqlCommandText.ToString().Replace("@", ""), sqlCommandText.ToString()));

            db.AddInParameter(cmd, "@JournalID", DbType.Int64, flowAuthRoleEntity.JournalID);
            db.AddInParameter(cmd, "@ActionID", DbType.Int64, flowAuthRoleEntity.ActionID);
            db.AddInParameter(cmd, "@RoleID", DbType.Int64, flowAuthRoleEntity.RoleID);

            try
            {
                db.ExecuteNonQuery(cmd);
                flag = true;
            }
            catch (SqlException sqlEx)
            {
                throw sqlEx;
            }
            return flag;
        }
        public IDictionary<string, object> Insert(AdoAdapter adapter, string tableName, IDictionary<string, object> data, IDbTransaction transaction = null,
                                  bool resultRequired = false)
        {
            var table = adapter.GetSchema().FindTable(tableName);
            var dataDictionary = BuildDataDictionary(adapter, data, table);

            string columnList = dataDictionary.Keys.Select(c => c.QuotedName).Aggregate((agg, next) => agg + "," + next);
            string valueList = dataDictionary.Keys.Select(s => "?").Aggregate((agg, next) => agg + "," + next);

            var insertSql = new StringBuilder();
            insertSql.AppendFormat("INSERT INTO {0} ({1}) VALUES ({2});", table.QualifiedName, columnList, valueList);
            if (resultRequired)
            {
                var identityColumn = table.Columns.FirstOrDefault(c => c.IsIdentity);
                if (identityColumn != null)
                {
                    insertSql.AppendFormat(" SELECT * FROM {0} WHERE {1} = LAST_INSERT_ID();", table.QualifiedName,
                                           identityColumn.QuotedName);
                    return ExecuteSingletonQuery(adapter, insertSql.ToString(), dataDictionary.Keys,
                                                 dataDictionary.Values, transaction);
                }
            }
            Execute(adapter, insertSql.ToString(), dataDictionary.Keys, dataDictionary.Values, transaction);
            return null;
        }
Example #30
0
        /// <summary>
        /// Creates an 'Order By' string expression from the query
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public static string ToOrderByLinqExpression(this Query query)
        {
            var orderByStatement = string.Empty;
            var queryEntity = query.RootEntity;
            var orderByBuilder = new StringBuilder();

            if (queryEntity != null && queryEntity.SequenceList.Count > 0)
            {

                //Add each of the sequences into our list:
                foreach (var sequence in queryEntity.SequenceList)
                {

                    orderByBuilder.Append(string.Format("{0} {1}, ",
                        sequence.PropertyName, sequence.Direction.ToString()));

                }

                //trim the last 2 characters off the end (the , and a space):
                orderByStatement = orderByBuilder.ToString().Substring(
                    0, orderByBuilder.ToString().Length - 2);

            }

            return orderByStatement;
        }