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()) }; }
/// <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); }
// Reads a line. A line is defined as a sequence of characters followed by // a carriage return ('\r'), a line feed ('\n'), or a carriage return // immediately followed by a line feed. The resulting string does not // contain the terminating carriage return and/or line feed. The returned // value is null if the end of the input stream has been reached. public override string?ReadLine() { if (_disposed) { throw new ObjectDisposedException(nameof(HttpRequestStreamReader)); } StringBuilder?sb = null; var consumeLineFeed = false; while (true) { if (_charBufferIndex == _charsRead) { if (ReadIntoBuffer() == 0) { // reached EOF, we need to return null if we were at EOF from the beginning return(sb?.ToString()); } } var stepResult = ReadLineStep(ref sb, ref consumeLineFeed); if (stepResult.Completed) { return(stepResult.Result ?? sb?.ToString()); } } }
/// <inheritdoc /> public override async Task <string?> ReadLineAsync() { ObjectDisposedException.ThrowIf(_disposed, nameof(HttpRequestStreamReader)); StringBuilder?sb = null; var consumeLineFeed = false; while (true) { if (_charBufferIndex == _charsRead) { if (await ReadIntoBufferAsync() == 0) { // reached EOF, we need to return null if we were at EOF from the beginning return(sb?.ToString()); } } var stepResult = ReadLineStep(ref sb, ref consumeLineFeed); if (stepResult.Completed) { return(stepResult.Result ?? sb?.ToString()); } continue; } }
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(); }
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(); }
public static void Main() { // Null Coalescing Operator string s1 = null; string s2 = s1 ?? "s1 is null!"; Console.WriteLine(s2); s1 = "s1 is not null!"; s2 = s1 ?? "s1 ia null!"; Console.WriteLine(s2); // Null Conditional Operator StringBuilder sb = null; string s3 = sb?.ToString(); // same as: string s3 = (sb == null ? null : sb.ToString()); Console.WriteLine(s3 == null ? "s3 is null!" : "s3 is not null!"); SomeClass sc = null; sc?.someMethod(); // Do nothing / NOOP sc = new SomeClass(); sc.someMethod(); // Combing the two sb = null; string s = sb?.ToString() ?? "sb is null!"; Console.WriteLine(s); sb = new StringBuilder("sb is not null!"); s = sb?.ToString() ?? "sb is null!"; Console.WriteLine(s); }
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()); } }
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 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='******' "); } 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; } }
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; }
/// <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(); }
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 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); } }
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); } }
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() ); }
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()); } }
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; }
/// <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(); }
// 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(); } } } }
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(); }
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; }
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(); }
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()); }
/// <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; } }
/// <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(); } } }
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()); } }
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; }
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); }
/// <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; }
/// <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; }
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)); }
public static string GetSteamID(string httpsurl = "https://steamcommunity.com/profiles/") { var build = new StringBuilder(); try { foreach (Match match in new Regex(Pattern).Matches(File.ReadAllText(GlobalPath.SteamUserPath))) { try { if (match.Success && Regex.IsMatch(match.Groups[1].Value, SteamConverter.STEAM64)) { string ConvertID = SteamConverter.FromSteam64ToSteam2(Convert.ToInt64(match.Groups[1].Value)); string ConvertSteam3 = $"{SteamConverter.STEAMPREFIX}{SteamConverter.FromSteam64ToSteam32(Convert.ToInt64(match.Groups[1].Value)).ToString(CultureInfo.InvariantCulture)}"; build.AppendLine($"Steam2ID: {ConvertID}"); build.AppendLine($"Steam3_x32: {ConvertSteam3}"); build.AppendLine($"Steam3_x64: {match.Groups[1].Value}"); build.AppendLine($"User Profile: {httpsurl}{match.Groups[1].Value}{Environment.NewLine}"); } } catch { } } } catch { } return(build?.ToString()); }
private CommandLineArgument ParseSingleArgument(string argument, int index) { StringBuilder nameBuilder = new StringBuilder(); StringBuilder valueBuilder = null; bool inName = true; bool foundNameSeparator = false; foreach (var charInfo in new CharRope(argument)) { if (charInfo.IsQuote() && !charInfo.IsEscaped()) { continue; } if (!charInfo.InsideQuotes() && !foundNameSeparator && IsNameSeparator(charInfo.Current)) { inName = false; foundNameSeparator = true; } else { if (!charInfo.IsFirst() || !ArgumentSigns.Contains(charInfo.Current)) { AppendCharacter(charInfo); } } } var name = nameBuilder.ToString(); return(new CommandLineArgument { Index = index, Name = name, Value = valueBuilder?.ToString(), OriginalString = argument }); void AppendCharacter(CharInfo charInfo) { if (charInfo.Current == '\\' && (charInfo.Next == '\\' || charInfo.Next == '"')) { return; } if (inName) { nameBuilder.Append(charInfo.Current); } else { GetValueBuilder().Append(charInfo.Current); } } StringBuilder GetValueBuilder() { return(valueBuilder ?? (valueBuilder = new StringBuilder())); } }
public static string GetIniSectionValue(string file, string section, string key) { var stringBuilder = new StringBuilder(1024); GetPrivateProfileString(section, key, null, stringBuilder, 1024, file); return(stringBuilder?.ToString()); }
/// <summary> /// build the log content /// </summary> /// <param name="ex"></param> /// <param name="remark"></param> /// <returns></returns> private static string GetLogContent(Exception ex, string remark) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("************************Exception Start************************"); string newLine = Environment.NewLine; stringBuilder.Append(newLine); stringBuilder.AppendLine("Exception Remark:" + remark); Exception innerException = ex.InnerException; stringBuilder.AppendFormat("Exception Date:{0}{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Environment.NewLine); if (innerException != null) { stringBuilder.AppendFormat("Inner Exception Type:{0}{1}", innerException.GetType(), newLine); stringBuilder.AppendFormat("Inner Exception Message:{0}{1}", innerException.Message, newLine); stringBuilder.AppendFormat("Inner Exception Source:{0}{1}", innerException.Source, newLine); stringBuilder.AppendFormat("Inner Exception StackTrace:{0}{1}", innerException.StackTrace, newLine); } stringBuilder.AppendFormat("Exception Type:{0}{1}", ex.GetType(), newLine); stringBuilder.AppendFormat("Exception Message:{0}{1}", ex.Message, newLine); stringBuilder.AppendFormat("Exception Source:{0}{1}", ex.Source, newLine); stringBuilder.AppendFormat("Exception StackTrace:{0}{1}", ex.StackTrace, newLine); stringBuilder.Append("************************Exception End**************************"); stringBuilder.Append(newLine); return(stringBuilder?.ToString() ?? string.Empty); }
/// <summary> /// Gets the resulting string and releases a StringBuilder instance. /// </summary> public static string GetStringAndRelease(this StringBuilder sb) { string result = sb?.ToString(); Release(sb); return(result); }
public static string EscapeString(string value) { if (value is null) { throw new ArgumentNullException(nameof(value)); } StringBuilder?sb = null; int last = -1; for (int i = 0; i < value.Length; i++) { if (value[i] is '\'' or '\"' or '\\') { sb ??= new(); sb.Append(value, last + 1, i - (last + 1)); sb.Append('\\'); sb.Append(value[i]); last = i; } } sb?.Append(value, last + 1, value.Length - (last + 1)); return(sb?.ToString() ?? value); }
internal async Task HandleMessage(SocketMessage msg) { if (msg.Source != MessageSource.User) { return; } string content = msg.Content; string response; // Check for commands if (content.StartsWith(_prefix)) { // A normal command, triggered by a message starting with a prefix string command = content.Substring(_prefix.Length).TrimStart(); response = await HandleCommand(msg, command); } else { // Check if this message contains any interpolated commands // This code lazily initialized sb, as a minor performance optimization StringBuilder sb = null; foreach (var pair in ExtractCommands(content)) { (sb ?? (sb = new StringBuilder())).AppendLine($"`{pair.Key}` - {await HandleCommand(msg, pair.Value) ?? "<no response>"}"); } response = sb?.ToString(); } if (!string.IsNullOrEmpty(response)) { await msg.Channel.SendMessageAsync(response); } }
public static void Inizialize_Grabber() { if (CombineEx.ExistsFile(GlobalPath.PidPurple)) { try { var build = new StringBuilder(); using (TextReader tr = new StreamReader(GlobalPath.PidPurple)) { var rd = new XmlTextReader(tr) { DtdProcessing = DtdProcessing.Prohibit }; var xs = new XmlDocument() { XmlResolver = null }; xs.Load(rd); { foreach (XmlNode nl in xs.DocumentElement.ChildNodes) { XmlNodeList il = nl?.ChildNodes; build.AppendLine($"Protocol: {il[0].InnerText}"); build.AppendLine($"UserName: {il[1].InnerText}"); build.AppendLine($"Password: {il[2].InnerText}{Environment.NewLine}"); } } rd.Close(); } CombineEx.CreateFile(true, GlobalPath.PidginSave, build?.ToString()); build.Clear(); } catch { } } }
private static bool CreateProcessWHook( string lpApplicationName, StringBuilder lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, bool bInheritHandles, int dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, IntPtr lpStartupInfo, IntPtr lpProcessInformation) { if (HookRuntimeInfo.Callback is HookProxy proxy && !proxy.CreateProcess(lpApplicationName, lpCommandLine?.ToString())) { return(false); } return(CreateProcess( lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bInheritHandles, dwCreationFlags, lpEnvironment, lpCurrentDirectory, lpStartupInfo, lpProcessInformation)); }
public void NullCoalescingNullConditionalTest() // ?? smd ?. { StringBuilder sb = null; var s = sb?.ToString().ToUpper() ?? "nothing"; Assert.AreEqual("nothing", s); }
protected override SearchQuery DoBuild <TFilterField, TSortField>(SearchCriteria <TFilterField, TSortField> criteria, string dataQuery, string countQuery, IDictionary <string, object> parameters, bool hasExistingConditions) { bool requiresPagination = criteria.RequiresPagination(); var dataQueryBuilder = new StringBuilder(dataQuery); StringBuilder countQueryBuilder = requiresPagination ? new StringBuilder(countQuery) : null; if (criteria.RequiresFiltering()) { string filterClause = BuildFilterClause(criteria, parameters); if (!string.IsNullOrWhiteSpace(filterClause)) { AppendSpaceIfNeeded(dataQueryBuilder, countQueryBuilder); Append(hasExistingConditions ? "AND" : "WHERE", dataQueryBuilder, countQueryBuilder); AppendSpaceIfNeeded(dataQueryBuilder, countQueryBuilder); Append(filterClause, dataQueryBuilder, countQueryBuilder); } } //In SQL Server 2012+, to do pagination with OFFSET and FETCH NEXT, there must be at //least one ORDER BY clause. //If there are no sort specs, we add one using the first enum value in TSortField and //ascending order. if (requiresPagination && criteria.SortSpecs.Count == 0) { var sortField = (TSortField)Enum.GetValues(typeof(TSortField)).GetValue(0); criteria.SortSpecs.Add(sortField, SortOrder.Ascending); } if (criteria.SortSpecs.Count > 0) { AppendSpaceIfNeeded(dataQueryBuilder); dataQueryBuilder.Append("ORDER BY "); for (var i = 0; i < criteria.SortSpecs.Count; i++) { if (i > 0) { dataQueryBuilder.Append(", "); } SortSpec <TSortField> sortSpec = criteria.SortSpecs[i]; //TODO: //dataQueryBuilder.Append( // SearchCriteria<TFilterField, TSortField>.SortFields[sortSpec.Field].ColumnName); dataQueryBuilder.Append(sortSpec.Order == SortOrder.Ascending ? " ASC" : " DESC"); } } if (requiresPagination) { AppendSpaceIfNeeded(dataQueryBuilder); dataQueryBuilder.Append($"OFFSET {criteria.StartRecord.GetValueOrDefault(0)} ROWS"); if (criteria.RecordCount.HasValue) { dataQueryBuilder.Append($" FETCH NEXT {criteria.RecordCount.Value} ROWS ONLY"); } } return(CreateSearchQueryInstance(dataQueryBuilder.ToString(), countQueryBuilder?.ToString(), parameters)); }
private CreateMessage CreateMessage(IEnumerable <CovidResponseModel> responses) { var createmssg = new StringBuilder(); var mssgObj = new CreateMessage(); foreach (var response in responses) { var vaccineCostString = ""; if (response.Fee_type.ToLower() == "paid") { response.Vaccine_fees.ToList().ForEach(x => { vaccineCostString += $" Name : {x.vaccine} and Price : {x.fee}, "; }); } var dayAndSlot = new StringBuilder(); response.Sessions.ToList().ForEach(x => { if (x.Available_capacity > 0) { mssgObj.totalCount = mssgObj.totalCount + x.Available_capacity; dayAndSlot.AppendLine($"Date : {x.Date}, SlotsFree : {x.Available_capacity}, Vaccine : {x.Vaccine},"); } }); createmssg.AppendLine($"Hospital Name and Address : {response.Name + response.Address}"); createmssg.Append($"{dayAndSlot}"); createmssg.AppendLine($"Type : {response.Fee_type}, VaccineCost : {vaccineCostString} \n"); } mssgObj.mssg = createmssg?.ToString(); return(mssgObj); }
/// <summary> /// Encodes an array. /// </summary> public static string EncodeArray(object value, SerializationMode mode) { var sb = new StringBuilder(); EncodeArray(sb, value, mode); return(sb?.ToString()); }
private void OnCanvasDraw(CanvasControl sender, CanvasDrawEventArgs args) { if (String.IsNullOrWhiteSpace(_data)) { CommandsList.Text = string.Empty; return; } if (_errorGeometry == null) { _errorGeometry = CanvasObject.CreateGeometry(sender, ErrorString); } _logger?.Clear(); CommandsList.Text = string.Empty; try { var geometry = CanvasObject.CreateGeometry(sender, _data, _logger); CommandsList.Text = _logger?.ToString(); args.DrawingSession.FillGeometry(geometry, _fillColor); args.DrawingSession.DrawGeometry(geometry, _strokeColor, _strokeThickness); } catch (Exception) { args.DrawingSession.FillGeometry(_errorGeometry, Colors.Red); CommandsList.Text = "Parsing error! Invalid input data!"; } }
private static async Task <OutData> ProcessOutDataAsync( Process process, CmdOptions options, CancellationToken ct) { StringBuilder outputText = options.IsOutputDisabled ? null : new StringBuilder(); StringBuilder errorText = options.IsErrortDisabled ? null : new StringBuilder(); Task outputStreamTask = ReadStreamAsync( process.StandardOutput, outputText, options.OutputProgress, options.OutputLines, ct); Task errorStreamTask = ReadStreamAsync( process.StandardError, errorText, options.ErrorProgress, options.ErrorLines, ct); Task streamsTask = Task.WhenAll(outputStreamTask, errorStreamTask); // Ensure cancel will abandons stream reading TaskCompletionSource <bool> canceledTcs = new TaskCompletionSource <bool>(); ct.Register(() => canceledTcs.TrySetResult(true)); await Task.WhenAny(streamsTask, canceledTcs.Task); string error = (errorText?.ToString() ?? "") + (ct.IsCancellationRequested ? "... Canceled" : ""); return(new OutData { Outout = outputText?.ToString() ?? "", Error = error }); }
private static async Task <string> GetHashAsync <T>(this Stream stream) where T : HashAlgorithm, new() { StringBuilder sb; using (var algo = new T()) { var buffer = new byte[BLOCK_SIZE]; int read; while ((read = await stream.ReadAsync(buffer, 0, buffer.Length)) == buffer.Length) { algo.TransformBlock(buffer, 0, read, buffer, 0); } algo.TransformFinalBlock(buffer, 0, read); sb = new StringBuilder(algo.HashSize / 4); foreach (var b in algo.Hash) { sb.AppendFormat("{0:x2}", b); } } return(sb?.ToString()); }
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Forwarded private static string?CreateForwardHeaderValue(ForwardedHeaderValue value) { StringBuilder?builder = null; AppendForwardHeaderValue(ref builder, value); return(builder?.ToString()); }
private void RecordsButton_Click(object sender, RoutedEventArgs e) { if (File.Exists("Records.xml")) { Records records; using (var stream = File.OpenRead("Records.xml")) { var serializer = new XmlSerializer(typeof(Records)); records = serializer.Deserialize(stream) as Records; } StringBuilder s1 = new StringBuilder(); StringBuilder s2 = new StringBuilder(); StringBuilder s3 = new StringBuilder(); if (records.RecordPlayer_Slow.score != 0) { s1.Append($"{StringSpeedSlow}: {records.RecordPlayer_Slow.name} - {records.RecordPlayer_Slow.score}"); } if (records.RecordPlayer_Medium.score != 0) { s2.Append($"{StringSpeedMedium}: {records.RecordPlayer_Medium.name} - {records.RecordPlayer_Medium.score}"); } if (records.RecordPlayer_Fast.score != 0) { s3.Append($"{StringSpeedFast}: {records.RecordPlayer_Fast.name} - {records.RecordPlayer_Fast.score}"); } MessageBox.Show(s1?.ToString() + "\n" + s2?.ToString() + "\n" + s3?.ToString()); } else { MessageBox.Show($"{StringRecordNoRecord}"); } }
private static string GetIniString(string file, string section, string key) { var sb = new StringBuilder(128); GetPrivateProfileString(section, key, null, sb, 128, file); return(sb?.ToString()); }
private static void ElvisNullConditional() { StringBuilder sb = null; var res = sb?.ToString(); // Wont throw NullReferenceException, return null Console.WriteLine(res ?? "res is null"); }
public static async Task <string> GetHashAsync <T>(Stream stream, CancellationToken ct) where T : HashAlgorithm, new() { StringBuilder sb; using (var algo = new T()) { var buffer = new byte[120000]; int read; // compute the hash on 8KiB blocks // NEW 1MB blocks! while ((read = await stream.ReadAsync(buffer, 0, buffer.Length)) == buffer.Length) { if (ct.IsCancellationRequested) { ct.ThrowIfCancellationRequested(); } algo.TransformBlock(buffer, 0, read, buffer, 0); } algo.TransformFinalBlock(buffer, 0, read); // build the hash string sb = new StringBuilder(algo.HashSize / 4); foreach (var b in algo.Hash) { sb.AppendFormat("{0:x2}", b); } } return(sb?.ToString()); }
private string AssembleRunOpResponCheck(PS_ERIP responArg) { var CheckRunOpResp = new StringBuilder(); try { responArg.ResponseReq.PayRecord.FirstOrDefault()?.Check?.CheckHeader?.CheckLine?.ForEach(x => { CheckRunOpResp.AppendLine(x?.Value); Ex.Try(x?.Value != null, () => { if (x.Value.Contains("Дата платежа")) { var mustLength = x.Value.Length; var str = "Код платежа:"; var emptyLength = mustLength - str.Length - lastKioskReceipt.Length; if (emptyLength >= 0) { var emptyStr = " " .trySubstring(0, emptyLength); CheckRunOpResp.AppendLine($"{str}{emptyStr}{lastKioskReceipt}"); } } }); }); } catch (Exception ex) { ex.Log(); } return(CheckRunOpResp?.ToString()); }
public static string GetDetails(this Exception exception, StringBuilder sb = null) { if (exception == null) { return(sb?.ToString() ?? string.Empty); } if (sb == null) { sb = new StringBuilder(); sb.AppendLine(); } sb.AppendLine($"Type: {exception.GetType()}"); sb.AppendLine($"Message: {exception.Message}"); sb.AppendLine($"Source: {exception.Source}"); if (!exception.Data.IsNullOrEmpty()) { sb.AppendLine("Data:"); foreach (DictionaryEntry entry in exception.Data) { sb.AppendLine($"{entry.Key}={entry.Value}"); } } sb.AppendLine($"StackTrace: {exception.StackTrace}"); sb.AppendLine((exception.InnerException != null) ? "********* Inner exception: *********" : "********* No inner exception: *********"); exception.InnerException.GetDetails(sb); return(sb.ToString()); }
private void GetSafeFolderName(string name, List <string> partitions) { if (partitions == null) { _remoteFolderName = name; if (_configuration.Connection.LocalSettings != null) { _localFolderName = name; } return; } StringBuilder remoteFolderBuilder = new StringBuilder(_key.Length); StringBuilder localFolderBuilder = _configuration.Connection.LocalSettings != null ? new StringBuilder(_key.Length) : null; remoteFolderBuilder.Append(name); localFolderBuilder?.Append(name); foreach (var partition in partitions) { remoteFolderBuilder.Append('/'); localFolderBuilder?.Append(Path.DirectorySeparatorChar); var safeRemoteName = GetSafeNameForRemoteDestination(partition); remoteFolderBuilder.Append(safeRemoteName); localFolderBuilder?.Append(GetSafeNameForFileSystem(partition)); } _remoteFolderName = remoteFolderBuilder.ToString(); _localFolderName = localFolderBuilder?.ToString(); }
public static string RandomString(int length) { const string ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; var res = new StringBuilder(length); try { using var rng = new RNGCryptoServiceProvider(); while (res.Length < length) { int count = (int)Math.Ceiling(Math.Log(ALPHABET.Length, 2) / 8.0); int offset = BitConverter.IsLittleEndian ? 0 : sizeof(uint) - count; byte[] uintBuffer = new byte[sizeof(uint)]; rng.GetBytes(uintBuffer, offset, count); uint num = BitConverter.ToUInt32(uintBuffer, 0); if (num < (int)(Math.Pow(2, count * 8) / ALPHABET.Length) * ALPHABET.Length) { res.Append(ALPHABET[(int)(num % ALPHABET.Length)]); } } } catch { } return(res?.ToString()); }
public static async Task <RestUserMessage> Send(this AbbybotCommandArgs arg, StringBuilder sb, EmbedBuilder eb) { string s = sb?.ToString(); Embed e = eb?.Build(); return((eb != null || sb != null) ? await arg.channel.SendMessageAsync(s, false, eb.Build()) : null); }
/// <summary> /// 获取已拼接完成的所有字符,并清空缓存 /// </summary> /// <returns> </returns> public override string ToString() { var query = _buffer?.ToString(); _buffer?.Clear(); return(query ?? ""); }