C# (CSharp) StringBuilder Code Examples

C# (CSharp) StringBuilder - 30 примеров найдено. Это лучшие примеры C# (CSharp) кода для StringBuilder, полученные из open source проектов. Вы можете ставить оценку каждому примеру, чтобы помочь нам улучшить качество примеров.
Пример #1
1
        public static DataTable GetAllCidades(int estado_id)
        {
            DataTable retorno = new DataTable();
            StringBuilder SQL = new StringBuilder();
            SQL.Append(@"SELECT CidadeId, Nome FROM Cidade WHERE EstadoId = @ESTADO_ID");

            try
            {
                using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Mendes_varejo"].ConnectionString))
                {
                    connection.Open();
                    SqlCommand command = new SqlCommand(SQL.ToString(), connection);
                    command.Parameters.AddWithValue("@ESTADO_ID", estado_id);
                    command.ExecuteNonQuery();
                    SqlDataAdapter adapter = new SqlDataAdapter(command);
                    adapter.Fill(retorno);
                }
            }
            catch (Exception erro)
            {
                throw erro;
            }

            return retorno;
        }
 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();
 }
        /// <summary> Renders the HTML for this element </summary>
        /// <param name="Output"> Textwriter to write the HTML for this element </param>
        /// <param name="Bib"> Object to populate this element from </param>
        /// <param name="Skin_Code"> Code for the current skin </param>
        /// <param name="IsMozilla"> Flag indicates if the current browse is Mozilla Firefox (different css choices for some elements)</param>
        /// <param name="PopupFormBuilder"> Builder for any related popup forms for this element </param>
        /// <param name="Current_User"> Current user, who's rights may impact the way an element is rendered </param>
        /// <param name="CurrentLanguage"> Current user-interface language </param>
        /// <param name="Translator"> Language support object which handles simple translational duties </param>
        /// <param name="Base_URL"> Base URL for the current request </param>
        /// <remarks> This simple element does not append any popup form to the popup_form_builder</remarks>
        public override void Render_Template_HTML(TextWriter Output, SobekCM_Item Bib, string Skin_Code, bool IsMozilla, StringBuilder PopupFormBuilder, User_Object Current_User, Web_Language_Enum CurrentLanguage, Language_Support_Info Translator, string Base_URL)
        {
            // Check that an acronym exists
            if (Acronym.Length == 0)
            {
                Acronym = "Enter the name(s) of the other committee members for this thesis/dissertation";
            }

            // Is there an ETD object?
            Thesis_Dissertation_Info etdInfo = Bib.Get_Metadata_Module(GlobalVar.THESIS_METADATA_MODULE_KEY) as Thesis_Dissertation_Info;
            if ((etdInfo == null) || ( etdInfo.Committee_Members_Count == 0 ))
            {
                render_helper(Output, String.Empty, Skin_Code, Current_User, CurrentLanguage, Translator, Base_URL);
            }
            else
            {
                if (etdInfo.Committee_Members_Count == 1)
                {
                    render_helper(Output, etdInfo.Committee_Members[0], Skin_Code, Current_User, CurrentLanguage, Translator, Base_URL);
                }
                else
                {
                    render_helper(Output, etdInfo.Committee_Members, Skin_Code, Current_User, CurrentLanguage, Translator, Base_URL);
                }
            }
        }
Пример #4
0
 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);
     }
 }
Пример #5
0
        public void TopUsersThatLiked(StringBuilder builder)
        {
            var users = GetUsersThatLiked();
            if (users == null || users.Count == 0)
            {
                return;
            }
            var groupedUsers = users.GroupBy(x => x).Select(x => new { x.Key, Count = x.Count() }).OrderByDescending(x => x.Count).ToList();

            int to = 0;
            if (groupedUsers == null || groupedUsers.Count == 0)
            {
                return;

            }
            else if (groupedUsers.Count > 0 && groupedUsers.Count < 3)
            {
                to = groupedUsers.Count + 1;
            }
            else
            {
                to = 4;
            }

            builder.Append("top users that liked your links: ");
            mHtmlBuilder.For(1, to, i =>
                {
                    builder.Append(i);
                    builder.Append(". <strong>");
                    builder.Append(mQuerier.GetNameByFId(groupedUsers[i-1].Key.ToString()));
                    builder.Append("</strong> - <strong>");
                    builder.Append(groupedUsers[i - 1].Count);
                    builder.Append("</strong> times");
                });
        }
 /// <summary>
 /// ดึงรายชื่อพนักงานตามเงื่อนไขที่กำหนด เพื่อนำไปแสดงบนหน้า ConvertByPayor
 /// </summary>
 /// <param name="doeFrom"></param>
 /// <param name="doeTo"></param>
 /// <param name="payor"></param>
 /// <returns></returns>
 public DataTable getPatient(DateTime doeFrom,DateTime doeTo,string payor,string mobileStatus)
 {
     System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
     #region Variable
     var dt = new DataTable();
     var strSQL = new StringBuilder();
     var clsSQL = new clsSQLNative();
     #endregion
     #region Procedure
     #region SQLQuery
     strSQL.Append("SELECT ");
     strSQL.Append("No,HN,PreName,Name,LastName,DOE,Payor,SyncWhen,'0' IsConvertPreOrder ");
     strSQL.Append("FROM ");
     strSQL.Append("Patient P ");
     strSQL.Append("WHERE ");
     strSQL.Append("(DOE BETWEEN '" + doeFrom.ToString("yyyy-MM-dd HH:mm") + "' AND '" + doeTo.ToString("yyyy-MM-dd HH:mm") + "') ");
     if(payor!="" && payor.ToLower() != "null")
     {
         strSQL.Append("AND Payor='"+payor+"' ");
     }
     if (mobileStatus == "NotRegister")
     {
         strSQL.Append("AND SyncStatus!='1' ");
     }
     else if (mobileStatus == "Register")
     {
         strSQL.Append("AND SyncStatus='1' ");
     }
     strSQL.Append("ORDER BY ");
     strSQL.Append("No;");
     #endregion
     dt = clsSQL.Bind(strSQL.ToString(), clsSQLNative.DBType.SQLServer, "MobieConnect");
     #endregion
     return dt;
 }
Пример #7
0
        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();
        }
Пример #8
0
        public static void Main()
        {
            #if DEBUG
            Console.SetIn(new System.IO.StreamReader(@"../../test.020.in.txt"));
            Debug.Listeners.Add(new ConsoleTraceListener());
            #endif

            Stopwatch sw = new Stopwatch();
            sw.Start();
            StringBuilder sb = new StringBuilder();
            int lines = int.Parse(Console.ReadLine());
            for (int i = 0; i < lines; i++)
            {
                string line = Console.ReadLine();

                bool isValid = Validate(line);
                if (isValid)
                {
                    sb.AppendLine("VALID");
                }
                else
                {
                    sb.AppendLine("INVALID");
                }
            }
            sw.Stop();
            Console.Write(sb.ToString());
            Debug.WriteLine(sw.Elapsed);
            string bla = "asdlj";
        }
Пример #9
0
        static void Main()
        {
            string inputStr = Console.ReadLine();
            string multipleString = "";
            while (inputStr != "END")
            {
                multipleString += inputStr;
                inputStr = Console.ReadLine();
            }
            string pattern = @"(?<=<a).*?\s*href\s*=\s*((""[^""]*""(?=>))|('[^']*'(?=>))|([\w\/\:\.]+\.\w{3})|(\/[^'""]*?(?=>)))";
               //string pattern = @"(?s)(?:<a)(?:[\s\n_0-9a-zA-Z=""()]*?.*?)(?:href([\s\n]*)?=(?:['""\s\n]*)?)([a-zA-Z:#\/._\-0-9!?=^+]*(\([""'a-zA-Z\s.()0-9]*\))?)(?:[\s\na-zA-Z=""()0-9]*.*?)?(?:\>)";
            MatchCollection collection = Regex.Matches(multipleString, pattern);
            List<string> resultStrings = new List<string>();
            foreach (Match match in collection)
            {
                StringBuilder tempStr = new StringBuilder(match.Groups[2].Value);
                if (tempStr[0] == '"' || tempStr[0] == '\'')
                {
                    tempStr.Remove(0,1);
                }
                if (tempStr[tempStr.Length-1] == '"' || tempStr[tempStr.Length-1] == '\'')
                {
                    tempStr.Remove(tempStr.Length-1,1);
                }
                resultStrings.Add(tempStr.ToString());
                Console.WriteLine(tempStr);

            }
            //Console.WriteLine(string.Join("\r\n",resultStrings));
        }
Пример #10
0
        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;
        }
Пример #11
0
		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');
		}
Пример #12
0
        private string SerializeObject(object obj, int depth)
        {
            var type = obj.GetType();
            if (!IsSerializeableType(obj) && !(obj is string))
            {
                return null;
            }
            StringBuilder stringBuilder = new StringBuilder();


            var fieldInfos = type.GetFields();
            stringBuilder.Append("{\n");
            foreach (var fieldInfo in fieldInfos)
            {
                var attributes = fieldInfo.GetCustomAttributes();

                if (attributes.OfType<NonSerializedAttribute>().Any())
                {
                    continue;
                }
                var value = fieldInfo.GetValue(obj);
                stringBuilder.Append(SerializeString(fieldInfo.Name, depth + 1));
                stringBuilder.Append(" : ");
                if (IsSimpleType(value))
                {
                    stringBuilder.Append(SerializeByDepth(value, 0) + "\n");
                    continue;
                }
                stringBuilder.Append(SerializeByDepth(value, depth + 1) + "\n");
            }
            stringBuilder.Append(GetTabs(depth) + "}");
            return stringBuilder.ToString();
        }
Пример #13
0
 protected virtual string FormatMethod(MethodBase method)
 {
     var sb = new StringBuilder();
     if (method.DeclaringType != null)
     {
         sb.Append(method.DeclaringType.FullName);
         sb.Append(".");
     }
     sb.Append(method.Name);
     if (method.IsGenericMethod)
     {
         sb.Append("<");
         sb.Append(string.Join(", ", method.GetGenericArguments().Select(t => t.Name)));
         sb.Append(">");
     }
     sb.Append("(");
     var f = false;
     foreach (var p in method.GetParameters())
     {
         if (f) sb.Append(", ");
         else f = true;
         sb.Append(p.ParameterType.Name);
         sb.Append(' ');
         sb.Append(p.Name);
     }
     sb.Append(")");
     return sb.ToString();
 }
Пример #14
0
	private static void ToCSharpString(Type type, StringBuilder name)
	{
		if (type.IsArray)
		{
			var elementType = type.GetElementType();
			ToCSharpString(elementType, name);
			name.Append(type.Name.Substring(elementType.Name.Length));
			return;
		}
		if (type.IsGenericParameter)
		{
			//NOTE: this has to go before type.IsNested because nested generic type is also a generic parameter and otherwise we'd have stack overflow
			name.AppendFormat("·{0}·", type.Name);
			return;
		}
		if (type.IsNested)
		{
			ToCSharpString(type.DeclaringType, name);
			name.Append(".");
		}
		if (type.IsGenericType == false)
		{
			name.Append(type.Name);
			return;
		}
		name.Append(type.Name.Split('`')[0]);
		AppendGenericParameters(name, type.GetGenericArguments());
	}
Пример #15
0
    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());
    }
Пример #16
0
 public static extern int GetPrivateProfileString(string lpAppName,        // points to section name
     string lpKeyName,        // points to key name
     string lpDefault,        // points to default string
     StringBuilder lpReturnedString,  // points to destination buffer
     int nSize,              // size of destination buffer
     string lpFileName        // points to initialization filename
     );
        /// <summary>
        /// Validates a credit card number using the standard Luhn/mod10 validation algorithm.
        /// </summary>
        /// <param name="cardNumber">Card number, with or without punctuation</param>
        /// <returns>
        /// 	<c>true</c> if card number appears valid; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsCardNumberValid(string cardNumber)
        {
            int i;

            var cleanNumber = new StringBuilder();
            for (i = 0; i < cardNumber.Length; i++)
                if (char.IsDigit(cardNumber, i))
                    cleanNumber.Append(cardNumber[i]);

            if (cleanNumber.Length < 13 || cleanNumber.Length > 16)
                return false;

            for (i = cleanNumber.Length + 1; i <= 16; i++)
                cleanNumber.Insert(0, "0");

            string number = cleanNumber.ToString();
            int total = 0;

            for (i = 1; i <= 16; i++)
            {
                int multiplier = 1 + (i % 2);
                int digit = int.Parse(number.Substring(i - 1, 1));
                int sum = digit * multiplier;
                
                if (sum > 9)
                    sum -= 9;

                total += sum;
            }
            return (total % 10 == 0);
        }
        private string[] SanitizeArgs(string[] args)
        {
            var commands = new List<string>();
            var enumerator = args.GetEnumerator();
            StringBuilder builder = null;
            while (enumerator.MoveNext())
            {
                var arg = enumerator.Current as string;
                if (arg.StartsWith(_token))
                {
                    if (builder != null) commands.Add(builder.ToString());
                    builder = new StringBuilder();
                    builder.Append(arg);
                }
                else
                {
                    builder.Append($" {arg}");
                }
            }


            commands.Add(builder.ToString());

            return commands.ToArray();
        }
Пример #19
0
        public string GetXml(bool validate)
        {
            XNamespace ns = "http://sd.ic.gc.ca/SLDR_Schema_Definition_en";

            var spectrum_licences = getLicences();

            XDocument doc = new XDocument(new XElement("spectrum_licence_data_registry", spectrum_licences));

            foreach (XElement e in doc.Root.DescendantsAndSelf())
            {
                if (e.Name.Namespace == "")
                    e.Name = ns + e.Name.LocalName;
            }

            var errors = new StringBuilder();

            if (validate)
            {
                XmlSchemaSet set = new XmlSchemaSet();
                var schema = getMainSchema();
                set.Add(null, schema);

                doc.Validate(set, (sender, args) => { errors.AppendLine(args.Message); });
            }

            //return errors.Length > 0 ? errors.ToString() : doc.ToString();
            var  result = errors.Length > 0 ? "Validation Errors: " + errors.ToString() : getDocumentAsString(doc);
            return result;
        }
        public IList<IViewAlbumArtistSongTotalVotes> GetMostVotedThisMonth( int page = 0 , int rowCount = 0 )
        {
            DateTime firstDayOfTheMonth;
            DateTime lastDayOfTheMonth;

            DateUtils.GetMonth(DateTime.Now , new CultureInfo("pt-BR") , out firstDayOfTheMonth , out lastDayOfTheMonth);

            StringBuilder builder = new StringBuilder();
            builder.AppendFormat(" (battlDate BETWEEN '{0}' AND '{1} 23:59:59')",firstDayOfTheMonth.ToString("yyyy-MM-dd"), lastDayOfTheMonth.ToString("yyyy-MM-dd"));

            IDataQuery query = new DataQuery();
            query.From = "ViewTopSongs";
            query.Where = builder.ToString();
            if( !String.IsNullOrEmpty(_orderBy) )
            {
                query.OrderBy = _orderBy;
            }

            query.Page = page;
            query.RowCount = rowCount;

            IList<IViewAlbumArtistSongTotalVotes> result = _repository.Find(query);

            query.From = "ViewTopSongs";
            this.Total = _repository.Count(query);

            _collection = result;

            return result;
        }
Пример #21
0
    /// <summary>
    /// Reads from the stream.
    /// </summary>
    /// <param name="timeout">The timeout.</param>
    /// <returns>Any text read from the stream.</returns>
    public string Read(TimeSpan timeout)
#endif
    {
      if (!this.byteStream.Connected || this.internalCancellation.Token.IsCancellationRequested)
      {
        return string.Empty;
      }

      StringBuilder sb = new StringBuilder();
      this.byteStream.ReceiveTimeout = (int)timeout.TotalMilliseconds;
      DateTime endInitialTimeout = DateTime.Now.Add(timeout);
      DateTime rollingTimeout = ExtendRollingTimeout(timeout);
      do
      {
        if (this.ParseResponse(sb))
        {
          rollingTimeout = ExtendRollingTimeout(timeout);
        }
      }
      while (!this.internalCancellation.Token.IsCancellationRequested && (this.IsResponsePending || IsWaitForInitialResponse(endInitialTimeout, sb) ||
#if ASYNC
                                                                                              await
#endif
                                                                                                    IsWaitForIncrementalResponse(rollingTimeout)));
      if (DateTime.Now >= rollingTimeout)
      {
        System.Diagnostics.Debug.Print("RollingTimeout exceeded {0}", DateTime.Now.ToString("ss:fff"));
      }

      return sb.ToString();
    }
        public static void Check_Instruction_20_CCF()
        {
            StringBuilder testProgram = new StringBuilder();
            // TStatesByMachineCycle = "1 (4)"
            testProgram.AppendLine("CCF");
            // TStatesByMachineCycle = "7 (4,3)"
            testProgram.AppendLine("LD A,0");
            // TStatesByMachineCycle = "1 (4)"
            testProgram.AppendLine("CCF");
            // TStatesByMachineCycle = "1 (4)"
            testProgram.AppendLine("CCF");

            TestSystem testSystem = new TestSystem();
            testSystem.LoadProgramInMemory(testProgram.ToString());

            CPUStateLogger logger = new CPUStateLogger(testSystem.CPU);
            logger.StartLogging(
                CPUStateLogger.CPUStateElements.InternalState | CPUStateLogger.CPUStateElements.Registers,
                new Z80CPU.LifecycleEventType[] { Z80CPU.LifecycleEventType.MachineCycleEnd });
            testSystem.ExecuteInstructionCount(4);
            logger.StopLogging();

            if (!logger.CompareWithSavedLog("ALU/ArithmeticGeneralPurpose/Logs/Check_Instruction_20_CCF"))
            {
                throw new Exception("Log compare failed");
            }
        }
Пример #23
0
        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;
        }
Пример #24
0
 public ChunkStream(WebHeaderCollection headers)
 {
     _headers = headers;
       _chunkSize = -1;
       _chunks = new List<Chunk> ();
       _saved = new StringBuilder ();
 }
Пример #25
0
 public override string ToXML()
 {
     StringBuilder sb = new StringBuilder();
     sb.Append(base.ToXML());
     sb.AppendLine("<tilt>" + tilt + "</tilt>");
     return sb.ToString();
 }
 protected void Page_Load(object sender, EventArgs e)
 {
     IUnityContainer container = new UnityContainer();
     UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
     section.Configure(container);
     if (Request["installation"] != null)
     {
         int installationid = Int32.Parse(Request["installation"]);
         userid = Int32.Parse(Request["userid"]);
         user = Request["user"];
         sservice = container.Resolve<IStatisticService>();
         IInstallationBL iinstall = container.Resolve<IInstallationBL>();
         imodel = iinstall.getInstallation(installationid);
         Dictionary<InstallationModel, List<InstallationState>> statelist = sservice.getInstallationState(imodel.customerid);
         StringBuilder str = new StringBuilder();
         str.Append("<table border = '1'><tr><th>Description</th><th>Messwert</th><th>Einheit</th></tr>");
         foreach (var values in statelist)
         {
             if(values.Key.installationid.Equals(installationid))
             {
                 foreach (var item in values.Value)
                 {
                      str.Append("<tr><td>" + item.description + "</td><td>" + item.lastValue + "</td><td>" + item.unit + "</td></tr>");
                 }
                 break;
             }
         }
         str.Append("</table>");
         anlagenzustand.InnerHtml = str.ToString();
     }
 }
Пример #27
0
 /// <summary>
 /// Read Data Value From the Ini File
 /// </summary>
 /// <PARAM name="Section"></PARAM>
 /// <PARAM name="Key"></PARAM>
 /// <PARAM name="Path"></PARAM>
 /// <returns></returns>
 public string IniReadValue(string Section,string Key)
 {
     StringBuilder temp = new StringBuilder(255);
     int i = GetPrivateProfileString(Section,Key,"",temp,
                                     255, this.path);
     return temp.ToString();
 }
Пример #28
0
        public static string Encode(string str, string key)
        {
            DESCryptoServiceProvider provider = new DESCryptoServiceProvider();

            provider.Key = Encoding.ASCII.GetBytes(key.Substring(0, 8));

            provider.IV = Encoding.ASCII.GetBytes(key.Substring(0, 8));

            byte[] bytes = Encoding.UTF8.GetBytes(str);

            MemoryStream stream = new MemoryStream();

            CryptoStream stream2 = new CryptoStream(stream, provider.CreateEncryptor(), CryptoStreamMode.Write);

            stream2.Write(bytes, 0, bytes.Length);

            stream2.FlushFinalBlock();

            StringBuilder builder = new StringBuilder();

            foreach (byte num in stream.ToArray())
            {

                builder.AppendFormat("{0:X2}", num);

            }

            stream.Close();

            return builder.ToString();
        }
        private void copyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DataGridView dataGrid = (DataGridView)this.SourceControl;

            StringBuilder sb = new StringBuilder();

            int firstRowIndex = dataGrid.RowCount;
            int lastRowIndex = 0;
            int firstColIndex = dataGrid.ColumnCount;
            int lastColIndex = 0;
            for (int i = 0; i < dataGrid.SelectedCells.Count; i++)
            {
                if (dataGrid.SelectedCells[i].RowIndex < firstRowIndex) firstRowIndex = dataGrid.SelectedCells[i].RowIndex;
                if (dataGrid.SelectedCells[i].RowIndex > lastRowIndex) lastRowIndex = dataGrid.SelectedCells[i].RowIndex;

                if (dataGrid.SelectedCells[i].ColumnIndex < firstColIndex) firstColIndex = dataGrid.SelectedCells[i].ColumnIndex;
                if (dataGrid.SelectedCells[i].ColumnIndex > lastColIndex) lastColIndex = dataGrid.SelectedCells[i].ColumnIndex;
            }

            for (int i = firstRowIndex; i <= lastRowIndex; i++)
            {
                for (int j = firstColIndex; j <= lastColIndex; j++)
                {
                    if (dataGrid[j, i].Selected)
                    {
                        try { sb.Append(dataGrid[j, i].Value.ToString()); }
                        catch (NullReferenceException) { }
                        if (j != lastColIndex) sb.Append("\t");
                    }
                }
                if (i != lastRowIndex) sb.Append("\r\n");
            }

            Clipboard.SetDataObject(sb.ToString(), true);
        }
Пример #30
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();
        }