AppendFormat() public method

public AppendFormat ( IFormatProvider provider, string format ) : StringBuilder
provider IFormatProvider
format string
return StringBuilder
Esempio n. 1
1
        /// <exception cref="MyException"></exception>
        public void Inserir(ICliente cliente, ILog log)
        {
            var sql = new StringBuilder();
            var tblLog = new TblClientesLog();

            sql.AppendFormat(" INSERT INTO {0} ({1},{2},{3}", tblLog.NomeTabela, tblLog.Clientes_Id, tblLog.Clientes_Nome, tblLog.Clientes_Status_Id);
            sql.AppendFormat(",{0},{1},{2})", tblLog.Usuarios_Id, tblLog.Operacao_Id, tblLog.DataHora);
            sql.Append(" VALUES (@id,@nome,@status_id");
            sql.Append(",@usuarios_id,@operacao_id,@datahora);");

            using (var dal = new DalHelperSqlServer())
            {
                try
                {
                    dal.CriarParametroDeEntrada("id", SqlDbType.Int, cliente.Id);
                    dal.CriarParametroDeEntrada("nome", SqlDbType.Char, cliente.Nome);
                    dal.CriarParametroDeEntrada("status_id", SqlDbType.SmallInt, cliente.Status.GetHashCode());
                    dal.CriarParametroDeEntrada("usuarios_id", SqlDbType.Int, log.Usuario.Id);
                    dal.CriarParametroDeEntrada("operacao_id", SqlDbType.SmallInt, log.Operacao.GetHashCode());
                    dal.CriarParametroDeEntrada("datahora", SqlDbType.DateTime, log.DataHora);

                    dal.ExecuteNonQuery(sql.ToString());
                }
                catch (SqlException) { throw new MyException("Operação não realizada, por favor, tente novamente!"); }
            }
        }
Esempio n. 2
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. 3
0
        private void DoSearch()
        {
            // 既存データクリア
            listDataGridView.Rows.Clear();

            DataTable table = GetData();

            StringBuilder cond = new StringBuilder();
            if (!string.IsNullOrEmpty(nendoTextBox.Text))
            {
                if (cond.Length > 0) { cond.Append(" AND "); }
                cond.AppendFormat("IraiNendo = '{0}'", nendoTextBox.Text);
            }
            if (!string.IsNullOrEmpty(noFromTextBox.Text))
            {
                if (cond.Length > 0) { cond.Append(" AND "); }
                cond.AppendFormat("IraiRenban >= '{0}'", noFromTextBox.Text);
            }
            if (!string.IsNullOrEmpty(noToTextBox.Text))
            {
                if (cond.Length > 0) { cond.Append(" AND "); }
                cond.AppendFormat("IraiRenban <= '{0}'", noToTextBox.Text);
            }

            // TODO 製品版では、クエリ内でフィルタを行う
            foreach (DataRow row in table.Select(cond.ToString()))
            {
                SetData(row);
            }
        }
Esempio n. 4
0
        public static string FormatTagsTable(Hashtable tags)
        {
            if (tags == null || tags.Count == 0)
            {
                return null;
            }

            StringBuilder resourcesTable = new StringBuilder();

            var tagsDictionary = TagsConversionHelper.CreateTagDictionary(tags, false);

            int maxNameLength = Math.Max("Name".Length, tagsDictionary.Max(tag => tag.Key.Length));
            int maxValueLength = Math.Max("Value".Length, tagsDictionary.Max(tag => tag.Value.Length));

            string rowFormat = "{0, -" + maxNameLength + "}  {1, -" + maxValueLength + "}\r\n";
            resourcesTable.AppendLine();
            resourcesTable.AppendFormat(rowFormat, "Name", "Value");
            resourcesTable.AppendFormat(rowFormat,
                GeneralUtilities.GenerateSeparator(maxNameLength, "="),
                GeneralUtilities.GenerateSeparator(maxValueLength, "="));

            foreach (var tag in tagsDictionary)
            {
                if (tag.Key.StartsWith(ExcludedTagPrefix))
                {
                    continue;
                }

                resourcesTable.AppendFormat(rowFormat, tag.Key, tag.Value);
            }

            return resourcesTable.ToString();
        }
Esempio n. 5
0
        /// <summary>
        /// 无参数动作执行时间 返回详细信息
        /// </summary>
        /// <example>
        /// <code>
        /// Msg.WriteEnd(ActionExtensions.Time(() => { Msg.Write(1); }, "测试", 1000));
        /// </code>
        /// </example>
        /// <param name="action">动作</param>
        /// <param name="name">测试名称</param>
        /// <param name="iteration">执行次数</param>
        /// <returns>返回执行时间毫秒(ms)</returns>
        public static string Time(this Action action, string name = "", int iteration = 1) {
            if (name.IsNullEmpty()) {
                var watch = Stopwatch.StartNew();
                long cycleCount = WinApi.GetCycleCount();
                for (int i = 0; i < iteration; i++) action();
                long cpuCycles = WinApi.GetCycleCount() - cycleCount;
                watch.Stop();
                return watch.Elapsed.ToString();
            } else {
                StringBuilder sb = new StringBuilder();

                GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
                int[] gcCounts = new int[GC.MaxGeneration + 1];
                for (int i = 0; i <= GC.MaxGeneration; i++) gcCounts[i] = GC.CollectionCount(i);

                var watch = Stopwatch.StartNew();
                long cycleCount = WinApi.GetCycleCount();
                for (int i = 0; i < iteration; i++) action();
                long cpuCycles = WinApi.GetCycleCount() - cycleCount;
                watch.Stop();

                sb.AppendFormat("{0} 循环{1}次测试结果:<br />", name, iteration);
                sb.AppendFormat("使用时间:{0}<br />", watch.Elapsed.ToString());
                sb.AppendFormat("CPU周期:{0}<br />", cpuCycles.ToString("N0"));

                for (int i = 0; i <= GC.MaxGeneration; i++) sb.AppendFormat("Gen  {0}:{1}<br />", i, GC.CollectionCount(i) - gcCounts[i]);
                sb.Append("<br />");
                return sb.ToString();
            }
        }
 public override void Compute()
 {
     TLKeyValuePairsList precision = (TLKeyValuePairsList)Workspace.Load("PrecisionData");
     TLKeyValuePairsList recall = (TLKeyValuePairsList)Workspace.Load("RecallData");
     TLKeyValuePairsList avgprecision = (TLKeyValuePairsList)Workspace.Load("AvgPrecisionData");
     StringBuilder sb = new StringBuilder();
     sb.AppendFormat("{0}\n", _config.Title);
     sb.AppendLine("--------------------------------------------------");
     sb.AppendFormat("Precision Data:\nMin:\t{0}\nMax:\t{1}\nAvg:\t{2}\n",
         GetMin(precision),
         GetMax(precision),
         GetAvg(precision)
     );
     sb.AppendLine("--------------------------------------------------");
     sb.AppendFormat("Recall Data:\nMin:\t{0}\nMax:\t{1}\nAvg:\t{2}\n",
         GetMin(recall),
         GetMax(recall),
         GetAvg(recall)
     );
     sb.AppendLine("--------------------------------------------------");
     sb.AppendFormat("Avg Precision Data:\nMin:\t{0}\nMax:\t{1}\nAvg:\t{2}\n",
         GetMin(avgprecision),
         GetMax(avgprecision),
         GetAvg(avgprecision)
     );
     sb.AppendLine("--------------------------------------------------");
     /*
     SimpleResultsWindow window = new SimpleResultsWindow();
     window.PrintToScreen(sb.ToString());
     window.ShowDialog();
     */
     Logger.Info(sb.ToString());
 }
        /// <summary>
        /// Generates an URI-friendly ID for the <see cref="ApiDescription"/>. E.g. "Get-Values-id_name" instead of "GetValues/{id}?name={name}"
        /// </summary>
        /// <param name="description">The <see cref="ApiDescription"/>.</param>
        /// <returns>The ID as a string.</returns>
        public static string GetFriendlyId(this ApiDescription description)
        {
            string path = description.RelativePath;
            string[] urlParts = path.Split('?');
            string localPath = urlParts[0];
            string queryKeyString = null;
            if (urlParts.Length > 1)
            {
                string query = urlParts[1];
                string[] queryKeys = HttpUtility.ParseQueryString(query).AllKeys;
                queryKeyString = string.Join("_", queryKeys);
            }

            var friendlyPath = new StringBuilder();
            friendlyPath.AppendFormat(
                "{0}-{1}",
                description.HttpMethod.Method,
                localPath.Replace("/", "-").Replace("{", string.Empty).Replace("}", string.Empty));
            if (queryKeyString != null)
            {
                friendlyPath.AppendFormat("_{0}", queryKeyString.Replace('.', '-'));
            }

            return friendlyPath.ToString();
        }
Esempio n. 8
0
        /// <summary>
        /// When overridden in a derived class, executes the task.
        /// </summary>
        /// <returns>
        /// true if the task successfully executed; otherwise, false.
        /// </returns>
        public override bool Execute()
        {
            decimal[] numbers = StringArrayToDecimalArray(this.Numbers);
            decimal? total = null;

            StringBuilder logger = new StringBuilder();
            logger.Append("Subtract numbers: ");

            foreach (decimal number in numbers)
            {
                if (total.HasValue)
                {
                    logger.AppendFormat(" - {0}", number);
                    total -= number;
                }
                else
                {
                    logger.Append(number);
                    total = number;
                }
            }

            decimal  actualTotal = total ?? 0;

            logger.AppendFormat(" = {0}", actualTotal);
            base.Log.LogMessage(logger.ToString());

            this.Result = actualTotal.ToString(this.NumericFormat ?? string.Empty);
            return true;
        }
		private string makeWhere(Uri url)
		{
			Stack<string> hostStack = new Stack<string>(url.Host.Split('.'));
			StringBuilder hostBuilder = new StringBuilder('.' + hostStack.Pop());
			string[] pathes = url.Segments;

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

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

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

				needOr = true;
			}

			sb.Append(')');
			return sb.ToString();
		}
Esempio n. 10
0
        public string GetFilterText()
        {
            StringBuilder sb = new StringBuilder("<filter>");

            if (Tests.Count > 0)
            {
                sb.Append("<tests>");
                foreach (string test in Tests)
                    sb.AppendFormat("<test>{0}</test>", test);
                sb.Append("</tests>");
            }

            if (Include.Count > 0)
            {
                sb.Append("<include>");
                foreach (string category in Include)
                    sb.AppendFormat("<category>{0}</category>", category);
                sb.Append("</include>");
            }

            if (Exclude.Count > 0)
            {
                sb.Append("<exclude>");
                foreach (string category in Exclude)
                    sb.AppendFormat("<category>{0}</category>", category);
                sb.Append("</exclude>");
            }

            sb.Append("</filter>");

            return sb.ToString();
        }
        public override string ToString()
        {
            StringBuilder builder = new StringBuilder();

            builder.AppendFormat("State {0}", num);
            builder.AppendLine();
            builder.AppendLine();

            foreach (ProductionItem item in kernelItems)
            {
                builder.AppendFormat("    {0}", item);
                builder.AppendLine();
            }

            builder.AppendLine();

            foreach (KeyValuePair<Terminal, ParserAction> a in parseTable)
            {
                builder.AppendFormat("    {0,-14} {1}", a.Key, a.Value);
                builder.AppendLine();
            }

            builder.AppendLine();

            foreach (KeyValuePair<NonTerminal, Transition> n in nonTerminalTransitions)
            {
                builder.AppendFormat("    {0,-14} go to state {1}", n.Key, Goto[n.Key].num);
                builder.AppendLine();
            }

            builder.AppendLine();

            return builder.ToString();
        }
        // 生成界面左边菜单
        public static MvcHtmlString MenuLinks(this HtmlHelper html,
          List<IMS_UP_MK> menuList)
        {
            if (menuList == null)
                return new MvcHtmlString("");

            long? lastIdx = -1;
            StringBuilder result = new StringBuilder();
            foreach (var menu in menuList)
            {
                if (menu.FMKID  == -1)
                {
                    if (lastIdx != -1 && lastIdx != menu.ID)
                    {
                        result.Append("</ul></div>");
                    }
                    lastIdx = menu.ID;
                    result.AppendFormat("<div title='{0}'>", menu.MKMC);
                    result.Append("<ul class='content' >");
                }
                else
                {
                    result.Append("<li>");
                    //result.AppendFormat("<a href='{0}' target='ibody'>{1}</a>", menu.URL, menu.ModuleName);
                    result.AppendFormat(@"<a href='###' onclick=""mainPage.onMenuClick('{0}','{1}','{2}');"">{1}</a>", menu.ID, menu.MKMC,   menu.URL);
                    result.Append("</li>");


                }
            }
            result.Append("</ul></div>");
            return MvcHtmlString.Create(result.ToString());
        }
Esempio n. 13
0
 private static void DescribeChunk(RiffChunk chunk, StringBuilder stringBuilder, byte[] data)
 {
     switch(chunk.IdentifierAsString)
     {
         case "strc":
             DescribeStrc(stringBuilder, data);
             break;
         case "bext":
             DescribeBext(stringBuilder, data);
             break;
         case "iXML":
             stringBuilder.Append(UTF8Encoding.UTF8.GetString(data));
             break;
         default:
             {
                 if (ByteArrayExtensions.IsEntirelyNull(data))
                 {
                     stringBuilder.AppendFormat("{0} null bytes\r\n", data.Length);
                 }
                 else
                 {
                     stringBuilder.AppendFormat("{0}\r\n", ByteArrayExtensions.DescribeAsHex(data," ",32));
                 }
             }
             break;
     }
 }
Esempio n. 14
0
        internal string GetUrl()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("http://exhentai.org/torrents.php");

            if (String.IsNullOrEmpty(this.Keyword))
                sb.AppendFormat("?search={0}&", Uri.EscapeUriString(this.Keyword));

            if (this.Page.HasValue && this.Page.Value > 1)
                sb.AppendFormat("?page={0}", (this.Page - 1));

            if (this.OrderType != null)
            {
                sb.Append("?o=");

                switch (this.OrderType.Value)
                {
                    case OrderTypes.Added:		sb.Append("a");	break;
                    case OrderTypes.Size:		sb.Append("z"); break;
                    case OrderTypes.Seeds:		sb.Append("s"); break;
                    case OrderTypes.Peers:		sb.Append("d");	break;
                    case OrderTypes.Downloads:	sb.Append("c");	break;
                }

                sb.Append(this.Ascending ? 'a' : 'd');
            }

            if (sb[sb.Length - 1] == '&')
                sb = sb.Remove(sb.Length - 1, 1);

            sb = sb.Replace("&?", "&");

            return sb.ToString();
        }
		protected override StringBuilder GetCommandText(string[] restrictions)
		{
			StringBuilder sql = new StringBuilder();
			StringBuilder where = new StringBuilder();

			sql.Append(
				@"SELECT
					null AS PROCEDURE_CATALOG,
					null AS PROCEDURE_SCHEMA,
					rdb$relation_name AS PROCEDURE_NAME,
					rdb$user AS GRANTEE,
					rdb$grantor AS GRANTOR,
					rdb$privilege AS PRIVILEGE,
					rdb$grant_option AS WITH_GRANT
				FROM rdb$user_privileges");

			where.Append("rdb$object_type = 5");

			if (restrictions != null)
			{
				int index = 0;

				/* PROCEDURE_CATALOG */
				if (restrictions.Length >= 1 && restrictions[0] != null)
				{
				}

				/* PROCEDURE_SCHEMA */
				if (restrictions.Length >= 2 && restrictions[1] != null)
				{
				}

				/* PROCEDURE_NAME */
				if (restrictions.Length >= 3 && restrictions[2] != null)
				{
					where.AppendFormat(CultureInfo.CurrentUICulture, " AND rdb$relation_name = @p{0}", index++);
				}

				/* GRANTOR */
				if (restrictions.Length >= 5 && restrictions[4] != null)
				{
					where.AppendFormat(CultureInfo.CurrentUICulture, " AND rdb$grantor = @p{0}", index++);
				}

				/* GRANTEE */
				if (restrictions.Length >= 4 && restrictions[3] != null)
				{
					where.AppendFormat(CultureInfo.CurrentUICulture, " AND rdb$user = @p{0}", index++);
				}
			}

			if (where.Length > 0)
			{
				sql.AppendFormat(CultureInfo.CurrentUICulture, " WHERE {0} ", where.ToString());
			}

			sql.Append(" ORDER BY rdb$relation_name");

			return sql;
		}
        private static IPublishedContent FindContentByAlias(ContextualPublishedContentCache cache, int rootNodeId, string alias)
        {
            if (alias == null) throw new ArgumentNullException("alias");

            // the alias may be "foo/bar" or "/foo/bar"
            // there may be spaces as in "/foo/bar,  /foo/nil"
            // these should probably be taken care of earlier on

            alias = alias.TrimStart('/');
            var xpathBuilder = new StringBuilder();
            xpathBuilder.Append(XPathStringsDefinition.Root);

            if (rootNodeId > 0)
                xpathBuilder.AppendFormat(XPathStrings.DescendantDocumentById, rootNodeId);

            XPathVariable var = null;
            if (alias.Contains('\'') || alias.Contains('"'))
            {
                // use a var, as escaping gets ugly pretty quickly
                var = new XPathVariable("alias", alias);
                alias = "$alias";
            }
            xpathBuilder.AppendFormat(XPathStrings.DescendantDocumentByAlias, alias);

            var xpath = xpathBuilder.ToString();

            // note: it's OK if var is null, will be ignored
            return cache.GetSingleByXPath(xpath, var);
        }
Esempio n. 17
0
        public CentroMedicoDataSet.UsuariosDataTable getUsersByCrit(String criterio)
        {

            criterio.Trim();
            SqlConnection conexion = new SqlConnection(strConexion);
            conexion.Open();
            StringBuilder query = new StringBuilder();

            if (criterio.Equals(""))
            {
                query.AppendFormat("select * from usuarios");
            }
            else
            {
                query.AppendFormat("select * from usuarios where NssUsuario like '%{0}%' or nombre like '%{0}%' or apellidos like '%{0}%' or direccion like '%{0}%' or localidad like '%{0}%' or telefono like '%{0}%' or dni like '%{0}%' or email like '%{0}%'", criterio);
            }
            SqlDataAdapter adapter = new SqlDataAdapter(query.ToString(), conexion);
            CentroMedicoDataSet.UsuariosDataTable tabla = new CentroMedicoDataSet.UsuariosDataTable();

            adapter.Fill(tabla);

            conexion.Close();

            return tabla;
        }
Esempio n. 18
0
        private string HierarchicalCatalogView(CrcReportFolder rootFolder, int level, string showFolder)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<div class=\"folderBox\">");
            string scrollTo = "";
            if (PathMatch(showFolder, rootFolder.Path))
                scrollTo = " scrollToFolder";
            sb.AppendFormat("<div class=\"folderName{1}\">{0}</div>", rootFolder.FolderName, scrollTo);
            string show = "none";
            if (level == 0 || PathContains(showFolder, rootFolder.Path))
                show = "block";

            sb.AppendFormat("<div class=\"folderChildren\" style=\"display:{0}\">", show);

            foreach (CrcReportFolder subFolderLoop in rootFolder.SubFolders)
                sb.Append(HierarchicalCatalogView(subFolderLoop, level + 1, showFolder));

            foreach (CrcReportItem itemLoop in rootFolder.Reports)
            {

                sb.Append("<div class=\"reportRow\">");
                sb.AppendFormat("<a class=\"reportLink vanillaHover\" href=\"Report.aspx?path={0}\" >{1}</a>",
                    Server.UrlEncode(itemLoop.ReportPath), itemLoop.DisplayName);
                if (!string.IsNullOrEmpty(itemLoop.ShortDescription))
                    sb.AppendFormat("<div class=\"reportInfo\">{0}</div>", itemLoop.ShortDescription);
                sb.Append("<div class=\"clear\"></div></div>");

            }

            sb.Append("</div></div>");
            return sb.ToString();
        }
Esempio n. 19
0
        /// <summary>
        /// 分页
        /// </summary>
        public static string Page(string table, int pagesize, int pagecurrent, string fields, string where, string order)
        {
            StringBuilder sql = new StringBuilder();
            if (pagecurrent == 1)
            {
                sql.Append(Select(table, pagesize, String.Empty, where, order));
            }
            else
            {
                sql.AppendFormat("select top {0} * from {1} ", pagesize, table);
                sql.AppendFormat(" where {0} not in(select top {1} {0} from {2} ", fields, pagesize * (pagecurrent - 1), table);
                if (where != "")
                {
                    sql.AppendFormat(" where {0} ", where);
                }
                if (order != "")
                {
                    sql.AppendFormat(" order by {0} ", order);
                }
                sql.AppendFormat(")");
                if (where != "")
                {
                    sql.AppendFormat(" and {0} ", where);
                }
                if (order != "")
                {
                    sql.AppendFormat(" order by {0} ", order);
                }
            }

            return sql.ToString();
        }
        public string GetImageTag(int? imageId, int? maxWidth = null, int? maxHeight = null )
        {
            var photoUrl = new StringBuilder();

            photoUrl.Append( System.Web.VirtualPathUtility.ToAbsolute( "~/" ) );

            string styleString = string.Empty;

            if ( imageId.HasValue )
            {
                photoUrl.AppendFormat( "GetImage.ashx?id={0}", imageId );

                if ( maxWidth.HasValue )
                {
                    photoUrl.AppendFormat( "&maxwidth={0}", maxWidth.Value );
                }
                if ( maxHeight.HasValue )
                {
                    photoUrl.AppendFormat( "&maxheight={0}", maxHeight.Value );
                }
            }
            else
            {
                photoUrl.Append( "Assets/Images/no-picture.svg?" );

                if ( maxWidth.HasValue || maxHeight.HasValue )
                {
                    styleString = string.Format( " style='{0}{1}'",
                        maxWidth.HasValue ? "max-width:" + maxWidth.Value.ToString() + "px; " : "",
                        maxHeight.HasValue ? "max-height:" + maxHeight.Value.ToString() + "px;" : "" );
                }
            }

            return string.Format( "<img src='{0}'{1}/>", photoUrl.ToString(), styleString );
        }
 public virtual void UrlEncode(StringBuilder sb)
 {
     sb.AppendFormat ("customer={0}&amount={1}&currency={2}&",
         HttpUtility.UrlEncode (CustomerID), Amount, HttpUtility.UrlEncode (Currency ?? "usd"));
     if (!string.IsNullOrEmpty (Description))
         sb.AppendFormat ("description={0}&", HttpUtility.UrlEncode (Description));
 }
        public string FormatHtml(object data)
        {
            const string keywordFormat = "<span style=\"color: #0000FF\">{0}</span>";
            const string typeFormat = "<span style=\"color: #2B91AF\">{0}</span>";

            var methodInfo = (MethodInfo)data;
            var sb = new StringBuilder();
            var declaringType = methodInfo.DeclaringType;
            sb.AppendFormat("{0} {1}.{2} {{ ",
                string.Format(keywordFormat, "class"),
                declaringType.Namespace,
                string.Format(typeFormat, declaringType.Name));

            AppendAccess(methodInfo, sb, keywordFormat);

            if (methodInfo.IsVirtual)
            {
                sb.AppendFormat(keywordFormat, "virtual");
                sb.Append(" ");
            }

            AppendMethodName(methodInfo, sb);
            sb.Append(" (...)");
            sb.Append("}}");

            return sb.ToString();
        }
        public static void Format(FtpCommandContext context, FileSystemInfo fileInfo, StringBuilder output)
        {
            var isFile = fileInfo is FileInfo;

            //Size
            output.AppendFormat("size={0};", isFile ? ((FileInfo)fileInfo).Length : 0);

            //Permission
            output.AppendFormat("perm={0}{1};",
                                /* Can read */ isFile ? "r" : "el",
                                /* Can write */ isFile ? "adfw" : "fpcm");
            
            //Type
            output.AppendFormat("type={0};", isFile ? "file" : "dir");

            //Create
            output.AppendFormat("create={0};", FtpDateUtils.FormatFtpDate(fileInfo.CreationTimeUtc));

            //Modify
            output.AppendFormat("modify={0};", FtpDateUtils.FormatFtpDate(fileInfo.LastWriteTimeUtc));

            //File name
            output.Append(DELIM);
            output.Append(fileInfo.Name);

            output.Append(NEWLINE);
        }
Esempio n. 24
0
        public void AttachmentInfo(ConsoleWriteLine WriteLine)
        {
            Client.Self.GetAttachmentResources((bool success, AttachmentResourcesMessage info) =>
            {
                if (!success || info == null)
                {
                    WriteLine("Failed to get the script info.");
                    return;
                }
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("Summary:");
                sb.AppendFormat("Memory used {0} KB out of {1} KB available.", info.SummaryUsed["memory"] / 1024, info.SummaryAvailable["memory"] / 1024);
                sb.AppendLine();
                sb.AppendFormat("URLs used {0} out of {1} available.", info.SummaryUsed["urls"], info.SummaryAvailable["urls"]);
                sb.AppendLine();
                sb.AppendLine();
                sb.AppendLine("Details:");

                foreach (KeyValuePair<AttachmentPoint, ObjectResourcesDetail[]> kvp in info.Attachments)
                {
                    sb.AppendLine();
                    sb.AppendLine(string.Format("Attached to {0} ", Utils.EnumToText(kvp.Key)) + ":");
                    for (int i = 0; i < kvp.Value.Length; i++)
                    {
                        ObjectResourcesDetail obj = kvp.Value[i];
                        sb.AppendLine(obj.Name + " using " + obj.Resources["memory"] / 1024 + " KB");
                    }
                }

                WriteLine(sb.ToString());
            }
            );
        }
Esempio n. 25
0
        /// <summary>
        /// Report a post
        /// </summary>
        /// <param name="report"></param>
        public void PostReport(Report report)
        {
            var sb = new StringBuilder();
            var email = new Email();

            sb.AppendFormat("<p>{2}: <a href=\"{0}\">{1}</a></p>", string.Concat(_settingsService.GetSettings().ForumUrl, report.Reporter.NiceUrl), 
                report.Reporter.UserName,
                _localizationService.GetResourceString("Report.Reporter"));

            sb.AppendFormat("<p>{2}: <a href=\"{0}\">{1}</a></p>", string.Concat(_settingsService.GetSettings().ForumUrl, 
                report.ReportedPost.Topic.NiceUrl), report.ReportedPost.Topic.Name,
                _localizationService.GetResourceString("Report.PostReported"));

            sb.AppendFormat("<p>{0}:</p>", _localizationService.GetResourceString("Report.Reason"));
            sb.AppendFormat("<p>{0}</p>", report.Reason);

            email.EmailFrom = _settingsService.GetSettings().NotificationReplyEmail;
            email.EmailTo = _settingsService.GetSettings().AdminEmailAddress;
            email.Subject = _localizationService.GetResourceString("Report.PostReport");
            email.NameTo = _localizationService.GetResourceString("Report.Admin");

            email.Body = _emailService.EmailTemplate(email.NameTo, sb.ToString());

            _emailService.SendMail(email);
        }
        public override string ToString()
        {
            StringBuilder output = new StringBuilder();
            output.AppendFormat("[First name: {0}; ", this.FirstName);

            if (this.MiddleName != null)
            {
                output.AppendFormat("Middle name: {0}; ", this.MiddleName);
            }

            if (this.LastName != null)
            {
                output.AppendFormat("Last name: {0}; ", this.LastName);
            }

            if (this.Nickname != null)
            {
                output.AppendFormat("Nickname: {0}; ", this.Nickname);
            }

            output.AppendFormat("Town: {0}; ", this.Town);

            output.AppendFormat("Phone number: {0}]", this.PhoneNumber);

            return output.ToString();
        }
Esempio n. 27
0
      public DataTable GetModel(string DBConnection,  IList<String> PdLine,  DateTime From, DateTime To)
     {
         DataTable Result = null;
         string selectSQL = "";
         string groupbySQL = "";

         groupbySQL += "GROUP by  b.Descr";

         string orderbySQL = "ORDER BY  b.Descr";
         StringBuilder sb = new StringBuilder();
         //sb.AppendLine("WITH [TEMP] AS (");
         sb.AppendLine(" select distinct b.Descr as Family from PCBLog a  inner join  Part b on a.PCBModel=b.PartNo ");


         //sb.AppendLine("INNER JOIN PCB b ON a.PCBNo = b.PCBNo AND e.PartNo = b.PCBModelID ");
         sb.AppendLine("WHERE a.Cdt Between @StartTime AND @EndTime and  b.BomNodeType='MB'   ");
         if (PdLine.Count > 0)
         {
             sb.AppendFormat("AND a.Line in ('{0}') ", string.Join("','", PdLine.ToArray()));
         }


         sb.AppendFormat("{0}  ", groupbySQL);
         sb.AppendFormat("{0}  ", orderbySQL); 
          Result = SQLHelper.ExecuteDataFill(DBConnection, System.Data.CommandType.Text,
                                                 sb.ToString(), new SqlParameter("@StartTime", From), new SqlParameter("@EndTime", To));

         return Result;
     }
        public override int SaveChanges()
        {
            try
            {
                return base.SaveChanges();
            }
            catch (DbEntityValidationException ex)
            {
                var sb = new StringBuilder();

                foreach (var failure in ex.EntityValidationErrors)
                {
                    sb.AppendFormat("{0} failed validation\n", failure.Entry.Entity.GetType());
                    foreach (var error in failure.ValidationErrors)
                    {
                        sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage);
                        sb.AppendLine();
                    }
                }

                throw new DbEntityValidationException(
                    "Entity Validation Failed - errors follow:\n" +
                    sb.ToString(), ex
                    ); // Add the original exception as the innerException
            }
        }
Esempio n. 29
0
 private string GetICSString(DateTime date, int duration, string name, string location, string shortDescription)
 {
     var sb = new StringBuilder();
     sb.AppendLine("BEGIN:VCALENDAR");
     sb.AppendLine("VERSION:1.0");
     sb.AppendLine("BEGIN:VEVENT");
     sb.AppendFormat("DTSTART:{0}", GetFormattedTime(date));
     sb.AppendLine();
     sb.AppendFormat("DTEND:{0}", GetFormattedTime(date.AddMinutes(duration)));
     sb.AppendLine();
     sb.AppendFormat("SUMMARY:{0}", name);
     sb.AppendLine();
     sb.AppendFormat("LOCATION:{0}", location);
     sb.AppendLine();
     string description = shortDescription;
     if (description.IsEmpty())
     {
         description = name;
     }
     sb.AppendFormat("DESCRIPTION:{0}", description.Replace(Environment.NewLine, " "));
     sb.AppendLine();
     sb.AppendLine("END:VEVENT");
     sb.AppendLine("END:VCALENDAR");
     return sb.ToString();
 }
        void IGrowlSender.SendNotification(IGrowlJob growl, string headline, string text)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("https://www.notifymyandroid.com/publicapi/notify?");
            // API-Key(s)
            sb.AppendFormat("apikey={0}", string.Join(",", growl.GetApiKeys()));
            // Application name
            sb.AppendFormat("&application={0}", HttpUtility.UrlEncode(growl.ApplicationName));
            // Event (max. 1000 chars)
            sb.AppendFormat("&event={0}", HttpUtility.UrlEncode(headline.Truncate(1000, true, true)));
            // Description (max. 10000 chars)
            sb.AppendFormat("&description={0}", HttpUtility.UrlEncode(text.Truncate(10000, true, true)));
            // Priority
            sb.AppendFormat("&priority={0}", EmergencyPriority);

            WebRequest notificationRequest = WebRequest.Create(sb.ToString());
            WebResponse notificationResponse = notificationRequest.GetResponse();

            NMAResponse logicalResponse = NMAResponse.ReadResponse(notificationResponse);
            if (!logicalResponse.IsSuccess)
            {
                Logger.Instance.LogFormat(LogType.Error, this, Properties.Resources.NMAApiKeyIsInvalid, logicalResponse.Message);
            }
            if (!logicalResponse.CanSendAnotherRequest)
            {
                Logger.Instance.LogFormat(LogType.Warning, this, Properties.Resources.NMANoRemainingRequestsLeft, logicalResponse.ResetTimer);
            }
        }
Esempio n. 31
0
        public static String Format(IFormatProvider provider, String format, params Object[] args)
        {
            var sb = new Text.StringBuilder();

            sb.AppendFormat(provider, format, args);
            return(sb.ToString());
        }
Esempio n. 32
0
        public static string DaubleTableToString(this double[] d)
        {
            var sb = new Text.StringBuilder();

            foreach (var r in d)
            {
                sb.AppendFormat("El: {0}", r);
                sb.AppendLine();
            }
            return(sb.ToString());
        }
Esempio n. 33
0
 private static void WriteDataRow(System.Text.StringBuilder sb, DataRow row)
 {
     sb.Append("{");
     foreach (DataColumn dataColumn in row.Table.Columns)
     {
         sb.AppendFormat("\"{0}\":", dataColumn.ColumnName);
         JSONConverter.WriteValue(sb, row[dataColumn]);
         sb.Append(",");
     }
     if (row.Table.Columns.Count > 0)
     {
         sb.Length--;
     }
     sb.Append("}");
 }
Esempio n. 34
0
        private void ProcessorUseVoucherBySelect(System.Web.HttpContext context)
        {
            decimal     orderAmount = decimal.Parse(context.Request["CartTotal"]);
            string      claimCode   = context.Request["VoucherCode"];
            VoucherInfo voucherInfo = ShoppingProcessor.UseVoucher(orderAmount, claimCode);

            System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
            if (voucherInfo != null)
            {
                stringBuilder.Append("{");
                stringBuilder.Append("\"Status\":\"OK\",");
                stringBuilder.AppendFormat("\"VoucherName\":\"{0}\",", voucherInfo.Name);
                stringBuilder.AppendFormat("\"DiscountValue\":\"{0}\"", Globals.FormatMoney(voucherInfo.DiscountValue));
                stringBuilder.Append("}");
            }
            else
            {
                stringBuilder.Append("{");
                stringBuilder.Append("\"Status\":\"ERROR\"");
                stringBuilder.Append("}");
            }
            context.Response.ContentType = "application/json";
            context.Response.Write(stringBuilder);
        }
Esempio n. 35
0
        //-----------------------------------------------------------------//
        public override string ToString()
        {
            StringBuilder carDetails = new System.Text.StringBuilder();

            carDetails.Append(base.ToString());
            carDetails.AppendFormat(@"Car Details:
    Color: {0}
    Number of Doors: {1}
",
                                    this.m_Color.ToString(),
                                    this.m_NumberOfDoors.ToString());
            carDetails.Append(Environment.NewLine);

            return(carDetails.ToString());
        }
Esempio n. 36
0
        public static string ToSqlAndString(this string fields, string key)
        {
            if (string.IsNullOrEmpty(fields))
            {
                return(fields);
            }
            var arrField = fields.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            var sb       = new System.Text.StringBuilder();

            sb.Append("(");
            for (var i = 0; i < arrField.Length; i++)
            {
                if (i == 0)
                {
                    sb.AppendFormat(" {0} like '%{1}%'", arrField[i], key);
                }
                else
                {
                    sb.AppendFormat(" and {0} like '%{1}%'", arrField[i], key);
                }
            }
            sb.Append(")");
            return(sb.ToString());
        }
        public IDataReader GetDataFromReader(string tableName, List <Column> tableColumns, List <PrimaryKey> tablePrimaryKeys)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder(200);
            sb.Append("SELECT ");
            foreach (Column col in tableColumns)
            {
                sb.Append(string.Format(System.Globalization.CultureInfo.InvariantCulture, "[{0}], ", col.ColumnName));
            }
            sb.Remove(sb.Length - 2, 2);

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

            sb.Append(SortSelect(tablePrimaryKeys));
            return(ExecuteDataReader(sb.ToString()));
        }
Esempio n. 38
0
 protected string GetMemberGrande()
 {
     System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
     System.Collections.Generic.IList <MemberGradeInfo> memberGrades = MemberHelper.GetMemberGrades();
     if (memberGrades != null && memberGrades.Count > 0)
     {
         foreach (MemberGradeInfo current in memberGrades)
         {
             stringBuilder.Append(" <label class=\"middle mr20\">");
             stringBuilder.AppendFormat("<input type=\"checkbox\" class=\"memberGradeCheck\" value=\"{0}\">{1}", current.GradeId, current.Name);
             stringBuilder.Append("  </label>");
         }
     }
     return(stringBuilder.ToString());
 }
Esempio n. 39
0
 protected string GetMemberCustomGroup()
 {
     System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
     System.Collections.Generic.IList <CustomGroupingInfo> customGroupingList = CustomGroupingHelper.GetCustomGroupingList();
     if (customGroupingList != null && customGroupingList.Count > 0)
     {
         foreach (CustomGroupingInfo current in customGroupingList)
         {
             stringBuilder.Append(" <label class=\"middle mr20\">");
             stringBuilder.AppendFormat("<input type=\"checkbox\" class=\"customGroup\" value=\"{0}\">{1}", current.Id, current.GroupName);
             stringBuilder.Append("  </label>");
         }
     }
     return(stringBuilder.ToString());
 }
Esempio n. 40
0
        private static bool SendApprovedEmail(int UserId)
        {
            UserViewData userView = UserBLL.GetUser(UserId);

            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            sb.AppendFormat("Dear {0},", userView.FullName);
            sb.AddNewHtmlLines(2);
            sb.Append("Your request to shipnpr.shiptalk.org account has been approved.");
            sb.AddNewHtmlLines(2);
            sb.Append("You may login anytime using your registered information.");
            sb.AddNewHtmlLines(2);

            sb.Append("If you do not know your new SHIPtalk password, you can reset it by going to <a href='https://shipnpr.shiptalk.org'>https://shipnpr.shiptalk.org</a> and clicking 'Forgot password?' in the left of the screen. Follow the instructions to have the password reset instructions emailed to you. Once you reset your password, you should be able to log in to the website with your username (email address) and new password.");
            sb.AddNewHtmlLines(2);

            sb.Append("Submit your entire email address so the instructions to reset your password will be emailed to you.");
            sb.AddNewHtmlLine();

            sb.Append("Thank you,");
            sb.AddNewHtmlLine();
            sb.Append("SHIP NPR Help Desk");
            sb.AddNewHtmlLine();
            sb.Append("<a href='https://shipnpr.shiptalk.org'>https://shipnpr.shiptalk.org</a>");
            sb.AddNewHtmlLine();
            sb.Append(ConfigUtil.ShiptalkSupportPhone);
            sb.AddNewHtmlLines(5);



            ShiptalkMailMessage mailMessage = new ShiptalkMailMessage(true, ShiptalkMailMessage.MailFrom.ShiptalkResourceCenter);

            mailMessage.ToList.Add(userView.PrimaryEmail);
            mailMessage.Subject = "Your shipnpr.shiptalk.org account is approved";

            mailMessage.Body = sb.ToString();
            ShiptalkMail mail = new ShiptalkMail(mailMessage);


            try
            {
                mail.SendMail();
                return(true);
            }
            catch { }

            return(false);
        }
Esempio n. 41
0
        BuildResult Respack(IProgressMonitor monitor, MoonlightProject proj, List <FilePath> toResGen, FilePath outfile)
        {
            monitor.Log.WriteLine("Packing resources...");

            var         runtime = proj.TargetRuntime;
            BuildResult result  = new BuildResult();

            string respack = runtime.GetToolPath(proj.TargetFramework, "respack");

            if (String.IsNullOrEmpty(respack))
            {
                result.AddError(null, 0, 0, null, "Could not find respack");
                result.FailedBuildCount++;
                return(result);
            }

            var si  = new System.Diagnostics.ProcessStartInfo();
            var env = runtime.GetToolsExecutionEnvironment(proj.TargetFramework);

            env.MergeTo(si);

            si.FileName         = respack.EndsWith(".exe")? "mono" : respack;
            si.WorkingDirectory = outfile.ParentDirectory;

            var sb = new System.Text.StringBuilder();

            if (respack.EndsWith(".exe"))
            {
                sb.Append(respack);
                sb.Append(" ");
            }
            sb.Append(outfile);

            foreach (var infile in toResGen)
            {
                sb.AppendFormat(" \"{0}\",\"{1}\"", infile.FullPath, infile.ToRelative(proj.BaseDirectory));
            }
            si.Arguments = sb.ToString();
            string err;
            int    exit = ExecuteCommand(monitor, si, out err);

            if (exit != 0)
            {
                result.AddError(null, 0, 0, exit.ToString(), "respack failed: " + err);
                result.FailedBuildCount++;
            }
            return(result);
        }
Esempio n. 42
0
        public System.Text.StringBuilder GetProductView(ProductQuery query, string localhost, string strformat, string skucontentformat, out int recordes)
        {
            System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
            int num = 0;

            System.Data.DataSet       productsByQuery = ProductHelper.GetProductsByQuery(query, out num);
            System.Text.StringBuilder stringBuilder2  = new System.Text.StringBuilder();
            foreach (System.Data.DataRow dataRow in productsByQuery.Tables[0].Rows)
            {
                string text = "false";
                System.Data.DataRow[] childRows = dataRow.GetChildRows("ProductRealation");
                System.Data.DataRow[] array     = childRows;
                for (int i = 0; i < array.Length; i++)
                {
                    System.Data.DataRow dataRow2 = array[i];
                    text = "true";
                    string skuContent = MessageInfo.GetSkuContent(dataRow2["SkuId"].ToString());
                    stringBuilder2.AppendFormat(skucontentformat, new object[]
                    {
                        dataRow2["ProductId"].ToString(),
                        dataRow2["SKuId"].ToString(),
                        skuContent,
                        dataRow2["Stock"].ToString(),
                        dataRow2["SalePrice"].ToString()
                    });
                }
                string text2 = localhost + Globals.GetSiteUrls().UrlData.FormatUrl("productDetails", new object[]
                {
                    dataRow["ProductId"].ToString()
                });
                stringBuilder.AppendFormat(strformat, new object[]
                {
                    dataRow["ProductId"].ToString(),
                    dataRow["ProductCode"].ToString(),
                    dataRow["ProductName"].ToString(),
                    localhost + dataRow["ThumbnailUrl60"].ToString(),
                    text2,
                    dataRow["MarketPrice"].ToString(),
                    dataRow["SalePrice"].ToString(),
                    dataRow["Weight"].ToString(),
                    dataRow["SaleStatus"].ToString(),
                    text,
                    stringBuilder2
                });
            }
            recordes = num;
            return(stringBuilder);
        }
 public static Dsl.DslFile LoadStory(string file)
 {
     if (!string.IsNullOrEmpty(file))
     {
         Dsl.DslFile dataFile = new Dsl.DslFile();
         var         bytes    = new byte[Dsl.DslFile.c_BinaryIdentity.Length];
         using (var fs = File.OpenRead(file)) {
             fs.Read(bytes, 0, bytes.Length);
             fs.Close();
         }
         var id = System.Text.Encoding.ASCII.GetString(bytes);
         if (id == Dsl.DslFile.c_BinaryIdentity)
         {
             try {
                 dataFile.LoadBinaryFile(file, StoryConfigManager.ReuseKeyBuffer, StoryConfigManager.ReuseIdBuffer);
                 return(dataFile);
             }
             catch (Exception ex) {
                 var sb = new System.Text.StringBuilder();
                 sb.AppendFormat("[LoadStory] LoadStory file:{0} Exception:{1}\n{2}", file, ex.Message, ex.StackTrace);
                 sb.AppendLine();
                 Helper.LogInnerException(ex, sb);
                 LogSystem.Error("{0}", sb.ToString());
             }
         }
         else
         {
             try {
                 if (dataFile.Load(file, LogSystem.Log))
                 {
                     return(dataFile);
                 }
                 else
                 {
                     LogSystem.Error("LoadStory file:{0} failed", file);
                 }
             }
             catch (Exception ex) {
                 var sb = new System.Text.StringBuilder();
                 sb.AppendFormat("[LoadStory] LoadStory file:{0} Exception:{1}\n{2}", file, ex.Message, ex.StackTrace);
                 sb.AppendLine();
                 Helper.LogInnerException(ex, sb);
                 LogSystem.Error("{0}", sb.ToString());
             }
         }
     }
     return(null);
 }
Esempio n. 44
0
 public static string FileHash(byte[] BArray)
 {
     using (System.IO.BufferedStream bs = new System.IO.BufferedStream(new System.IO.MemoryStream(BArray)))
     {
         using (System.Security.Cryptography.SHA1Managed sha1 = new System.Security.Cryptography.SHA1Managed())
         {
             byte[] hash = sha1.ComputeHash(bs);
             System.Text.StringBuilder formatted = new System.Text.StringBuilder(2 * hash.Length);
             foreach (byte b in hash)
             {
                 formatted.AppendFormat("{0:X2}", b);
             }
             return(formatted.ToString());
         }
     }
 }
Esempio n. 45
0
        /// <summary>
        /// returns the elements of the array as a string, delimited with the default delimitor
        /// </summary>
        /// <param name="array"></param>
        /// <returns></returns>
        public static string GetArrayContents(Array array)
        {
            System.Text.StringBuilder result = new System.Text.StringBuilder();

            foreach (object o in array)
            {
                result.AppendFormat("{0}{1} ", o.ToString(), DEFAULT_DELIMITER);
            }

            if (result.Length > 0)
            {
                result.Length -= 2;
            }

            return(result.ToString());
        }
Esempio n. 46
0
 public int UpdateIOSConfig(int IsIOSShop, int AgentID, int VersionNo, int SrcVersionNo, string AgentName, string AppKey, string AppSecret, string AppUrl)
 {
     System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
     stringBuilder.AppendFormat("UPDATE RYAgentDB.dbo.T_AgentIsIOS SET IsIOSShop={0},VersionNo={1},SrcVersionNo={2},AgentName='{4}',AppKey='{5}',AppSecret='{6}',AppUrl='{7}' WHERE AgentID={3}", new object[]
     {
         IsIOSShop,
         VersionNo,
         SrcVersionNo,
         AgentID,
         AgentName,
         AppKey,
         AppSecret,
         AppUrl
     });
     return(this.aideAccountsData.ExecuteSql(stringBuilder.ToString()));
 }
Esempio n. 47
0
        public static string ForEachType(IEnumerable <Type> types, string format, int lenToRemove)
        {
            var sb      = new System.Text.StringBuilder();
            var counter = 0;

            foreach (var type in types)
            {
                sb.AppendFormat(format, type.Name, TX.ToWinRT(type), counter);
                counter++;
            }
            if (sb.Length > 0)
            {
                sb.Remove(sb.Length - lenToRemove, lenToRemove);
            }
            return(sb.ToString());
        }
Esempio n. 48
0
        public void LoadSkinMenu()
        {
            SkinConfigMonitor watcher = (SkinConfigMonitor)Application["SkinWatcher"];

            Skin[] skins = watcher.CurrentScreen.Skins;

            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("<iframe  frameBorder='0' style='-moz-opacity:0; -webkit-opacity:0; opacity:0;  position:absolute; visibility:inherit; top:0px; left:-15px;  height:100%;width:150px; z-index:-1;background:none' ></iframe>");
            sb.Append("<ul ID='skin_change'>");
            foreach (Skin s in skins)
            {
                sb.AppendFormat("<LI  title='{0}' name='{2}' ><A href='#'><IMG  class=taskbar_tag_img src='{1}' width=17 height=14><SPAN>{0}</SPAN></A></LI>", s.Title, s.Icon, s.Name);
            }
            sb.Append("</ul>");
            skinBubbleCenter.Text = sb.ToString();
        }
Esempio n. 49
0
        public static string GeneratePasswordKey()
        {
            int    passwordLength             = 32;
            int    alphaNumericalCharsAllowed = 2;
            string randomPassword             = Membership.GeneratePassword(passwordLength, alphaNumericalCharsAllowed);

            // turn string into byte array
            byte[] bytes = System.Text.Encoding.Unicode.GetBytes(randomPassword);
            System.Text.StringBuilder hex = new System.Text.StringBuilder(bytes.Length * 2);
            foreach (byte b in bytes)
            {
                hex.AppendFormat("{0:x2}", b);
            }

            return(hex.ToString().ToUpper());
        }
Esempio n. 50
0
 private string GenerateValueItems(System.Collections.Generic.IList <AttributeValueInfo> values)
 {
     if (values != null && values.Count != 0)
     {
         System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
         foreach (AttributeValueInfo current in values)
         {
             stringBuilder.Append("{");
             stringBuilder.AppendFormat("\"ValueId\":\"{0}\",\"ValueStr\":\"{1}\"", current.ValueId.ToString(System.Globalization.CultureInfo.InvariantCulture), current.ValueStr);
             stringBuilder.Append("},");
         }
         stringBuilder.Remove(stringBuilder.Length - 1, 1);
         return(stringBuilder.ToString());
     }
     return(string.Empty);
 }
Esempio n. 51
0
    protected void btnexecl_Click(object sender, System.EventArgs e)
    {
        DataTable dt = new DataTable();

        System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
        if (this.txtSignPeople.Value.Trim() != "")
        {
            stringBuilder.AppendFormat(" AND v_xm LIKE '%{0}%'", this.txtSignPeople.Value.Trim());
        }
        if (this.hldfIsExamineApprove.Value == "1")
        {
            stringBuilder.Append(" AND p1.FlowState=1 ");
        }
        dt = (this.ViewState["contract"] as DataTable);
        new Common2().ExportToExecelAll(this.GetTitleByTable(dt), "收入合同结算报表.xls", base.Request.Browser.Browser);
    }
Esempio n. 52
0
        /// <summary>
        /// プロパティの一覧の文字列を作成する.
        /// </summary>
        /// <param name="properties">プロパティ</param>
        /// <returns>プロパティの一覧の文字列</returns>
        private static string MakePropertiesText(IEnumerable <Tuple <string, object> > properties)
        {
            var sb = new System.Text.StringBuilder();

            foreach (var prop in properties)
            {
                if ((prop.Item1 == null) || (prop.Item2 == null))
                {
                    continue;
                }

                sb.AppendFormat("<{0}>\n{1}\n\n", prop.Item1, prop.Item2);
            }

            return(sb.ToString());
        }
Esempio n. 53
0
 //加密的代码:
 /// <summary>
 /// DES加密
 /// </summary>
 /// <param name="str">要加密字符串</param>
 /// <returns>返回加密后字符串</returns>
 public static String Encrypt_DES(String str)
 {
     System.Security.Cryptography.DESCryptoServiceProvider des = new System.Security.Cryptography.DESCryptoServiceProvider();
     Byte[] inputByteArray = System.Text.Encoding.Default.GetBytes(str);
     des.Key = System.Text.ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(strDesKey, "md5").Substring(0, 8)); //加密对象的密钥
     des.IV  = System.Text.ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(strDesKey, "md5").Substring(0, 8)); //加密对象的偏移量,此两个值重要不能修改
     System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(ms, des.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
     cs.Write(inputByteArray, 0, inputByteArray.Length);
     cs.FlushFinalBlock();
     System.Text.StringBuilder sb = new System.Text.StringBuilder();
     foreach (Byte b in ms.ToArray())
     {
         sb.AppendFormat("{0:X2}", b);
     }
     return(sb.ToString());
 }
Esempio n. 54
0
 public static string GetMemberList(string list)
 {
     System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
     string[] array = list.Split(new char[]
     {
         ','
     }, System.StringSplitOptions.RemoveEmptyEntries);
     for (int i = 0; i < array.Length; i++)
     {
         stringBuilder.AppendFormat("{0},", TypeUtil.GetMemberName(byte.Parse(array[i])));
     }
     return(stringBuilder.ToString().TrimEnd(new char[]
     {
         ','
     }));
 }
Esempio n. 55
0
        public static string ToUnicode(string str)
        {
            string result = "";

            if (!string.IsNullOrEmpty(str))
            {
                System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
                byte[] bytes = System.Text.Encoding.Unicode.GetBytes(str);
                for (int i = 0; i < bytes.Length; i += 2)
                {
                    stringBuilder.AppendFormat("\\u{0}", bytes[i + 1].ToString("x").PadLeft(2, '0') + bytes[i].ToString("x").PadLeft(2, '0'));
                }
                result = stringBuilder.ToString();
            }
            return(result);
        }
Esempio n. 56
0
        //private static string reservedChars = "+~";

        /// <summary>
        /// Formats the list of request parameters into string a according
        /// to the requirements of oauth. The resulting string could be used
        /// in the Authorization header of the request.
        /// </summary>
        ///
        /// <remarks>
        ///   <para>
        ///     See http://dev.twitter.com/pages/auth#intro  for some
        ///     background.  The output of this is not suitable for signing.
        ///   </para>
        ///   <para>
        ///     There are 2 formats for specifying the list of oauth
        ///     parameters in the oauth spec: one suitable for signing, and
        ///     the other suitable for use within Authorization HTTP Headers.
        ///     This method emits a string suitable for the latter.
        ///   </para>
        /// </remarks>
        ///
        /// <param name="parameters">The Dictionary of
        /// parameters. It need not be sorted.</param>
        ///
        /// <returns>a string representing the parameters</returns>
        private static string EncodeRequestParameters(ICollection <KeyValuePair <string, string> > p)
        {
            var sb = new System.Text.StringBuilder();

            foreach (KeyValuePair <string, string> item in p.OrderBy(x => x.Key))
            {
                if (!string.IsNullOrEmpty(item.Value) && !item.Key.EndsWith("secret"))
                {
                    sb.AppendFormat("{0}={1}&",
                                    UrlEncode(item.Key),
                                    UrlEncode(item.Value));
                }
            }

            return(sb.ToString());
        }
Esempio n. 57
0
 public static string GetServiceArea(int intServiceArea)
 {
     System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
     System.Collections.Generic.IList <EnumDescription> serviceAreaList = ServiceAreaHelper.GetServiceAreaList(typeof(ServiceArea));
     foreach (EnumDescription current in serviceAreaList)
     {
         if (current.EnumValue == (intServiceArea & current.EnumValue))
         {
             stringBuilder.AppendFormat("{0},", ServiceAreaHelper.GetServiceAreaDes((ServiceArea)current.EnumValue));
         }
     }
     return(stringBuilder.ToString().TrimEnd(new char[]
     {
         ','
     }));
 }
Esempio n. 58
0
 /// <summary>
 /// 打开悬浮提示窗口
 /// </summary>
 /// <param name="page">页面指针 一般输入"this"</param>
 /// <param name="message">显示的消息</param>
 /// <param name="Width">窗口宽度</param>
 /// <param name="height">窗口高度</param>
 public static void OpenFloatDialog(System.Web.UI.Page page, string message, int Width, int height)
 {
     System.Text.StringBuilder Builder = new System.Text.StringBuilder();
     Builder.Append("<script type='text/javascript' language='javascript' defer>");
     //   Builder.Append("var msgw,msgh,bordercolor; ");
     Builder.AppendLine("function ShowBDDialog(){ ");
     Builder.AppendLine("bordercolor='#66ccff';titlecolor='#99CCFF';");
     Builder.AppendLine("var sWidth,sHeight; sWidth=document.body.offsetWidth; sHeight=document.body.offsetHeight;");
     Builder.AppendLine("var bgObj=document.createElement('div'); ");
     Builder.AppendLine(" bgObj.setAttribute('id','bgDiv'); ");
     Builder.AppendLine("bgObj.style.position='absolute'; ");
     Builder.AppendLine("bgObj.style.top='0'; bgObj.style.background='#dcdcdc';");
     Builder.AppendLine("bgObj.style.filter='progid:DXImageTransform.Microsoft.Alpha(style=3,opacity=25,finishOpacity=75';");
     Builder.AppendLine("bgObj.style.opacity='0.6'; ");
     Builder.AppendLine("bgObj.style.left='0';");
     Builder.AppendLine("bgObj.style.width=sWidth + 'px'; ");
     Builder.AppendLine("bgObj.style.height=sHeight + 'px';");
     Builder.AppendLine("document.body.appendChild(bgObj); ");
     Builder.AppendLine("var msgObj=document.createElement('div')");
     Builder.AppendLine("msgObj.setAttribute('id','msgDiv');");
     Builder.AppendLine("msgObj.setAttribute('align','center');");
     Builder.AppendLine("msgObj.style.position='absolute';msgObj.style.background='white'; ");
     Builder.AppendLine("msgObj.style.font='12px/1.6em Verdana, Geneva, Arial, Helvetica, sans-serif';");
     Builder.AppendLine("msgObj.style.border='1px solid ' + bordercolor;");
     Builder.AppendFormat("msgObj.style.width='{0} '+ 'px'; ", Width);
     Builder.AppendFormat("msgObj.style.height='{0}' + 'px';", height);
     Builder.AppendFormat("msgObj.style.top=(document.documentElement.scrollTop + (sHeight-'{0}')/2) + 'px';", height);
     Builder.AppendFormat("msgObj.style.left=(sWidth-'{0}')/2 + 'px';", Width);
     Builder.AppendLine("var title=document.createElement('h4');");
     Builder.AppendLine("title.setAttribute('id','msgTitle');");
     Builder.AppendLine("title.setAttribute('align','right');");
     Builder.AppendLine("title.style.margin='0'; ");
     Builder.AppendLine("title.style.padding='3px'; title.style.background=bordercolor; ");
     Builder.AppendLine("title.style.filter='progid:DXImageTransform.Microsoft.Alpha(startX=20, startY=20, finishX=100, finishY=100,style=1,opacity=75,finishOpacity=100);'; ");
     Builder.AppendLine("title.style.opacity='0.75'; ");
     Builder.AppendLine("title.style.border='1px solid ' + bordercolor;title.innerHTML='<a style=font-size:small href=#>关闭</a>'; ");
     Builder.AppendLine("title.onclick=function(){ document.body.removeChild(bgObj);document.getElementById('msgDiv').removeChild(title); document.body.removeChild(msgObj);} ");
     Builder.AppendLine("document.body.appendChild(msgObj); ");
     Builder.AppendLine("document.getElementById('msgDiv').appendChild(title);");
     Builder.AppendLine("var txt=document.createElement('p');");
     Builder.AppendFormat("txt.style.height='{0}';", height);
     Builder.AppendFormat("txt.style.width='{0}';", Width);
     Builder.AppendLine(" txt.style.margin='1em 0' ");
     Builder.AppendLine("txt.setAttribute('id','msgTxt');");
     Builder.AppendFormat("txt.innerHTML='{0}'; ", message);
     Builder.AppendLine("document.getElementById('msgDiv').appendChild(txt);return false;}");
     Builder.AppendLine(" ShowBDDialog(); </script>");
     page.Response.Write(Builder.ToString());
     page.ClientScript.RegisterStartupScript(page.GetType(), "message", "<script language='javscript'>ShowBDDialog();</" + "script>");
 }
Esempio n. 59
0
        public static string UrlEncode(string str, string encode)
        {
            int factor = 0;

            if (encode == "UTF-8")
            {
                factor = 3;
            }
            if (encode == "GB2312")
            {
                factor = 2;
            }
            //不需要编码的字符

            string okChar = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.";

            System.Text.Encoder encoder = System.Text.Encoding.GetEncoding(encode).GetEncoder();
            char[] c1 = str.ToCharArray();
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            //一个字符一个字符的编码

            for (int i = 0; i < c1.Length; i++)
            {
                //不需要编码

                if (okChar.IndexOf(c1[i]) > -1)
                {
                    sb.Append(c1[i]);
                }
                else
                {
                    byte[] c2 = new byte[factor];
                    int    charUsed, byteUsed; bool completed;

                    encoder.Convert(c1, i, 1, c2, 0, factor, true, out charUsed, out byteUsed, out completed);

                    foreach (byte b in c2)
                    {
                        if (b != 0)
                        {
                            sb.AppendFormat("%{0:X}", b);
                        }
                    }
                }
            }
            return(sb.ToString().Trim());
        }
Esempio n. 60
0
        /// <summary>
        /// post请求不带Token
        /// </summary>
        /// <param name="url"></param>
        /// <param name="dic"></param>
        /// <returns></returns>
        public static string Post(string url, Dictionary <string, string> dic)
        {
            string result = "";

            try
            {
                //添加Post 参数
                System.Text.StringBuilder builder = new System.Text.StringBuilder();
                int i = 0;
                foreach (var item in dic)
                {
                    if (i > 0)
                    {
                        builder.Append("&");
                    }
                    builder.AppendFormat("{0}={1}", item.Key, item.Value);
                    i++;
                }
                byte[] postData = System.Text.Encoding.UTF8.GetBytes(builder.ToString());

                System.Net.HttpWebRequest _webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
                _webRequest.Method = "POST";
                //_webRequest.ContentType = "application/json";
                //内容类型
                _webRequest.ContentType   = "application/x-www-form-urlencoded";
                _webRequest.Timeout       = 1000 * 30;
                _webRequest.ContentLength = postData.Length;

                using (System.IO.Stream reqStream = _webRequest.GetRequestStream())
                {
                    reqStream.Write(postData, 0, postData.Length);
                    reqStream.Close();
                }
                System.Net.HttpWebResponse resp   = (System.Net.HttpWebResponse)_webRequest.GetResponse();
                System.IO.Stream           stream = resp.GetResponseStream();
                //获取响应内容
                using (System.IO.StreamReader reader = new System.IO.StreamReader(stream, System.Text.Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                }
                return(result);
            }
            catch (Exception)
            {
                return("");
            }
        }