string TestEmail(Settings settings)
    {
        string email = settings.Email;
        string smtpServer = settings.SmtpServer;
        string smtpServerPort = settings.SmtpServerPort.ToString();
        string smtpUserName = settings.SmtpUserName;
        string smtpPassword = settings.SmtpPassword;
        string enableSsl = settings.EnableSsl.ToString();

        var mail = new MailMessage
        {
            From = new MailAddress(email, smtpUserName),
            Subject = string.Format("Test mail from {0}", smtpUserName),
            IsBodyHtml = true
        };
        mail.To.Add(mail.From);
        var body = new StringBuilder();
        body.Append("<div style=\"font: 11px verdana, arial\">");
        body.Append("Success");
        if (HttpContext.Current != null)
        {
            body.Append(
                "<br /><br />_______________________________________________________________________________<br /><br />");
            body.AppendFormat("<strong>IP address:</strong> {0}<br />", Utils.GetClientIP());
            body.AppendFormat("<strong>User-agent:</strong> {0}", HttpContext.Current.Request.UserAgent);
        }

        body.Append("</div>");
        mail.Body = body.ToString();

        return Utils.SendMailMessage(mail, smtpServer, smtpServerPort, smtpUserName, smtpPassword, enableSsl.ToString());
    }
 internal static string Join(object thisob, string separator, bool localize)
 {
     StringBuilder builder = new StringBuilder();
     uint num = Microsoft.JScript.Convert.ToUint32(LateBinding.GetMemberValue(thisob, "length"));
     if (num > 0x7fffffff)
     {
         throw new JScriptException(JSError.OutOfMemory);
     }
     if (num > builder.Capacity)
     {
         builder.Capacity = (int) num;
     }
     for (uint i = 0; i < num; i++)
     {
         object valueAtIndex = LateBinding.GetValueAtIndex(thisob, (ulong) i);
         if ((valueAtIndex != null) && !(valueAtIndex is Missing))
         {
             if (localize)
             {
                 builder.Append(Microsoft.JScript.Convert.ToLocaleString(valueAtIndex));
             }
             else
             {
                 builder.Append(Microsoft.JScript.Convert.ToString(valueAtIndex));
             }
         }
         if (i < (num - 1))
         {
             builder.Append(separator);
         }
     }
     return builder.ToString();
 }
Esempio n. 3
1
        public string ComposeSentence(string[] words)
        {
            StringBuilder text = new StringBuilder();
            bool hasSpace = true;

            for (int i = 0; i < words.Length; i++)
            {
                if (IsNoSpacePunctuation(words[i])) text.Append(words[i]);
                else if (IsReverseSpacePunctuation(words[i]))
                {
                    hasSpace = false;
                    text.Append(" " + words[i]);
                }
                else if (i == 0)
                {
                    text.Append(StaticHelper.FirstLetterToUpper(words[i]));
                }
                else
                {
                    if (words[i - 1] == ".") words[i] = StaticHelper.FirstLetterToUpper(words[i]);

                    if (hasSpace) text.Append(" " + words[i]);
                    else text.Append(words[i]);
                    hasSpace = true;
                }
            }

            string newText = text.ToString().Trim();
            return newText;
        }
Esempio n. 4
1
		internal static string FormatMessage (string msg)
		{
			StringBuilder sb = new StringBuilder ();
			bool wasWs = false;
			foreach (char ch in msg) {
				if (ch == ' ' || ch == '\t') {
					if (!wasWs)
						sb.Append (' ');
					wasWs = true;
					continue;
				}
				wasWs = false;
				sb.Append (ch);
			}

			var doc = TextDocument.CreateImmutableDocument (sb.ToString());
			foreach (var line in doc.Lines) {
				string text = doc.GetTextAt (line.Offset, line.Length).Trim ();
				int idx = text.IndexOf (':');
				if (text.StartsWith ("*", StringComparison.Ordinal) && idx >= 0 && idx < text.Length - 1) {
					int offset = line.EndOffsetIncludingDelimiter;
					msg = text.Substring (idx + 1) + doc.GetTextAt (offset, doc.TextLength - offset);
					break;
				}
			}
			return msg.TrimStart (' ', '\t');
		}
Esempio n. 5
1
        public string ByteArrayToString(byte[] data)
        {
            StringBuilder sb = new StringBuilder();
            byte[] newdata = new byte[3];

            // 2 bytes 3 characters
            // First, bits with weight 4,8,16,32,64 of byte 1
            // Second, bits with weight 32,64,128 of byte 2 plus bits with weight 1,2 from byte 1
            // Third, bits with  weight 1,2,4,8,16 of byte 2
            newdata[0] = (byte)(((int)data[0]& 0x7c)/4);
            newdata[1] = (byte)((((int)data[0] & 0x03)*8) + (((int)data[1] & 0xe0) / 32));
            newdata[2] = (byte)((int)data[1] & 0x1f);

            for (int i = 0; i < newdata.Length; i++)
            {
                if (newdata[i] >= 0x01 && newdata[i] <= 0x1a)
                    sb.Append(((char)((((int)newdata[i])) + 65 - 0x01)));
                else if (newdata[i] == 0x1b)
                    sb.Append('-');
                else if (newdata[i] == 0x00)
                    sb.Append(' ');
            }

            return sb.ToString();
        }
Esempio n. 6
1
        static StringBuilder BuildExceptionReport(Exception e, StringBuilder sb, int d)
        {
            if (e == null)
                return sb;

            sb.AppendFormat("Exception of type `{0}`: {1}", e.GetType().FullName, e.Message);

            var tle = e as TypeLoadException;
            if (tle != null)
            {
                sb.AppendLine();
                Indent(sb, d);
                sb.AppendFormat("TypeName=`{0}`", tle.TypeName);
            }
            else // TODO: more exception types
            {
            }

            if (e.InnerException != null)
            {
                sb.AppendLine();
                Indent(sb, d); sb.Append("Inner ");
                BuildExceptionReport(e.InnerException, sb, d + 1);
            }

            sb.AppendLine();
            Indent(sb, d); sb.Append(e.StackTrace);

            return sb;
        }
Esempio n. 7
1
        protected string HandlerData(HttpContext context)
        {
            StringBuilder sbResult = new StringBuilder();
            try
            {
                string strPath = CY.Utility.Common.RequestUtility.GetQueryString("path");
                string strName = CY.Utility.Common.RequestUtility.GetQueryString("name");
                if (string.IsNullOrEmpty(strPath) || string.IsNullOrEmpty(strName))
                {
                    return sbResult.Append("{success:false,msg:'传递的参数错误ofx001!'}").ToString();
                }

                string appPath = CY.Utility.Common.RequestUtility.CurPhysicalApplicationPath;
                string dirPath = appPath + "Content\\Instrument\\Img\\";
                string fileName = strPath.Substring(strPath.LastIndexOf("/"), strPath.Length);
                if (File.Exists(dirPath + fileName))
                {
                    File.Delete(dirPath + fileName);
                    sbResult.Append("{success:true}");
                }
                else
                {
                    return sbResult.Append("{success:false,msg:'该文件件不存在!'}").ToString();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
            }
            return sbResult.ToString();
        }
Esempio n. 8
1
 public override void ToString(StringBuilder sb, IQueryWithParams query)
 {
     if (this.op == CriteriaOperator.Like ||
         this.op == CriteriaOperator.NotLike)
     {
         var valueCriteria = this.right as ValueCriteria;
         if (query.Dialect.IsCaseSensitive() &&
             !ReferenceEquals(null, valueCriteria) &&
             valueCriteria.Value is string)
         {
             sb.Append("UPPER(");
             this.left.ToString(sb, query);
             sb.Append(this.op == CriteriaOperator.Like ? ") LIKE UPPER(" : ") NOT LIKE UPPER(");
             this.right.ToString(sb, query);
             sb.Append(")");
         }
         else
         {
             this.left.ToString(sb, query);
             sb.Append(this.op == CriteriaOperator.Like ? " LIKE " : " NOT LIKE ");
             this.right.ToString(sb, query);
         }
     }
     else
     {
         this.left.ToString(sb, query);
         sb.Append(opText[(int)this.op - (int)CriteriaOperator.AND]);
         this.right.ToString(sb, query);
     }
 }
Esempio n. 9
0
        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();
        }
Esempio n. 10
0
        /// <summary>
        /// 通过confirmId删除Ass_Step表的信息
        /// </summary>
        /// <param name="confirmId"></param>
        /// <returns></returns>
        public static bool DeleteAssStepByConfirmId(long confirmId)
        {
            bool result = false;
            try
            {
                StringBuilder strSql = new StringBuilder();
                strSql.Append("delete from Ass_Step where ConfirmId=@confirmId");
                strSql.Append(";select @@IDENTITY");
                SqlParameter[] parameters = {
                    new SqlParameter("@confirmId", SqlDbType.BigInt),

                                        };
                parameters[0].Value = confirmId;
                int count = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
                if (count == 1)
                {
                    result = true;
                }
            }
            catch (Exception e)
            {
                Log4Net.LogWrite("err", "Controler.Med_Ass.AddDiBao:" + e.Message);
            }
            return result;
        }
Esempio n. 11
0
 /** implementation of method from OperationsPtg*/
 public override String ToFormulaString(String[] operands)
 {
     StringBuilder buffer = new StringBuilder();
     buffer.Append(MINUS);
     buffer.Append(operands[0]);
     return buffer.ToString();
 }
Esempio n. 12
0
 private int ConsumeUntil(char c1, char c2, StringBuilder collector)
 {
     while (!BufferEof)
     {
         if (CharsLeft == 0)
         {
             EnsureBuffer();
         }
         var terminatorPos = -1;
         if (c2 == char.MinValue)
         {
             terminatorPos = Array.IndexOf(buffer, c1, bufferPos, bufferLength - bufferPos);
         }
         else
         {
             for (int i = bufferPos; i < bufferLength; i++)
             {
                 if (buffer[i] == c1 || buffer[i] == c2)
                 {
                     terminatorPos = i;
                     break;
                 }
             }
         }
         if (terminatorPos >= 0)
         {
             collector?.Append(buffer, bufferPos, terminatorPos - bufferPos);
             bufferPos = terminatorPos;
             return(buffer[terminatorPos]);
         }
         collector?.Append(buffer, bufferPos, bufferLength - bufferPos);
         bufferPos = bufferLength;
     }
     return(-1);
 }
Esempio n. 13
0
        public static float CalculatedMovementDifficultyAt(int tile, bool perceivedStatic, int?ticksAbs = null, StringBuilder explanation = null)
        {
            Tile tile2 = Find.WorldGrid[tile];

            if (explanation != null && explanation.Length > 0)
            {
                explanation.AppendLine();
            }
            if (tile2.biome.impassable || tile2.hilliness == Hilliness.Impassable)
            {
                explanation?.Append("Impassable".Translate());
                return(1000f);
            }
            float num = 0f + tile2.biome.movementDifficulty;

            explanation?.Append(tile2.biome.LabelCap + ": " + tile2.biome.movementDifficulty.ToStringWithSign("0.#"));
            float num2 = HillinessMovementDifficultyOffset(tile2.hilliness);
            float num3 = num + num2;

            if (explanation != null && num2 != 0f)
            {
                explanation.AppendLine();
                explanation.Append(tile2.hilliness.GetLabelCap() + ": " + num2.ToStringWithSign("0.#"));
            }
            return(num3 + GetCurrentWinterMovementDifficultyOffset(tile, ticksAbs ?? GenTicks.TicksAbs, explanation));
        }
Esempio n. 14
0
        internal override void AppendCodeStringStmt(StringBuilder res, PythonAst ast, CodeFormattingOptions format) {
            format.ReflowComment(res, this.GetProceedingWhiteSpace(ast));
            res.Append("with");
            var itemWhiteSpace = this.GetListWhiteSpace(ast);
            int whiteSpaceIndex = 0;
            for (int i = 0; i < _items.Length; i++) {
                var item = _items[i];
                if (i != 0) {
                    if (itemWhiteSpace != null) {
                        res.Append(itemWhiteSpace[whiteSpaceIndex++]);
                    }
                    res.Append(',');
                }

                item.ContextManager.AppendCodeString(res, ast, format);
                if (item.Variable != null) {
                    if (itemWhiteSpace != null) {
                        res.Append(itemWhiteSpace[whiteSpaceIndex++]);
                    } else {
                        res.Append(' ');
                    }
                    res.Append("as");
                    item.Variable.AppendCodeString(res, ast, format);
                }
            }

            _body.AppendCodeString(res, ast, format);
        }
Esempio n. 15
0
        /// <summary>
        /// Adds the Path Element to the Path.
        /// </summary>
        /// <param name="pathBuilder">CanvasPathBuilder object</param>
        /// <param name="currentPoint">The last active location in the Path before adding
        /// the Path Element</param>
        /// <param name="lastElement">The previous PathElement in the Path.</param>
        /// <param name="logger">For logging purpose. To log the set of CanvasPathBuilder
        /// commands, used for creating the CanvasGeometry, in string format.</param>
        /// <returns>The latest location in the Path after adding the Path Element</returns>
        public override Vector2 CreatePath(CanvasPathBuilder pathBuilder, Vector2 currentPoint,
                                           ref ICanvasPathElement lastElement, StringBuilder logger)
        {
            // Calculate coordinates
            var controlPoint1 = new Vector2(_x1, _y1);
            var controlPoint2 = new Vector2(_x2, _y2);
            var point         = new Vector2(_x, _y);

            if (IsRelative)
            {
                controlPoint1 += currentPoint;
                controlPoint2 += currentPoint;
                point         += currentPoint;
            }

            // Save the second absolute control point so that it can be used by the following
            // SmoothCubicBezierElement (if any)
            _absoluteControlPoint2 = controlPoint2;

            // Execute command
            pathBuilder.AddCubicBezier(controlPoint1, controlPoint2, point);

            // Log command
            logger?.Append($"{Indent}pathBuilder.AddCubicBezier(new Vector2({controlPoint1.X}, {controlPoint1.Y})");
            logger?.Append($", new Vector2({controlPoint2.X}, {controlPoint2.Y})");
            logger?.AppendLine($", new Vector2({point.X}, {point.Y}));");

            // Set Last Element
            lastElement = this;
            // Return current point
            return(point);
        }
Esempio n. 16
0
	AsEffectEntity LoadEntity( string sourcePath)
	{
		if( false == AsGameMain.GetOptionState( OptionBtnType.OptionBtnType_EffectShow))
			return null;
	
		GameObject obj = ResourceLoad.LoadGameObject( sourcePath);
		if( obj == null)
			return null;
		
		GameObject go = GameObject.Instantiate( obj) as GameObject;
		if( go == null)
			return null;
		
		AsEffectEntity entity =  go.AddComponent<AsEffectEntity>();
		
		int hash = entity.GetHashCode();
		StringBuilder sb = new StringBuilder();
		sb.Append( entity.name);
		sb.Append( "_key:");
		sb.Append( hash);
//		string entityname = entity.name + "_key:" + hash;
		entity.name = sb.ToString();
		entity.Id = hash;
		entity.EntityObject = go;
		entity.gameObject.layer = LayerMask.NameToLayer( "Effect");
//		entity.isStatic = true;
		AddEffectEntity( entity);
		
		return entity;
	}
Esempio n. 17
0
        /// <summary>
        /// ����һ������
        /// </summary>
        public int Add(ECSMS.Model.EC_UserSmsAccount model)
        {
            StringBuilder strSql=new StringBuilder();
            strSql.Append("insert into EC_UserSmsAccount(");
            strSql.Append("UserId,SmsType,InitNum,LargessNum,LeaveNum,AwokeNum)");
            strSql.Append(" values (");
            strSql.Append("@UserId,@SmsType,@InitNum,@LargessNum,@LeaveNum,@AwokeNum)");
            strSql.Append(";select @@IDENTITY");
            SqlParameter[] parameters = {
                    new SqlParameter("@UserId", SqlDbType.Int,4),
                    new SqlParameter("@SmsType", SqlDbType.VarChar,10),
                    new SqlParameter("@InitNum", SqlDbType.Int,4),
                    new SqlParameter("@LargessNum", SqlDbType.Int,4),
                    new SqlParameter("@LeaveNum", SqlDbType.Int,4),
                    new SqlParameter("@AwokeNum", SqlDbType.Int,4)};
            parameters[0].Value = model.UserId;
            parameters[1].Value = model.SmsType;
            parameters[2].Value = model.InitNum;
            parameters[3].Value = model.LargessNum;
            parameters[4].Value = model.LeaveNum;
            parameters[5].Value = model.AwokeNum;

            object obj = DbHelperSQL.GetSingle(strSql.ToString(),parameters);
            if (obj == null)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(obj);
            }
        }
Esempio n. 18
0
        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
            // don't touch temp data if there's no work to perform
            if (!_notifier.List().Any())
                return;

            var tempData = filterContext.Controller.TempData;

            // initialize writer with current data
            var sb = new StringBuilder();
            if (tempData.ContainsKey(TempDataMessages)) {
                sb.Append(tempData[TempDataMessages]);
            }

            // accumulate messages, one line per message
            foreach (var entry in _notifier.List()) {
                sb.Append(Convert.ToString(entry.Type))
                    .Append(':')
                    .AppendLine(entry.Message.ToString())
                    .AppendLine("-");
            }

            // assign values into temp data
            // string data type used instead of complex array to be session-friendly
            tempData[TempDataMessages] = sb.ToString();
        }
Esempio n. 19
0
 /// <summary>
 /// 增加一条数据
 /// </summary>
 public int Add(RuRo.Model.TB_CONSENT_FORM model)
 {
     StringBuilder strSql = new StringBuilder();
     strSql.Append("insert into TB_CONSENT_FORM(");
     strSql.Append("Path,PatientName,PatientID,Consent_From,date)");
     strSql.Append(" values (");
     strSql.Append("@Path,@PatientName,@PatientID,@Consent_From,@date)");
     strSql.Append(";select @@IDENTITY");
     SqlParameter[] parameters = {
             new SqlParameter("@Path", SqlDbType.NVarChar,200),
             new SqlParameter("@PatientName", SqlDbType.VarChar,50),
             new SqlParameter("@PatientID", SqlDbType.Int,4),
             new SqlParameter("@Consent_From", SqlDbType.NVarChar,150),
              new SqlParameter("@date",SqlDbType.DateTime)
                                 };
     parameters[0].Value = model.Path;
     parameters[1].Value = model.PatientName;
     parameters[2].Value = model.PatientID;
     parameters[3].Value = model.Consent_From;
     parameters[4].Value = model.Date;
     object obj = DbHelperSQL_SY.GetSingleSY(strSql.ToString(), parameters);
     if (obj == null)
     {
         return 0;
     }
     else
     {
         return Convert.ToInt32(obj);
     }
 }
Esempio n. 20
0
    protected void Page_Load(object sender, EventArgs e)
    {
        CurrentMaster.Title.TitleText = GetString("Task.ViewHeader");
        CurrentMaster.Title.TitleImage = GetImageUrl("CMSModules/CMS_Integration/tasks.png");

        IntegrationTaskInfo ti = IntegrationTaskInfoProvider.GetIntegrationTaskInfo(TaskID);
        // Set edited object
        EditedObject = ti;

        if (ti != null)
        {
            CurrentMaster.Title.TitleText += " (" + HTMLHelper.HTMLEncode(ti.TaskTitle) + ")";

            string direction = GetString(ti.TaskIsInbound ? "integration.inbound" : "integration.outbound");

            // Prepare task description
            StringBuilder sbTaskInfo = new StringBuilder();
            sbTaskInfo.Append("<table>");
            sbTaskInfo.Append("<tr><td class=\"Title Grid\">" + GetString("integration.taskdirection") + ":</td><td>" + direction + "</td></tr>");
            sbTaskInfo.Append("<tr><td class=\"Title Grid\">" + GetString("integration.tasktype") + ":</td><td>" + ti.TaskType + "</td></tr>");
            sbTaskInfo.Append("<tr><td class=\"Title Grid\">" + GetString("integration.tasktime") + ":</td><td>" + ti.TaskTime + "</td></tr>");
            sbTaskInfo.Append("</table>");

            string objectType = ti.TaskObjectType;
            if (ti.TaskNodeID > 0)
            {
                objectType = PredefinedObjectType.DOCUMENT;
            }
            viewDataSet.ObjectType = objectType;
            viewDataSet.DataSet = GetDataSet(ti.TaskData, ti.TaskType, ti.TaskObjectType);
            viewDataSet.AdditionalContent = sbTaskInfo.ToString();
        }
    }
        //取消打折
        private void btnUndoDiscount_Click(object sender, EventArgs e)
        {
            var pars = new List<string>();
            var vals = new List<string>();

            vals.AddRange(m_Seats.Select(x => x.systemId).ToList());
            int count = m_Seats.Count;
            for (int i = 0; i < count; i++ )
            {
                pars.Add("systemId");
            }

            var orders = dao.get_orders(pars, vals, "or");
            StringBuilder sb = new StringBuilder();
            foreach (var order in orders)
            {
                reset_order_money(order);
                sb.Append(@" update [Orders] set money=");
                sb.Append(order.money.ToString());
                sb.Append(" , donorEmployee=null, donorExplain=null, donorTime=null where id=");
                sb.Append(order.id.ToString());
            }
            if (!dao.execute_command(sb.ToString()))
            {
                BathClass.printErrorMsg("取消打折失败,请重试!");
                return;
            }
        }
Esempio n. 22
0
		private static void MergeFiles(){
			Console.WriteLine( "Please paste or type the manifest file path here..." );

			String manifestPath = Console.ReadLine();

			if (manifestPath == null) throw new InvalidDataException();

			if (Directory.Exists( manifestPath ) == false){
				Console.WriteLine( "File isn't exsited." );
				return;
			}

			List<String> paths = Directory.GetFiles( manifestPath, "*.sql" ).ToList();

			var stringBuilder = new StringBuilder();

			foreach (var path in paths){
				if (File.Exists( path ) == false) continue;

				stringBuilder.Append( "\r\nGO\n\r\n" );
				stringBuilder.Append( File.ReadAllText( path, Encoding.GetEncoding( 65001 ) ) );
			}

			if (File.Exists( @"r:\\output.sql" )) File.Delete( @"r:\\output.sql" );

			File.WriteAllText( @"r:\\output.sql", stringBuilder.ToString() );
		}
Esempio n. 23
0
        /// <summary>
        /// 更新购药月封顶线
        /// </summary>
        /// <returns></returns>
        public bool UpdateDrugMonthMax(decimal monthDrugMax)
        {
            bool result = false;
            try
            {
                StringBuilder strSql = new StringBuilder();
                strSql.Append(" update T_Med_MonthDrugMax set");
                strSql.Append(" MonthDrugMax=@MonthDrugMax ");
                SqlParameter[] parameters =
                {
                    new SqlParameter("@MonthDrugMax", SqlDbType.Decimal)
                };
                parameters[0].Value = monthDrugMax;

                if (SqlHelper.ExecuteNonQuery(SqlHelper.connString, CommandType.Text, strSql.ToString(), parameters) > 0) //更改成功 影响条数为1
                {
                    result = true;  //更新成功设置为true
                }
            }
            catch (Exception e)
            {
                Log4Net.LogWrite("err", "Med_DAL:DAL_MonthDrugMax//UpdateDrugMonthMax" + e.Message);  //发生异常,记录
            }
            return result;
        }
Esempio n. 24
0
        public string HtmlAttributeEncode(string s)
        {
            if (String.IsNullOrEmpty (s))
                return String.Empty;
            var needEncode = s.Any(c => c == '&' || c == '"' || c == '<' || c == '\'');

            if (!needEncode)
                return s;

            var output = new StringBuilder();
            var len = s.Length;
            for (var i = 0; i < len; i++)
                switch (s[i])
                {
                    case '&':
                        output.Append("&amp;");
                        break;
                    case '"':
                        output.Append("&quot;");
                        break;
                    case '<':
                        output.Append("&lt;");
                        break;
                case '\'':
                    output.Append ("&#39;");
                    break;
                    default:
                        output.Append(s[i]);
                        break;
                }

            return output.ToString();
        }
Esempio n. 25
0
 /// <summary>
 /// 在嵌入的资源文件中查找相应的图片
 /// </summary>
 /// <param name="name">资源图片的文件名称+扩展名</param>
 /// <returns></returns>
 public static Image GetImage(string name)
 {
     Image image = null;
     try
     {
         if (!string.IsNullOrEmpty(name))
         {
             StringBuilder sb = new StringBuilder();
             if (name[0] != '.')
                 sb.Append(AppResource.CurrentAssemblyName + "." + name);
             else
                 sb.Append(AppResource.CurrentAssemblyName + name);
             using (Stream stream = CurrentAssembly.GetManifestResourceStream(sb.ToString()))
             {
                 if (stream == null)
                     throw new Exception("加载资源文件失败");
                 else
                     image = Image.FromStream(stream);
             }
         }
     }
     catch (Exception ex)
     {
         Debug.WriteLine("AssemblyHelper.GetImage(string)->" + ex.Message);
         throw ex;
     }
     return image;
 }
Esempio n. 26
0
        /// <summary>
        /// ����һ������
        /// </summary>
        public int Add(SeoWebSite.Model.odds_bz model)
        {
            StringBuilder strSql=new StringBuilder();
            strSql.Append("insert into odds_bz(");
            strSql.Append("companyID,scheduleID,home,draw,away,time)");
            strSql.Append(" values (");
            strSql.Append("@companyID,@scheduleID,@home,@draw,@away,@time)");
            strSql.Append(";select @@IDENTITY");
            SqlParameter[] parameters = {
                    new SqlParameter("@companyID", SqlDbType.Int,4),
                    new SqlParameter("@scheduleID", SqlDbType.Int,4),
                    new SqlParameter("@home", SqlDbType.Float,8),
                    new SqlParameter("@draw", SqlDbType.Float,8),
                    new SqlParameter("@away", SqlDbType.Float,8),
                    new SqlParameter("@time", SqlDbType.DateTime)};
            parameters[0].Value = model.companyID;
            parameters[1].Value = model.scheduleID;
            parameters[2].Value = model.home;
            parameters[3].Value = model.draw;
            parameters[4].Value = model.away;
            parameters[5].Value = model.time;

            object obj = DbHelperSQL.GetSingle(strSql.ToString(),parameters);
            if (obj == null)
            {
                return 1;
            }
            else
            {
                return Convert.ToInt32(obj);
            }
        }
Esempio n. 27
0
        public static string CheckBoxList(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> listInfo, IDictionary<string, object> htmlAttributes)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw new ArgumentException("The argument must have a value", "name");
            }

            if (listInfo == null)
            {
                throw new ArgumentNullException("listInfo");
            }

            var sb = new StringBuilder();

            foreach (SelectListItem info in listInfo)
            {
                var builder = new TagBuilder("input");
                if (info.Selected)
                {
                    builder.MergeAttribute("checked", "checked");
                }

                builder.MergeAttributes(htmlAttributes);
                builder.MergeAttribute("type", "checkbox");
                builder.MergeAttribute("value", info.Value);
                builder.MergeAttribute("name", name);
                builder.InnerHtml = info.Text;
                sb.Append(builder.ToString(TagRenderMode.Normal));
                sb.Append("<br />");
            }

            return sb.ToString();
        }
        public static String Replace(this String s, String oldValue, String newValue, StringComparison comparisonType)
        {
            if (s == null)
            {
                throw new ArgumentNullException("s");
            }
            if (oldValue == null)
            {
                throw new ArgumentNullException("oldValue");
            }
            if (oldValue.Equals(String.Empty))
            {
                throw new ArgumentException("String cannot be of zero length.", "oldValue");
            }

            StringBuilder sb = new StringBuilder();

            int previousIndex = 0;
            int index = s.IndexOf(oldValue, comparisonType);
            while (index != -1)
            {
                sb.Append(s.Substring(previousIndex, index - previousIndex));
                sb.Append(newValue);
                index += oldValue.Length;

                previousIndex = index;
                index = s.IndexOf(oldValue, index, comparisonType);
            }
            sb.Append(s.Substring(previousIndex));

            return sb.ToString();
        }
Esempio n. 29
0
        public static string ForceLineEndings(string fileData, LineEndingType type)
        {
            var ret = new StringBuilder(fileData.Length);

            string ending;
            switch(type)
            {
                case LineEndingType.Windows:
                    ending = "\r\n";
                    break;
                case LineEndingType.Posix:
                    ending = "\n";
                    break;
                case LineEndingType.MacOS9:
                    ending = "\r";
                    break;
                default:
                    throw new Exception("Specify an explicit line ending type");
            }

            foreach (var line in fileData.Split('\n'))
            {
                var fixedLine = line.Replace("\r", "");
                ret.Append(fixedLine);
                ret.Append(ending);
            }

            return ret.ToString();
        }
Esempio n. 30
0
 /**
  * Process a property.
  */
 protected internal void Process(StringBuilder buf, String lang) {
     buf.Append("<rdf:li xml:lang=\"");
     buf.Append(lang);
     buf.Append("\" >");
     buf.Append(this[lang]);
     buf.Append("</rdf:li>");
 }
Esempio n. 31
0
        /// <summary>
        /// Shorten input text to a desired length, preserving words and appending the
        /// specified trailer.
        /// </summary>
        /// <param name="input"></param>
        /// <param name="length"></param>
        /// <param name="trailer"></param>
        /// <returns>A string with the trailer attached if the string greater than length</returns>
        public static string AbbreviateText(this string input, int length, string trailer = "…")
        {
            if (string.IsNullOrEmpty(input))
                throw new ArgumentNullException("input");

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

            StringBuilder output = new StringBuilder(length + 20); //Add room for a word not breaking and the trailer

            string[] words = input.Split(new char[] { ' ' });
            int i = 0;
            while (((output.Length + words[i].Length + trailer.Length) < (length - trailer.Length))
                    && (i < words.GetUpperBound(0)))
            {
                output.Append(words[i]);
                output.Append(" ");
                i++;
            }

            if (i < words.GetUpperBound(0)) //We exited the loop before reaching the end of the array - which would normally be the case.
            {
                output.Remove(output.Length - 1, 1); //Remove the ending space before attaching the trailer.
                output.Append(trailer);
            }
            else
            {
                output.Append(words[i]);
            }

            return output.ToString();
        }
Esempio n. 32
0
        /// <summary>
        /// 通过fid删除Ass_Confirm表的信息
        /// </summary>
        /// <param name="fid"></param>
        /// <returns></returns>
        public static bool DeleteConfirmByFid(long fid)
        {
            bool result = false;
            try
            {
                StringBuilder strSql = new StringBuilder();
                strSql.Append("delete from Ass_Confirm where Fid=@fid");
                strSql.Append(";select @@IDENTITY");
                SqlParameter[] parameters = {
                    new SqlParameter("@fid", SqlDbType.BigInt),

                                        };
                parameters[0].Value = fid;
                int count = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
                if (count == 1)
                {
                    result = true;
                }
            }
            catch (Exception e)
            {
                Log4Net.LogWrite("err", "error:" + e.Message);
            }
            return result;
        }
Esempio n. 33
0
        public override String ToString()
        {
            StringBuilder buffer = new StringBuilder();

            buffer.Append("[FBI]\n");
            buffer.Append("    .xBasis               = ")
                .Append("0x").Append(HexDump.ToHex(XBasis))
                .Append(" (").Append(XBasis).Append(" )");
            buffer.Append(Environment.NewLine);
            buffer.Append("    .yBasis               = ")
                .Append("0x").Append(HexDump.ToHex(YBasis))
                .Append(" (").Append(YBasis).Append(" )");
            buffer.Append(Environment.NewLine);
            buffer.Append("    .heightBasis          = ")
                .Append("0x").Append(HexDump.ToHex(HeightBasis))
                .Append(" (").Append(HeightBasis).Append(" )");
            buffer.Append(Environment.NewLine);
            buffer.Append("    .scale                = ")
                .Append("0x").Append(HexDump.ToHex(Scale))
                .Append(" (").Append(Scale).Append(" )");
            buffer.Append(Environment.NewLine);
            buffer.Append("    .indexToFontTable     = ")
                .Append("0x").Append(HexDump.ToHex(IndexToFontTable))
                .Append(" (").Append(IndexToFontTable).Append(" )");
            buffer.Append(Environment.NewLine);

            buffer.Append("[/FBI]\n");
            return buffer.ToString();
        }
Esempio n. 34
0
    public static void ReplaceTarget(List<string> words)
    {
        using (StreamReader reader = new StreamReader("test.txt"))
        {
            using (StreamWriter writer = new StreamWriter("temp.txt"))
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(@"\b(");
                foreach (string word in words) sb.Append(word + "|");

                sb.Remove(sb.Length - 1, 1);
                sb.Append(@")\b");

                string pattern = @sb.ToString();
                Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);

                for (string line; (line = reader.ReadLine()) != null; )
                {
                    string newLine = rgx.Replace(line, "");
                    writer.WriteLine(newLine);
                }
            }
        }

        File.Delete("test.txt");
        File.Move("temp.txt", "test.txt");
    }
Esempio n. 35
0
        private TokenType SkipNumber(char ch, StringBuilder buffer, ref int hash)
        {
            StringHasher hasher = StringHasher.Create();

            if (ch == '-')
            {
                hasher.AddChar(ch);
                buffer?.Append(ch);
                ch = this.NextChar();
            }

            if (!Tokenizer.IsDigit(ch))
            {
                return(TokenType.Error);
            }

            ch = this.SkipDigits(ch, buffer, ref hasher);

            if (ch == '.')
            {
                hasher.AddChar(ch);
                buffer?.Append(ch);
                ch = this.NextChar();

                if (!Tokenizer.IsDigit(ch))
                {
                    return(TokenType.Error);
                }

                ch = this.SkipDigits(ch, buffer, ref hasher);
            }

            if (ch == 'e' || ch == 'E')
            {
                hasher.AddChar(ch);
                buffer?.Append(ch);
                ch = this.NextChar();

                if (ch == '-' || ch == '+')
                {
                    hasher.AddChar(ch);
                    buffer?.Append(ch);
                    ch = this.NextChar();
                }

                if (!Tokenizer.IsDigit(ch))
                {
                    return(TokenType.Error);
                }

                this.SkipDigits(ch, buffer, ref hasher);
            }

            hash = hasher.HashValue;
            Debug.Assert(buffer == null || StringHasher.HashSubstring(buffer.ToString(), 0, buffer.Length) == hash);

            return(TokenType.Number);
        }
Esempio n. 36
0
 public void Write(string value)
 {
     Guard.AgainstNull(value, nameof(value));
     lock (locker)
     {
         ThrowIfFlushed();
         InitBuilder();
         Builder?.Append(value);
     }
 }
Esempio n. 37
0
        /// <summary>
        /// Adds the Path Element to the Path.
        /// </summary>
        /// <param name="pathBuilder">CanvasPathBuilder object</param>
        /// <param name="currentPoint">The last active location in the Path before adding
        /// the Path Element</param>
        /// <param name="lastElement">The previous PathElement in the Path.</param>
        /// <param name="logger">For logging purpose. To log the set of CanvasPathBuilder
        /// commands, used for creating the CanvasGeometry, in string format.</param>
        /// <returns>The latest location in the Path after adding the Path Element</returns>
        public override Vector2 CreatePath(CanvasPathBuilder pathBuilder, Vector2 currentPoint,
                                           ref ICanvasPathElement lastElement, StringBuilder logger)
        {
            // Calculate coordinates
            // Check if the last element was a Cubic Bezier
            Vector2 controlPoint1;
            var     cubicBezier = lastElement as CubicBezierElement;

            if (cubicBezier != null)
            {
                // Reflect the second control point of the cubic bezier over the current point. The
                // resulting point will be the first control point of this Bezier.
                controlPoint1 = Utils.Reflect(cubicBezier.GetControlPoint(), currentPoint);
            }
            // Or if the last element was s Smooth Cubic Bezier
            else
            {
                var smoothCubicBezier = lastElement as SmoothCubicBezierElement;
                // If the last element was a Smooth Cubic Bezier then reflect its second control point
                // over the current point. The resulting point will be the first control point of this
                // Bezier. Otherwise, if the last element was not a Smooth Cubic Bezier then the
                // currentPoint will be the first control point of this Bezier
                controlPoint1 = smoothCubicBezier != null
                    ? Utils.Reflect(smoothCubicBezier.GetControlPoint(), currentPoint)
                    : currentPoint;
            }

            var controlPoint2 = new Vector2(_x2, _y2);
            var point         = new Vector2(_x, _y);

            if (IsRelative)
            {
                controlPoint2 += currentPoint;
                point         += currentPoint;
            }

            // Save the second absolute control point so that it can be used by the following
            // SmoothCubicBezierElement (if any)
            _absoluteControlPoint2 = controlPoint2;

            // Execute command
            pathBuilder.AddCubicBezier(controlPoint1, controlPoint2, point);

            // Log command
            logger?.Append($"{Indent}pathBuilder.AddCubicBezier(new Vector2({controlPoint1.X}, {controlPoint1.Y})");
            logger?.Append($", new Vector2({controlPoint2.X}, {controlPoint2.Y})");
            logger?.AppendLine($", new Vector2({point.X}, {point.Y}));");

            // Set Last Element
            lastElement = this;
            // Return current point
            return(point);
        }
Esempio n. 38
0
        public static bool IsValidTileForNewSettlement(int tile, StringBuilder reason = null)
        {
            Tile tile2 = Find.WorldGrid[tile];

            if (!tile2.biome.canBuildBase)
            {
                reason?.Append("CannotLandBiome".Translate(tile2.biome.LabelCap));
                return(false);
            }
            if (!tile2.biome.implemented)
            {
                reason?.Append("BiomeNotImplemented".Translate() + ": " + tile2.biome.LabelCap);
                return(false);
            }
            if (tile2.hilliness == Hilliness.Impassable)
            {
                reason?.Append("CannotLandImpassableMountains".Translate());
                return(false);
            }
            Settlement settlement = Find.WorldObjects.SettlementBaseAt(tile);

            if (settlement != null)
            {
                if (reason != null)
                {
                    if (settlement.Faction == null)
                    {
                        reason.Append("TileOccupied".Translate());
                    }
                    else if (settlement.Faction == Faction.OfPlayer)
                    {
                        reason.Append("YourBaseAlreadyThere".Translate());
                    }
                    else
                    {
                        reason.Append("BaseAlreadyThere".Translate(settlement.Faction.Name));
                    }
                }
                return(false);
            }
            if (Find.WorldObjects.AnySettlementBaseAtOrAdjacent(tile))
            {
                reason?.Append("FactionBaseAdjacent".Translate());
                return(false);
            }
            if (Find.WorldObjects.AnyMapParentAt(tile) || Current.Game.FindMap(tile) != null || Find.WorldObjects.AnyWorldObjectOfDefAt(WorldObjectDefOf.AbandonedSettlement, tile))
            {
                reason?.Append("TileOccupied".Translate());
                return(false);
            }
            return(true);
        }
Esempio n. 39
0
 public static bool EnjoyableOutsideNow(Map map, StringBuilder outFailReason = null)
 {
     if (map.weatherManager.RainRate >= 0.25f)
     {
         outFailReason?.Append(map.weatherManager.curWeather.label);
         return(false);
     }
     if (!map.gameConditionManager.AllowEnjoyableOutsideNow(map, out var reason))
     {
         outFailReason?.Append(reason.label);
         return(false);
     }
     return(true);
 }
Esempio n. 40
0
 public StringBuilderWrapper(StringBuilder builder, string wrapper, bool diff = false)
 {
     Builder = builder;
     Wrapper = wrapper;
     Diff    = diff;
     if (Diff)
     {
         Builder?.Append(Wrapper[0]);
     }
     else
     {
         Builder?.Append(wrapper);
     }
 }
Esempio n. 41
0
 internal static void AppendContentRow(
     this StringBuilder sb,
     ProjectInfo projectInfo,
     UnitUnderTest unitUnderTest,
     OperationUnderTest operationUnderTest,
     TestScenario testScenario,
     string separator,
     INameFormatter nameFormatter)
 {
     sb?.Append($"{nameFormatter.SpecialCasedWordToSentence(projectInfo.Name)}{separator}");
     sb?.Append($"{nameFormatter.SpecialCasedWordToSentence(unitUnderTest.Namespace)}{separator}");
     sb?.Append($"{nameFormatter.SpecialCasedWordToSentence(operationUnderTest.ClassName)}{separator}");
     sb?.AppendLine($"\"{nameFormatter.CreateTestScenarioDescription(testScenario.Name, operationUnderTest.ClassName)}\"");
 }
Esempio n. 42
0
        private bool CompareList(string depth, IList from, IList to, StringBuilder builder)
        {
            var fromCount = from.Count;
            var toCount   = to.Count;

            var changed = false;
            var shared  = Math.Min(fromCount, toCount);
            var i       = 0;

            foreach (var item in from)
            {
                if (i >= shared)
                {
                    break;
                }
                var toItem = to[i];
                //compare items
                if (CompareObject(depth + "[" + i + "]", item, toItem, builder))
                {
                    changed = true;
                }
                ++i;
            }

            if (from.Count > to.Count)
            {
                //removed last in from
                for (int j = shared; j < from.Count; j++)
                {
                    builder?.Append(depth + "[" + j + "] removed: ");
                    PrintObject(from[j], builder);
                    builder?.AppendLine();
                }
                changed = true;
            }
            else
            {
                //added last in to
                for (int j = shared; j < to.Count; j++)
                {
                    builder?.Append(depth + "[" + j + "] added: ");
                    PrintObject(to[j], builder);
                    builder?.AppendLine();
                }
                changed = true;
            }
            return(changed);
        }
Esempio n. 43
0
        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);
        }
 private static void ParseToDictionary(object obj, IEnumerable <XElement> elements, StringBuilder ParseErrors)
 {
     foreach (var element in elements)
     {
         try
         {
             if (element.Name != _Pair_)
             {
                 throw new Exception($"Item.Name '{element.Name}' supposed to be {_Pair_}.");
             }
             var KeyElement   = element.Element(_KEY_);
             var ValueElement = element.Element(_VALUE_);
             var key          = ParseXmlRecursive(KeyElement, ParseErrors);
             var value        = ParseXmlRecursive(ValueElement, ParseErrors);
             var keyType      = GetTypeByAttribute(KeyElement);
             var valueType    = GetTypeByAttribute(ValueElement);
             var method       = obj.GetType().GetMethod("Add", new Type[] { keyType, valueType });
             method.Invoke(obj, new object[] { key, value });
         }
         catch (Exception ex)
         {
             ParseErrors?.Append($"{ex.Message}{Environment.NewLine}{element.ToString()}{Environment.NewLine}");
         }
     }
 }
Esempio n. 45
0
        private static Packet ReadPacket(Stream ms, StringBuilder log)
        {
            var len = ReadLine(ms).ToInt(-1);

            log?.Append(len);
            if (len <= 0)
            {
                return(null);
            }
            //if (len <= 0) throw new InvalidDataException();

            var buf = new Byte[len + 2];
            var p   = 0;

            while (p < buf.Length)
            {
                // 等待,直到读完需要的数据,避免大包丢数据
                var count = ms.Read(buf, p, buf.Length - p);
                if (count <= 0)
                {
                    break;
                }

                p += count;
            }

            var pk = new Packet(buf, 0, p - 2);

            log?.AppendFormat(" {0}", pk.ToStr(null, 0, 1024)?.TrimEnd());

            return(pk);
        }
 /// <summary>
 ///
 /// </summary>
 /// <param name="builder"></param>
 /// <param name="condition"></param>
 /// <param name="text"></param>
 public static void AppendIf(this StringBuilder builder, bool condition, string text)
 {
     if (condition)
     {
         builder?.Append(text);
     }
 }
        StringBuilder RenderLogEvent(LogEventInfo logEvent, StringBuilder preallocated = null)
        {
            var           orgLength = preallocated?.Length ?? 0;
            StringBuilder output    = null;

            try
            {
                var nextDelimiter = "";
                var mtp           = logEvent.MessageTemplateParameters;

                foreach (var parameter in mtp)
                {
                    if (parameter.Format == null)
                    {
                        continue;
                    }

                    if (output == null)
                    {
                        output = preallocated ?? new StringBuilder();
                        output.Append("[");
                    }

                    var space = new StringWriter();

                    if (logEvent.Properties != null &&
                        logEvent.Properties.TryGetValue(parameter.Name, out var value))
                    {
                        if (parameter.CaptureType == CaptureType.Normal)
                        {
                            var formatString = string.Concat("{0:", parameter.Format, "}");
                            space.Write(formatString, value);
                        }
                        else
                        {
                            space.Write(value);
                        }
                    }

                    output.Append(nextDelimiter);
                    nextDelimiter = ",";
                    JsonConverter.SerializeObject(space.ToString(), output);
                }

                return(output);
            }
            catch
            {
                if (output != null && preallocated != null)
                {
                    preallocated.Length = orgLength;    // truncate/unwind faulty output
                }
                output = null;
                throw;
            }
            finally
            {
                output?.Append("]");
            }
        }
 protected void CheckAddNewLine()
 {
     if (result.ToString() != "")
     {
         result?.Append(Environment.NewLine);
     }
 }
Esempio n. 49
0
        /// <summary>
        /// internal multiple parameter method.
        /// </summary>
        /// <param name="strb">String string builder.</param>
        /// <param name="x">Some integer.</param>
        /// <param name="y">Some string.</param>
        /// <param name="action">Some action.</param>
        /// <returns>Some function.</returns>
        internal Func <int, int> InternalMultipleParameter(ref StringBuilder strb, int x, string y, Action <int> action)
        {
            strb?.Append(x)?.Append(y);
            action?.Invoke(x);

            return(InternalInstanceFunc);
        }
Esempio n. 50
0
        public static string EnsureOnlyLetterDigitOrWhiteSpace(this string text)
        {
            StringBuilder cleanedInput = null;

            for (var i = 0; i < text.Length; ++i)
            {
                var currentChar = text[i];
                var charIsValid = char.IsLetterOrDigit(currentChar) || char.IsWhiteSpace(currentChar);

                if (charIsValid)
                {
                    cleanedInput?.Append(currentChar);
                }
                else
                {
                    if (cleanedInput != null)
                    {
                        continue;
                    }
                    cleanedInput = new StringBuilder();
                    if (i > 0)
                    {
                        cleanedInput.Append(text.Substring(0, i));
                    }
                }
            }

            return(cleanedInput == null ? text : cleanedInput.ToString());
        }
Esempio n. 51
0
        private void ConsumeEscapedCodePoint(StringBuilder valueBuilder)
        {
            var ch = _reader.Read();

            // EOF
            if (ch < 0)
            {
                valueBuilder?.Append(REPLACEMENT_CHAR);
                return;
            }

            // Hex encoded code point
            int hexDigit;

            if (!TryParseHexDigit(ch, out hexDigit))
            {
                valueBuilder?.Append((char)ch);
                return;
            }

            int codePoint = hexDigit;
            int hexDigits = 1;

            while (hexDigits < 6 && (ch = _reader.Peek()) >= 0 && TryParseHexDigit(ch, out hexDigit))
            {
                _reader.Read();
                codePoint = (codePoint << 4) + hexDigit;
                hexDigits++;
            }
            TryConsumeWhitespace();

            if (valueBuilder != null)
            {
                if (codePoint == 0 || codePoint > MAX_CODE_POINT || IsSurrogateCodePoint(codePoint))
                {
                    valueBuilder.Append(REPLACEMENT_CHAR);
                }
                else if (codePoint <= char.MaxValue)
                {
                    valueBuilder.Append((char)codePoint);
                }
                else
                {
                    valueBuilder.Append(char.ConvertFromUtf32(codePoint));
                }
            }
        }
Esempio n. 52
0
        protected override void UpdateTimerTick()
        {
            var db = KCDatabase.Instance;

            if (!db.RelocatedEquipments.Any())
            {
                return;
            }

            if (_isInSortie)
            {
                return;
            }

            if (NotifiesSquadronRelocation)
            {
                StringBuilder sb = null;
                foreach (var corps in db.BaseAirCorps.Values.Where(corps =>
                                                                   (NotifiesNormalMap && db.MapArea[corps.MapAreaID].MapType == 0) ||
                                                                   (NotifiesEventMap && db.MapArea[corps.MapAreaID].MapType == 1)))
                {
                    var targetSquadrons = corps.Squadrons.Values.Where(sq => sq.State == 2 && !_notifiedEquipments.Contains(sq.EquipmentID) && (DateTime.Now - sq.RelocatedTime) >= RelocationSpan);

                    if (targetSquadrons.Any())
                    {
                        sb = sb?.Append(", ") ?? new StringBuilder();

                        sb.Append(string.Join(", ", targetSquadrons.Select(sq =>
                                                                           $"#{corps.MapAreaID} {corps.Name} 第{sq.SquadronID}中隊 ({sq.EquipmentInstance.NameWithLevel})")));

                        foreach (var sq in targetSquadrons)
                        {
                            _notifiedEquipments.Add(sq.EquipmentID);
                        }
                    }
                }

                if (sb != null)
                {
                    Notify(sb.ToString() + "の配置転換が完了しました。母港に入り直すと更新されます。");
                }
            }

            if (NotifiesEquipmentRelocation)
            {
                var targets = db.RelocatedEquipments.Where(kv => !_notifiedEquipments.Contains(kv.Key) &&
                                                           (DateTime.Now - kv.Value.RelocatedTime) >= RelocationSpan);

                if (targets.Any())
                {
                    Notify($"{string.Join(", ", targets.Select(kv => kv.Value.EquipmentInstance.NameWithLevel))} の配置転換が完了しました。母港に入り直すと更新されます。");

                    foreach (var t in targets)
                    {
                        _notifiedEquipments.Add(t.Key);
                    }
                }
            }
        }
Esempio n. 53
0
        public static string StripSpaces(string str)
        {
            var length = str.Length;

            if (length == 0)
            {
                return(string.Empty);
            }

            var nonSpaceStart = 0;

            while (str[nonSpaceStart] == Space)
            {
                if (++nonSpaceStart == length)
                {
                    return(" ");
                }
            }

            StringBuilder sb = null;
            int           i;

            for (i = nonSpaceStart; i < length; ++i)
            {
                if (str[i] != Space)
                {
                    continue;
                }

                var j = i + 1;
                while (j < length && str[j] == Space)
                {
                    ++j;
                }

                if (j == length)
                {
                    return(sb?.Append(str, nonSpaceStart, i - nonSpaceStart).ToString() ?? str.Substring(nonSpaceStart, i - nonSpaceStart));
                }

                if (j == i + 1)
                {
                    continue;
                }

                sb ??= new StringBuilder(length);

                sb.Append(str, nonSpaceStart, i - nonSpaceStart + 1);
                nonSpaceStart = j;
                i             = j - 1;
            }

            if (sb == null)
            {
                return(nonSpaceStart == 0 ? str : str.Substring(nonSpaceStart, length - nonSpaceStart));
            }

            return(i > nonSpaceStart?sb.Append(str, nonSpaceStart, i - nonSpaceStart).ToString() : sb.ToString());
        }
Esempio n. 54
0
        /// <summary>
        /// Conberts an element notation of complex property into
        /// </summary>
        /// <param name="xamlReader">
        /// On entry this XTextReader must be on Element start tag;
        /// on exit - on EndElement tag.
        /// </param>
        /// <param name="htmlWriter">
        /// May be null, in which case we are skipping xaml content
        /// without producing any html output
        /// </param>
        /// <param name="inlineStyle">
        /// StringBuilder containing a value for STYLE attribute.
        /// </param>
        /// <param name="context">Conversion context</param>
        private static bool HandleComplexProperty(XmlReader xamlReader, XmlWriter htmlWriter, StringBuilder inlineStyle, HtmlFromXamlContext context)
        {
            Debug.Assert(xamlReader.NodeType == XmlNodeType.Element);

            // ship Table.Columns (unhandled)
            if (!xamlReader.Name.Contains(".") || xamlReader.Name == "Table.Columns")
            {
                return(false);
            }

            if (xamlReader.Name.EndsWith(".TextDecorations"))
            {
                var level       = 1;
                var decorations = new List <string>();
                while (ReadNextToken(xamlReader))
                {
                    if (xamlReader.NodeType == XmlNodeType.Element)
                    {
                        if (!xamlReader.IsEmptyElement)
                        {
                            level++;
                        }
                        if (xamlReader.Name == "TextDecoration")
                        {
                            if (xamlReader.HasAttributes && xamlReader.MoveToAttribute("Location"))
                            {
                                if (xamlReader.Value == "Strikethrough")
                                {
                                    decorations.Add("line-through");
                                }
                                else if (xamlReader.Value == "Underline")
                                {
                                    decorations.Add("underline");
                                }
                            }
                        }
                    }
                    else if (xamlReader.NodeType == XmlNodeType.EndElement)
                    {
                        level--;
                    }
                    if (level <= 0)
                    {
                        if (decorations.Any())
                        {
                            inlineStyle?.Append($"text-decoration:{string.Join(" ", decorations)};");
                        }
                        break;
                    }
                }
                return(false);
            }
            else
            {
                // Skip the element representing the unhandled complex property
                WriteElementContent(xamlReader, /*htmlWriter:*/ null, /*inlineStyle:*/ null, context);
                return(true);
            }
        }
Esempio n. 55
0
        private static ValidationFailure ExtractFormatItems(string formatString, out List <FormatStringItem> formatStringItems)
        {
            formatStringItems = new List <FormatStringItem>();
            var           curlyBraceCount           = 0;
            StringBuilder currentFormatItemBuilder  = null;
            var           isEscapingOpenCurlyBrace  = false;
            var           isEscapingCloseCurlyBrace = false;

            for (var i = 0; i < formatString.Length; i++)
            {
                var currentChar  = formatString[i];
                var previousChar = i > 0 ? formatString[i - 1] : '\0';

                if (currentChar == '{')
                {
                    if (previousChar == '{' && !isEscapingOpenCurlyBrace)
                    {
                        curlyBraceCount--;
                        isEscapingOpenCurlyBrace = true;
                        currentFormatItemBuilder = null;
                        continue;
                    }

                    curlyBraceCount++;
                    isEscapingOpenCurlyBrace = false;
                    currentFormatItemBuilder ??= new StringBuilder();
                    continue;
                }

                if (previousChar == '{' && !char.IsDigit(currentChar) && currentFormatItemBuilder != null)
                {
                    return(ValidationFailure.InvalidCharacterAfterOpenCurlyBrace);
                }

                if (currentChar == '}')
                {
                    isEscapingCloseCurlyBrace = previousChar == '}' && !isEscapingCloseCurlyBrace;
                    curlyBraceCount           = isEscapingCloseCurlyBrace
                        ? curlyBraceCount + 1
                        : curlyBraceCount - 1;

                    if (currentFormatItemBuilder != null)
                    {
                        if (TryParseItem(currentFormatItemBuilder.ToString(), out var formatStringItem) is { } failure)
                        {
                            return(failure);
                        }

                        formatStringItems.Add(formatStringItem);
                        currentFormatItemBuilder = null;
                    }
                    continue;
                }

                currentFormatItemBuilder?.Append(currentChar);
            }

            return(curlyBraceCount == 0 ? null : ValidationFailure.UnbalancedCurlyBraceCount);
        }
Esempio n. 56
0
 public static void UpdateLogger(ILambdaLogger logger, StringBuilder sb)
 {
     Logger.WriteLine = s =>
     {
         logger.LogLine(s);
         sb?.Append(s + "\n");
     };
 }
Esempio n. 57
0
        public bool Use(Entity instignator, Entity target, StringBuilder sb)
        {
            var stats = target.GetOne <StatBlock>();

            stats.Heal(Restore, StatID);
            sb?.Append($"{Word.AName(target)} {Word.Verb(target, "heal")} {Restore} HP. "); // TODO: not always HP
            return(true);
        }
Esempio n. 58
0
 /// <summary>
 /// Appends a copy of the specified string to this instance indenting every line by specified value.
 /// </summary>
 /// <param name="builder">The StringBuilder object.</param>
 /// <param name="text">The string to append.</param>
 /// <param name="indentLevel">Indentation level (multiples of 4).</param>
 public static void Append(this StringBuilder builder, string text, int indentLevel)
 {
     foreach (string line in text.GetLines(false))
     {
         builder?.Append(' ', indentLevel * 4);
         builder?.AppendLine(line);
     }
 }
Esempio n. 59
0
        public int Take()
        {
            peekCache = new int?();
            var num = reader.Read();

            sb?.Append((char)num);
            return(num);
        }
Esempio n. 60
0
        /// <summary>
        /// Processes the string strDrain into a calculated Drain dicepool and appropriate display attributes and labels.
        /// </summary>
        /// <param name="strDrain"></param>
        /// <param name="objImprovementManager"></param>
        /// <param name="drain"></param>
        /// <param name="attributeText"></param>
        /// <param name="valueText"></param>
        /// <param name="tooltip"></param>
        public void CalculateTraditionDrain(string strDrain, Improvement.ImprovementType drain, Label attributeText = null, Label valueText = null, ToolTip tooltip = null)
        {
            if (string.IsNullOrWhiteSpace(strDrain) || (attributeText == null && valueText == null && tooltip == null))
            {
                return;
            }
            StringBuilder objDrain        = valueText != null ? new StringBuilder(strDrain) : null;
            StringBuilder objDisplayDrain = attributeText != null ? new StringBuilder(strDrain) : null;
            StringBuilder objTip          = tooltip != null ? new StringBuilder(strDrain) : null;
            int           intDrain        = 0;

            // Update the Fading CharacterAttribute Value.
            foreach (string strAttribute in AttributeSection.AttributeStrings)
            {
                CharacterAttrib objAttrib = _objCharacter.GetAttribute(strAttribute);
                if (strDrain.Contains(objAttrib.Abbrev))
                {
                    string strAttribTotalValue = objAttrib.TotalValue.ToString();
                    objDrain?.Replace(objAttrib.Abbrev, strAttribTotalValue);
                    objDisplayDrain?.Replace(objAttrib.Abbrev, objAttrib.DisplayAbbrev);
                    objTip?.Replace(objAttrib.Abbrev, objAttrib.DisplayAbbrev + " (" + strAttribTotalValue + ")");
                }
            }
            if (objDrain != null)
            {
                try
                {
                    intDrain = Convert.ToInt32(Math.Ceiling((double)CommonFunctions.EvaluateInvariantXPath(objDrain.ToString())));
                }
                catch (XPathException) { }
                catch (OverflowException) { }    // Result is text and not a double
                catch (InvalidCastException) { } // Result is text and not a double
            }

            if (valueText != null || tooltip != null)
            {
                int intBonusDrain = ImprovementManager.ValueOf(_objCharacter, drain);
                if (intBonusDrain != 0)
                {
                    intDrain += intBonusDrain;
                    objTip?.Append(" + " + LanguageManager.GetString("Tip_Modifiers") + " (" + intBonusDrain.ToString() + ")");
                }
            }

            if (attributeText != null)
            {
                attributeText.Text = objDisplayDrain.ToString();
            }
            if (valueText != null)
            {
                valueText.Text = intDrain.ToString();
            }
            if (tooltip != null)
            {
                tooltip.SetToolTip(valueText, objTip.ToString());
            }
        }