Ejemplo n.º 1
1
        public void ProcessRequest(HttpContext context)
        {
            System.Text.StringBuilder result = new System.Text.StringBuilder();
            context.Response.ContentType = "application/json";

            try
            {
                int id;
                bool parsed = int.TryParse(context.Request.QueryString["id"], out id);

                if (!parsed)
                {
                    result.Append("{success: false, msg: '非法的标识'}");
                    context.Response.Write(result.ToString());
                    return;
                }

                CY.GeneralPrivilege.Core.Business.PermissionsList pl = CY.GeneralPrivilege.Core.Business.PermissionsList.Load(id);

                if (pl != null)
                {
                    pl.DeleteOnSave();
                    pl.Save();
                }

                result.Append("{success: true}");
            }
            catch (Exception ex)
            {
                result = new System.Text.StringBuilder();
                result.Append("{success: false, msg: '删除失败'}");
            }

            context.Response.Write(result.ToString());
        }
Ejemplo n.º 2
0
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            ClientScriptManager csm = Page.ClientScript;
            Type csType = this.Page.GetType();
            String csKey = "BIResources";
            if (!csm.IsClientScriptBlockRegistered(csType, csKey))
            {
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                sb.Append("<script type=\"text/javascript\">");
                sb.AppendFormat("var Milion_CurrencySymbol = '{0}';", Resources.BI.Milion_CurrencySymbol);
                sb.Append("</script>");
                csm.RegisterClientScriptBlock(csType, csKey, sb.ToString());
            }

            Control wc;
            switch(Get_Param_SubMenuCode())
            {
                case "asis_AC":
                    wc = LoadControl("wcACCube.ascx");
                    break;
                case "asis_IC":
                    wc = LoadControl("wcICCube.ascx");
                    break;
                default:
                    wc = LoadControl("wcSaleCube.ascx");
                    break;
            }
            AnalysisPlaceHolder.Controls.Add(wc);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Converts a number to System.String.
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        public static System.String ToString(long number)
        {
            System.Text.StringBuilder s = new System.Text.StringBuilder();

            if (number == 0)
            {
                s.Append("0");
            }
            else
            {
                if (number < 0)
                {
                    s.Append("-");
                    number = -number;
                }

                while (number > 0)
                {
                    char c = digits[(int)number % 36];
                    s.Insert(0, c);
                    number = number / 36;
                }
            }

            return s.ToString();
        }
Ejemplo n.º 4
0
 public void export(QuadNode node, List<System.Text.StringBuilder> result)
 {
     //List<string> _Result = new List<string>();
     System.Text.StringBuilder item = new System.Text.StringBuilder("");
     item.Append(String.Format("{0}\t{1}\t{2}\t{3}\t{4}",
                             node._id.ToString().Trim(),
                             node._bounds.X.ToString().Trim(),
                             node._bounds.Y.ToString().Trim(),
                             node._bounds.Width.ToString().Trim(),
                             node._bounds.Height.ToString().Trim()));
     if (node._nodeBL != null)
     {
         export(node._nodeBL, result);
         export(node._nodeBR, result);
         export(node._nodeTL, result);
         export(node._nodeTR, result);
     }
     else
     {
         for (int i = 0; i < node._listObject.Count;++i )
         {
             item.Append( "\t" + node._listObject[i]._id.ToString().Trim());
         }
     }
     result.Add(item);
 }
        /// <summary>
        ///     Ensures that if the identifier contains a hyphen or other special characters that it will be escaped by tick (`) characters.
        /// </summary>
        /// <param name="identifier">The identifier to format</param>
        /// <returns>An escaped identifier, if escaping was required.  Otherwise the original identifier.</returns>
        public static string EscapeIdentifier(string identifier)
        {
            if (identifier == null)
            {
                throw new ArgumentNullException("identifier");
            }

            bool containsSpecialChar = false;
            for (var i = 0; i < identifier.Length; i++)
            {
                if (!Char.IsLetterOrDigit(identifier[i]))
                {
                    containsSpecialChar = true;
                    break;
                }
            }

            if (!containsSpecialChar)
            {
                return identifier;
            }
            else
            {
                var sb = new System.Text.StringBuilder(identifier.Length + 2);

                sb.Append('`');
                sb.Append(identifier.Replace("`", "``"));
                sb.Append('`');
                return sb.ToString();
            }
        }
Ejemplo n.º 6
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if ( LRegistro.ExisteSesion( Session ) )
            {
                if ( !IsPostBack )
                {
                    // Si utilizamos using System.Text no hace falta invocar con System.Text.StringBuilder()
                    System.Text.StringBuilder sbMiSaludo = new System.Text.StringBuilder();

                    sbMiSaludo.AppendFormat("Hola {0}", LRegistro.NombreUsuario(Session));

                    liSaludo.Text = sbMiSaludo.ToString();

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

                    sbMiSaludo2.Append("Hola ");
                    sbMiSaludo2.Append(LRegistro.NombreUsuario(Session));

                    // sbMiSaludo2.Append("Hola " + LRegistro.NombreUsuario(Session));
                } // IsPosBack
            }
            else
            {
                // Si no hay sessión le expulso
                Response.Redirect("index.aspx");
            }
        }
Ejemplo n.º 7
0
        /// <summary></summary>
        /// <returns></returns>
        public override string ToString()
        {
            /*
            function<out Function func> =	(. func = new Function();
                                    Expression exp = null;
                                .)
            ident						(. func.Name = t.val; .)
            '(' expr<out exp>			(. func.Expression = exp; .)
            ')'
            .
            */
            System.Text.StringBuilder txt = new System.Text.StringBuilder();
            txt.AppendFormat("{0}(", name);
            if (expression != null) {
                bool first = true;
                foreach (Term t in expression.Terms) {
                    //if (t.Value.EndsWith("=")) {
                    if (first) {
                        first = false;
                    } else if (t.Value != null && !t.Value.EndsWith("=")) {
                        txt.Append(", ");
                    }

                    bool quoteMe = false;
                    if (t.Type == TermType.String && !t.Value.EndsWith("=")) {
                        quoteMe = true;
                    }
                    if (quoteMe) { txt.Append("'"); }
                    txt.Append(t.ToString());
                    if (quoteMe) { txt.Append("'"); }
                }
            }
            txt.Append(")");
            return txt.ToString();
        }
 private static async Task<Document> RemoveTrailingWhiteSpaceAsync(Document document, Diagnostic diagnostic, CancellationToken cancellationToken)
 {
     var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
     var trivia = root.FindTrivia(diagnostic.Location.SourceSpan.End - 1);
     SyntaxNode newRoot;
     if (trivia.IsKind(SyntaxKind.WhitespaceTrivia))
     {
         newRoot = root.ReplaceTrivia(trivia, new SyntaxTrivia[] { });
     }
     else if (trivia.IsKind(SyntaxKind.SingleLineDocumentationCommentTrivia, SyntaxKind.MultiLineDocumentationCommentTrivia))
     {
         var commentText = trivia.ToFullString();
         var commentLines = commentText.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
         var newComment = "";
         var builder = new System.Text.StringBuilder();
         builder.Append(newComment);
         for (int i = 0; i < commentLines.Length; i++)
         {
             var commentLine = commentLines[i];
             builder.Append(Regex.Replace(commentLine, @"\s+$", ""));
             if (i < commentLines.Length - 1) builder.Append(Environment.NewLine);
         }
         newComment = builder.ToString();
         newRoot = root.ReplaceTrivia(trivia, SyntaxFactory.SyntaxTrivia(SyntaxKind.DocumentationCommentExteriorTrivia, newComment));
     }
     else
     {
         var triviaNoTrailingWhiteSpace = Regex.Replace(trivia.ToFullString(), @"\s+$", "");
         newRoot = root.ReplaceTrivia(trivia, SyntaxFactory.ParseTrailingTrivia(triviaNoTrailingWhiteSpace));
     }
     return document.WithSyntaxRoot(newRoot);
 }
Ejemplo n.º 9
0
        public SelectModel GetCashSelectModel(int pageIndex, int pageSize, string orderStr, int pledgeApplyId)
        {
            NFMT.Common.SelectModel select = new NFMT.Common.SelectModel();

            select.PageIndex = pageIndex;
            select.PageSize = pageSize;
            if (string.IsNullOrEmpty(orderStr))
                select.OrderStr = "psd.ContractNo desc";
            else
                select.OrderStr = orderStr;

            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append(" psd.ContractNo as StockContractNo,psd.Deadline,SUM(Hands) as Hands,bank.BankName as AccountName ");
            select.ColumnName = sb.ToString();

            sb.Clear();
            sb.Append(" dbo.Fin_PledgeApply pa ");
            sb.AppendFormat(" inner join dbo.Fin_PledgeApplyStockDetail psd on pa.PledgeApplyId = psd.PledgeApplyId and psd.DetailStatus ={0} ", (int)Common.StatusEnum.已生效);
            sb.Append(" left join NFMT_Basic..Bank bank on pa.FinancingBankId = bank.BankId ");
            select.TableName = sb.ToString();

            sb.Clear();
            sb.AppendFormat(" pa.PledgeApplyId ={0} group by psd.ContractNo,psd.Deadline,bank.BankName ", pledgeApplyId);

            select.WhereStr = sb.ToString();

            return select;
        }
Ejemplo n.º 10
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            contact.addContact(
                Guid.Parse(hfUserId.Value),
                txtAddAddress.Text,
                txtAddHomeAddress.Text,
                txtAddCity.Text,
                txtAddProvince.Text,
                txtAddZipCode.Text,
                txtAddCountry.Text,
                txtAddPhoneNumber.Text,
                txtAddEmail.Text,
                txtAddGuardianName.Text,
                txtAddRelationship.Text,
                txtAddGuardianAddress.Text,
                txtAddGuardianPhone.Text);

            BindData();

            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append(@"<script type='text/javascript'>");
            sb.Append("$('#addModal').modal('hide');");
            sb.Append(@"</script>");
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "HideShowModalScript", sb.ToString(), false);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Logs a message to the console.
        /// </summary>
        /// <param name="style"> A style which influences the icon and text color. </param>
        /// <param name="objects"> The objects to output to the console. These can be strings or
        /// ObjectInstances. </param>
        public void Log(FirebugConsoleMessageStyle style, object[] objects)
        {
#if !SILVERLIGHT
            var original = Console.ForegroundColor;
            switch (style)
            {
                case FirebugConsoleMessageStyle.Information:
                    Console.ForegroundColor = ConsoleColor.White;
                    break;
                case FirebugConsoleMessageStyle.Warning:
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    break;
                case FirebugConsoleMessageStyle.Error:
                    Console.ForegroundColor = ConsoleColor.Red;
                    break;
            }
#endif

            // Convert the objects to a string.
            var message = new System.Text.StringBuilder();
            for (int i = 0; i < objects.Length; i++)
            {
                message.Append(' ');
                message.Append(TypeConverter.ToString(objects[i]));
            }

            // Output the message to the console.
            Console.WriteLine(message.ToString());


#if !SILVERLIGHT
            if (style != FirebugConsoleMessageStyle.Regular)
                Console.ForegroundColor = original;
#endif
        }
Ejemplo n.º 12
0
		/// <summary> Replaces unprintable characters by their espaced (or unicode escaped)
		/// equivalents in the given string
		/// </summary>
		protected internal static System.String AddEscapes(System.String str)
		{
			System.Text.StringBuilder retval = new System.Text.StringBuilder();
			char ch;
			for (int i = 0; i < str.Length; i++)
			{
				switch (str[i])
				{
					
					case (char) (0): 
						continue;
					
					case '\b': 
						retval.Append("\\b");
						continue;
					
					case '\t': 
						retval.Append("\\t");
						continue;
					
					case '\n': 
						retval.Append("\\n");
						continue;
					
					case '\f': 
						retval.Append("\\f");
						continue;
					
					case '\r': 
						retval.Append("\\r");
						continue;
					
					case '\"': 
						retval.Append("\\\"");
						continue;
					
					case '\'': 
						retval.Append("\\\'");
						continue;
					
					case '\\': 
						retval.Append("\\\\");
						continue;
					
					default: 
						if ((ch = str[i]) < 0x20 || ch > 0x7e)
						{
							System.String s = "0000" + System.Convert.ToString(ch, 16);
							retval.Append("\\u" + s.Substring(s.Length - 4, (s.Length) - (s.Length - 4)));
						}
						else
						{
							retval.Append(ch);
						}
						continue;
					
				}
			}
			return retval.ToString();
		}
Ejemplo n.º 13
0
        protected string DetermineRecipientCount()
        {
            string strCounties = (AllCounties.Checked) ? "All" : Session["Criteria-County"].ToString();
            string strSchools = (AllSchools.Checked) ? "All" : Session["Criteria-School"].ToString();
            string strGrades = (AllGrades.Checked) ? "All" : Session["Criteria-Grade"].ToString();
            string strCareers = (AllCareers.Checked) ? "All" : Session["Criteria-Career"].ToString();
            string strClusters = (AllClusters.Checked) ? "All" : Session["Criteria-Cluster"].ToString();
            string strGender = Session["GenderChoice"].ToString();

            System.Text.StringBuilder sbSQL = new System.Text.StringBuilder();
            sbSQL.Append("select count(portfolioid) from PortfolioUserInfo where active=1 and ConSysID=" + ConSysID);

            if (strGender != "All")
                sbSQL.Append(" and GenderID in (" + strGender + ")");
            if (strGrades != "All")
                sbSQL.Append(" and GradeNumber in (" + strGrades + ")");
            if (strSchools != "All")
                sbSQL.Append(" and SchoolID in (" + strSchools + ")");
            if (strCounties != "All")
                sbSQL.Append(" and CountyID in (" + strCounties + ")");
            if (strCareers != "All")
                sbSQL.Append(" and PortfolioID in (Select PortfolioID from Port_SavedCareers where OccNumber in (" + strCareers + "))");
            if (strClusters != "All")
                sbSQL.Append(" and PortfolioID in (Select PortfolioID from Port_ClusterInterests where ClusterID in (" + strClusters + "))");

            return CCLib.Common.DataAccess.GetValue(sbSQL.ToString()).ToString();
        }
Ejemplo n.º 14
0
        public String GenerateMap()
        {
            System.Text.StringBuilder builderMap = new System.Text.StringBuilder();
            int tamanho = Constantes.tamLabirinto;
            Random rand = new Random();

            for (int i = 0; i < tamanho; i++)
                builderMap.Append("P");

            for (int i = 0; i < tamanho-2; i++) {
                builderMap.Append("PC");
                for (int j = 0; j < tamanho-4; j++)
                    if (i == 0 || i == tamanho-3)
                        builderMap.Append("C");
                    else
                        if (rand.Next() % 3 != 0)
                            builderMap.Append("C");
                        else
                        builderMap.Append("P");
                builderMap.Append("CP");
            }

            for (int i = 0; i < tamanho; i++)
                builderMap.Append("P");

            return builderMap.ToString();
        }
Ejemplo n.º 15
0
        protected void gvAnn_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.Equals("editRecord"))
            {
                dt = new DataTable();
                int index = Convert.ToInt32(e.CommandArgument);
                System.Text.StringBuilder sb = new System.Text.StringBuilder();

                dt = ann.getAnnById((int)(gvAnn.DataKeys[index].Value));
                lblRowId.Text = dt.Rows[0]["Id"].ToString();
                ddlEditType.SelectedItem.Text = dt.Rows[0]["Type"].ToString();
                txtEditTitle.Text = dt.Rows[0]["Title"].ToString();
                txtEditContent.Text = dt.Rows[0]["Content"].ToString();

                sb.Append(@"<script type='text/javascript'>");
                sb.Append("$('#updateModal').modal('show');");
                sb.Append(@"</script>");
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "EditShowModalScript", sb.ToString(), false);
            }
            else if (e.CommandName.Equals("deleteRecord"))
            {
                int index = Convert.ToInt32(e.CommandArgument);
                string rowId = ((Label)gvAnn.Rows[index].FindControl("lblRowId")).Text;
                hfDeleteId.Value = rowId;

                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                sb.Append(@"<script type='text/javascript'>");
                sb.Append("$('#deleteModal').modal('show');");
                sb.Append(@"</script>");
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "DeleteShowModalScript", sb.ToString(), false);
            }
        }
Ejemplo n.º 16
0
        private void Load_NavigateConten(string strType)
        {
            if (strType == "hr")
            {
                zlzw.BLL.GeneralBasicSettingBLL generalBasicSettingBLL = new zlzw.BLL.GeneralBasicSettingBLL();
                System.Data.DataTable dt = generalBasicSettingBLL.GetList("DisplayName='" + strType + "'").Tables[0];
                zlzw.BLL.ExchangeCornerListBLL exchangeCornerListBLL = new zlzw.BLL.ExchangeCornerListBLL();
                System.Data.DataTable dt01 = exchangeCornerListBLL.GetList("ExchangeCornerTypeKey='" + dt.Rows[0]["SettingKey"].ToString() + "'").Tables[0];
                titleName.Text = dt01.Rows[0]["ExchangeCornerTitle"].ToString();
                System.Text.StringBuilder strBuilder = new System.Text.StringBuilder();
                strBuilder.Append("<table style='width:100%;'><tr><td algin='center' style='width:38%;font-size:14px;'>文件名称</td><td style='font-size:14px;'>文件大小</td><td style='font-size:14px;'>发布日期</td><td style='font-size:14px;'>点击下载</td></tr>");
                for (int nCount = 0; nCount < dt01.Rows.Count; nCount++)
                {
                    strBuilder.Append("<tr><td algin='center'><a href='" + dt01.Rows[nCount]["ExchangeCornerFilePath"].ToString().Split('~')[1] + "' style='text-decoration:none;color:#000; href='" + dt01.Rows[nCount]["ExchangeCornerFilePath"].ToString().Split('~')[1] + "' style='color:#355F95;font-weight:bold;text-decoration:none;''>" + dt01.Rows[nCount]["ExchangeCornerTitle"].ToString() + "</a></td><td algin='center'>" + Get_FileSize(int.Parse(dt01.Rows[nCount]["ExchangeCornerFileSize"].ToString())) + "</td><td algin='center'>" + Set_DateFormat(dt01.Rows[nCount]["PublishDate"].ToString()) + "</td><td algin='center'><a href='" + dt01.Rows[nCount]["ExchangeCornerFilePath"].ToString().Split('~')[1] + "' style='color:#355F95;font-weight:bold;text-decoration:none;'>下载地址</td></tr>");
                }
                strBuilder.Append("</table>");
                labContent.Text = strBuilder.ToString();
            }
            else
            {
                zlzw.BLL.GeneralBasicSettingBLL generalBasicSettingBLL = new zlzw.BLL.GeneralBasicSettingBLL();
                System.Data.DataTable dt = generalBasicSettingBLL.GetList("DisplayName='" + strType + "'").Tables[0];
                zlzw.BLL.ExchangeCornerListBLL exchangeCornerListBLL = new zlzw.BLL.ExchangeCornerListBLL();
                System.Data.DataTable dt01 = exchangeCornerListBLL.GetList("ExchangeCornerTypeKey='" + dt.Rows[0]["SettingKey"].ToString() + "'").Tables[0];
                titleName.Text = dt01.Rows[0]["ExchangeCornerTitle"].ToString();
                labContent.Text = dt01.Rows[0]["exchangecornercontent"].ToString();
            }

        }
Ejemplo n.º 17
0
        /// <summary>
        /// Returns a string representation of this IDictionary.
        /// </summary>
        /// <remarks>
        /// The string representation is a list of the collection's elements in the order 
        /// they are returned by its IEnumerator, enclosed in curly brackets ("{}").
        /// The separator is a comma followed by a space i.e. ", ".
        /// </remarks>
        /// <param name="dict">Dictionary whose string representation will be returned</param>
        /// <returns>A string representation of the specified dictionary or "null"</returns>
        public static string DictionaryToString(IDictionary dict)
        {
            StringBuilder sb = new StringBuilder();

            if (dict != null)
            {
                sb.Append("{");
                int i = 0;
                foreach (DictionaryEntry e in dict)
                {
                    if (i > 0)
                    {
                        sb.Append(", ");
                    }

                    if (e.Value is IDictionary)
                        sb.AppendFormat("{0}={1}", e.Key.ToString(), DictionaryToString((IDictionary)e.Value));
                    else if (e.Value is IList)
                        sb.AppendFormat("{0}={1}", e.Key.ToString(), ListToString((IList)e.Value));
                    else
                        sb.AppendFormat("{0}={1}", e.Key.ToString(), e.Value.ToString());
                    i++;
                }
                sb.Append("}");
            }
            else
                sb.Insert(0, "null");

            return sb.ToString();
        }
Ejemplo n.º 18
0
 public void OutputWrite(string S)
 {
     System.Text.StringBuilder SB = new System.Text.StringBuilder (OutputBox.Buffer.Text);
     SB.Append (S);
     SB.Append ("\n");
     OutputBox.Buffer.Text = SB.ToString ();
 }
Ejemplo n.º 19
0
        public static string getUserName()
        {
            try
            {
                var x = "";

                var connectionOptions = new ConnectionOptions();

                var scope = new System.Management.ManagementScope("\\\\localhost", connectionOptions);
                var query = new System.Management.ObjectQuery("select * from Win32_ComputerSystem");

                using (var searcher = new ManagementObjectSearcher(scope, query))
                {
                    var builder = new System.Text.StringBuilder();
                    builder.Append(x);

                    foreach (var row in searcher.Get())
                    {
                        builder.Append((row["UserName"].ToString() + " "));
                    }
                    x = builder.ToString();

                    return x;
                }
            }
            catch (Exception ex)
            {
                return "";
            }
        }
Ejemplo n.º 20
0
 /// <summary>
 /// 加载列表
 /// </summary>
 private void InitScenicList()
 {
     PageInfo pi = new PageInfo();
     pi.PageIndex = 1;
     pi.PageSize = int.MaxValue;
     pi.AddCondition<HotspotScenicsDTO>(o => o.publishtarget, Target, QueryMethod.Equal);
     pi.AddCondition<HotspotScenicsDTO>(o => o.is_valid, 1, QueryMethod.Equal);
     //Response.Write(pi.ToSqlCondition());
     var list = BHotspot.GetScenicsList(pi);
     if (list != null)
     {
         System.Text.StringBuilder tmpStr = new System.Text.StringBuilder();
         tmpStr.Append("<li>");
         for (int i = 0; i < list.Count(); i++)
         {
             if ((i + 1) % 2 == 0)
             {
                 tmpStr.Append("<div class=\"list_div right\"><img class=\"list_img\" src=\"" + Common.NoPhotoDefault(list[i].coverphoto) + "\"><h1>" + list[i].hotspot_name + "</h1><p>" + list[i].tourtime + "</p><a href=\"javascript:void(0)\" ID=\"" + list[i].id + "\" EID=\"" + list[i].hotspot_id + "\" class=\"jingdianAdd\">&nbsp;</a></div>");
             }
             else
             {
                 tmpStr.Append("<div class=\"list_div left\"><img class=\"list_img\" src=\"" + Common.NoPhotoDefault(list[i].coverphoto) + "\"><h1>" + list[i].hotspot_name + "</h1><p>" + list[i].tourtime + "</p><a href=\"javascript:void(0)\" ID=\"" + list[i].id + "\" EID=\"" + list[i].hotspot_id + "\" class=\"jingdianAdd\">&nbsp;</a></div>");
             }
             
             if ((i+1) % 2 == 0) { tmpStr.Append("</li><li>"); }
         }
         tmpStr.Append("</li>");
         this.ltrJD.Text = tmpStr.ToString();
     }
 }
Ejemplo n.º 21
0
        public HttpResponseMessage list()
        {
            dynamic errorlog = entity.ErrorLogGetList().ToList<ErrorLogGetList_Result>();

            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("<html><head><style></style></head><body>");

            foreach (ErrorLogGetList_Result e in errorlog)
            {
                sb.Append("<table border='1' style='border-collapse:collapse; border:1px gray solid; font-size:8pt;'>");
                sb.AppendFormat("<tr bgcolor=#FFFF00> <td> ERROR SN </td> <td>{0}</td> </tr>", e.logsn);
                sb.AppendFormat("<tr> <td> IP </td> <td>{0}</td> </tr>", e.ip);
                sb.AppendFormat("<tr> <td> URI </td> <td>{0}</td> </tr>", e.uri);
                sb.AppendFormat("<tr> <td> SOURCE </td> <td>{0}</td> </tr>", e.source);
                sb.AppendFormat("<tr> <td> METHOD </td> <td>{0}</td> </tr>", e.method);
                sb.AppendFormat("<tr> <td> DATE </td> <td>{0}</td> </tr>", e.dtcreate);
                sb.AppendFormat("<tr> <td> ERROR </td> <td>{0}</td> </tr>", e.error);
                sb.AppendFormat("<tr> <td> TRACE </td> <td>{0}</td> </tr>", e.trace.Replace("\n", "<br />").Replace("\t", "<br />"));
                sb.AppendFormat("<tr> <td> INPU JSON </td> <td>{0}</td> </tr>", e.json);
                sb.Append("<table>");

                sb.Append("<hr />");
            }
            sb.Append("</body></html>");

            var response = new HttpResponseMessage();
            response.Content = new StringContent(sb.ToString());
            response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("text/html");

            return response;
        }
		/// <summary> Given a string that contains HL7 messages, and possibly other junk, 
		/// returns an array of the HL7 messages.  
		/// An attempt is made to recognize segments even if there is other 
		/// content between segments, for example if a log file logs segments 
		/// individually with timestamps between them.  
		/// 
		/// </summary>
		/// <param name="theSource">a string containing HL7 messages 
		/// </param>
		/// <returns> the HL7 messages contained in theSource
		/// </returns>
        private static System.String[] getHL7Messages(System.String theSource)
        {
            System.Collections.ArrayList messages = new System.Collections.ArrayList(20);
            Match startMatch = new Regex("^MSH", RegexOptions.Multiline).Match(theSource);

            foreach (Group group in startMatch.Groups)
            {
                System.String messageExtent = getMessageExtent(theSource.Substring(group.Index), "^MSH");

                char fieldDelim = messageExtent[3];

                Match segmentMatch = Regex.Match(messageExtent, "^[A-Z]{3}\\" + fieldDelim + ".*$", RegexOptions.Multiline);

                System.Text.StringBuilder msg = new System.Text.StringBuilder();
                foreach (Group segGroup in segmentMatch.Groups)
                {
                    msg.Append(segGroup.Value.Trim());
                    msg.Append('\r');
                }

                messages.Add(msg.ToString());
            }

            String[] retVal = new String[messages.Count];
            messages.CopyTo(retVal);

            return retVal;
        }
Ejemplo n.º 23
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Sitecore.Links.UrlOptions urlOptions = new Sitecore.Links.UrlOptions();
            urlOptions.AlwaysIncludeServerUrl = true;
            urlOptions.AddAspxExtension = true;
            urlOptions.LanguageEmbedding = LanguageEmbedding.Never;

            var homeItem = Sitecore.Context.Database.GetItem(Sitecore.Context.Site.StartPath.ToString());
            homePageUrl = Sitecore.Links.LinkManager.GetItemUrl(homeItem, urlOptions);

            //Add dynamic content to header
            HtmlHead head = (HtmlHead)Page.Header;

            //Add Open Tag
            if (Session["sess_User"] != null)
            {
                User objUser = (User)Session["sess_User"];
                if (objUser.Preferences != null)
                {
                    if (objUser.Preferences.MarketingCookies && objUser.Preferences.MetricsCookies)
                    {
                        head.Controls.Add(new LiteralControl(OpenTagHelper.OpenTagVirginActiveUK));
                    }
                }
            }

            //Add Page Title
            System.Text.StringBuilder markupBuilder = new System.Text.StringBuilder();
            markupBuilder.Append(@"<meta name='viewport' content='width=1020'>");
            markupBuilder.Append(@"<link rel='apple-touch-icon' href='/virginactive/images/apple-touch-icon.png'>");
            markupBuilder.Append(@"<link rel='shortcut icon' href='/virginactive/images/favicon.ico'>");
            markupBuilder.Append(@"<link href='/virginactive/css/fonts.css' rel='stylesheet'>");
            markupBuilder.Append(@"<link href='/va_campaigns/css/campaign.css' rel='stylesheet'>");
            head.Controls.Add(new LiteralControl(markupBuilder.ToString()));
        }
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            base.Process(context, output);

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

            var existAttribute = output.Attributes["class"];
            if (existAttribute != null)
            {
                sb.Append(existAttribute.Value.ToString());
                sb.Append(" ");
            }

            if (this.Condition)
            {
                if (!string.IsNullOrWhiteSpace(this.TrueClass))
                {
                    sb.Append(this.TrueClass);
                }
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(this.FalseClass))
                {
                    sb.Append(this.FalseClass);
                }
            }

            if (sb.Length > 0)
            {
                output.Attributes.SetAttribute("class", sb.ToString());
            }
        }
Ejemplo n.º 25
0
 public static int EXECommand(SqlCommand cmd, SqlConnection conn)
 {
     int i = 0;
     try
     {
         cmd.Connection = conn;
         if (conn.State != ConnectionState.Open)
             conn.Open();
         i = cmd.ExecuteNonQuery();
     }
     catch (SqlException _sqlException)
     {
         System.Text.StringBuilder err = new System.Text.StringBuilder();
         err.Append("Error executing [");
         err.Append(cmd.CommandText);
         //err.Append("]\nConnection String [");
         //err.Append(conn.ConnectionString);
         err.Append("]\nError [");
         err.Append(_sqlException.Message);
         err.Append("]");
         Logger.Write(err.ToString());
         return 0;
     }
     catch (InvalidOperationException _sqlException)
     {
         Logger.Write(_sqlException.Message);
     }
     finally
     {
         conn.Close();
     }
     return i;
 }
        private void RecursiveFillTree(DataTable dtParent, int ParentId)
        {
            level++; //on the each call level increment 1
            System.Text.StringBuilder appender = new System.Text.StringBuilder();

            for (int j = 0; j < level; j++)
            {
                appender.Append("&nbsp;&nbsp;&nbsp;&nbsp;");
            }
            if (level > 0)
            {
                appender.Append("|__");
            }

            DataView dv = new DataView(dtParent);
            dv.RowFilter = string.Format("ParentId = {0}", ParentId);

            int i;

            if (dv.Count > 0)
            {
                for (i = 0; i < dv.Count; i++)
                {
                    //DROPDOWNLIST
                    ddlTreeNode_Topics.Items.Add(new ListItem(Server.HtmlDecode(appender.ToString() + dv[i]["Gallery_TopicName"].ToString()), dv[i]["Gallery_TopicId"].ToString()));
                    RecursiveFillTree(dtParent, int.Parse(dv[i]["Gallery_TopicId"].ToString()));
                }
            }

            level--; //on the each function end level will decrement by 1
        }
Ejemplo n.º 27
0
        /// <summary></summary>
        /// <returns></returns>
        public override string ToString()
        {
            /*
function<out Function func> =	(. func = new Function();
                                    Expression exp = null;
                                .)
    ident						(. func.Name = t.val; .)
    '(' expr<out exp>			(. func.Expression = exp; .)
    ')'
.
            */
            System.Text.StringBuilder txt = new System.Text.StringBuilder();
            txt.AppendFormat("{0}(", name);
            if (expression != null)
            {
                bool first = true;
                foreach (Term t in expression.Terms)
                {
                    //if (first) { first = false; } else { txt.Append(" "); }
                    txt.Append(t.ToString());
                }
            }
            txt.Append(")");
            return txt.ToString();
        }
Ejemplo n.º 28
0
		public override string ToString()
		{
			System.Text.StringBuilder sb = new System.Text.StringBuilder();
			sb.Append('<');
			object[] attr = GetType().GetCustomAttributes(typeof(XmlTypeAttribute), false);
			if (attr.Length == 1)
			{
				sb.Append(((XmlTypeAttribute)attr[0]).TypeName);
			}
			else
			{
				sb.Append(GetType().Name);
			}
			foreach (System.Reflection.FieldInfo field in GetType().GetFields())
			{
				if (!field.IsStatic)
				{
					object value = field.GetValue(this);
					if (value != null)
					{
						attr = field.GetCustomAttributes(typeof(XmlAttributeAttribute), false);
						if (attr.Length == 1)
						{
							sb.AppendFormat(" {0}=\"{1}\"", ((XmlAttributeAttribute)attr[0]).AttributeName, value);
						}
					}
				}
			}
			sb.Append(" />");
			return sb.ToString();
		}
		public override System.String HighlightTerm(System.String originalText, TokenGroup tokenGroup)
		{
			if (tokenGroup.GetTotalScore() == 0)
				return originalText;
			float score = tokenGroup.GetTotalScore();
			if (score == 0)
			{
				return originalText;
			}
			
			// try to size sb correctly
			System.Text.StringBuilder sb = new System.Text.StringBuilder(originalText.Length + EXTRA);
			
			sb.Append("<span style=\"");
			if (highlightForeground)
			{
				sb.Append("color: ");
				sb.Append(GetForegroundColorString(score));
				sb.Append("; ");
			}
			if (highlightBackground)
			{
				sb.Append("background: ");
				sb.Append(GetBackgroundColorString(score));
				sb.Append("; ");
			}
			sb.Append("\">");
			sb.Append(originalText);
			sb.Append("</span>");
			return sb.ToString();
		}
        /// <summary> Converts a long to a String suitable for indexing.</summary>
        public static System.String LongToString(long l)
        {
            if (l == System.Int64.MinValue)
            {
                // special case, because long is not symetric around zero
                return MIN_STRING_VALUE;
            }

            System.Text.StringBuilder buf = new System.Text.StringBuilder(STR_SIZE);

            if (l < 0)
            {
                buf.Append(NEGATIVE_PREFIX);
                l = System.Int64.MaxValue + l + 1;
            }
            else
            {
                buf.Append(POSITIVE_PREFIX);
            }
            System.String num = System.Convert.ToString(l, RADIX);

            int padLen = STR_SIZE - num.Length - buf.Length;
            while (padLen-- > 0)
            {
                buf.Append('0');
            }
            buf.Append(num);

            return buf.ToString();
        }
Ejemplo n.º 31
0
        public string Serialize(IntPtr manager)
        {
            var type           = this.GetType();
            var string_builder = new System.Text.StringBuilder();

            string_builder.Append("0|");             // header (version)
            foreach (var f in type.GetFields())
            {
                if (!f.IsPublic)
                {
                    continue;
                }
                if (f.Name == "entity_")
                {
                    continue;
                }
                if (f.Name == "componentId_")
                {
                    continue;
                }
                if (f.Name == "scene_")
                {
                    continue;
                }

                var  val      = f.GetValue(this);
                Type val_type = f.FieldType;
                string_builder.Append(val_type.Name);
                string_builder.Append("|");
                string_builder.Append(f.Name);
                string_builder.Append("|");

                if (f.FieldType == typeof(Entity))
                {
                    if (manager != IntPtr.Zero)
                    {
                        if (val == null)
                        {
                            string_builder.Append(ulong.MaxValue);
                        }
                        else
                        {
                            ulong guid = getEntityGUIDFromID(manager, ((Entity)val).entity_Id_);
                            string_builder.Append(guid.ToString());
                        }
                    }
                    else
                    {
                        if (val == null)
                        {
                            string_builder.Append(-1);
                        }
                        else
                        {
                            string_builder.Append(((Entity)val).entity_Id_);
                        }
                    }
                }
                else if (f.FieldType.BaseType == typeof(Resource))
                {
                    IntPtr native_res = val == null ? IntPtr.Zero : ((Resource)val).__Instance;
                    string path       = Resource.getPath(native_res);
                    string_builder.Append(path);
                }
                else
                {
                    string_builder.Append(val);
                }
                string_builder.Append("|");
            }
            return(string_builder.ToString());
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Sets the value of a name/value pair in the registry key, using the specified registry data type.
        /// <para><b>New in v1.3</b></para>
        /// </summary>
        /// <param name="name">Name of value to store data in.</param>
        /// <param name="value">Data to store.</param>
        /// <param name="valueKind">The registry data type to use when storing the data.</param>
        /// <exception cref="System.ArgumentException">The length of the specified value is longer than the maximum length allowed (255 characters).</exception>
        /// <exception cref="System.ArgumentNullException">value is null.</exception>
        /// <exception cref="System.ObjectDisposedException">The RegistryKey being set is closed (closed keys cannot be accessed).</exception>
        /// <exception cref="System.UnauthorizedAccessException">The RegistryKey being set is readonly, and cannot be written to (for example, it is a root-level node, or the key has not been opened with write-access).</exception>
        public void SetValue(string name, object value, RegistryValueKind valueKind)
        {
            if (m_writable)
            {
                if (CheckHKey())
                {
                    byte[] data;

                    switch (valueKind)
                    {
                    case RegistryValueKind.String:
                        data = System.Text.Encoding.Unicode.GetBytes((string)value + '\0');
                        break;

                    case RegistryValueKind.MultiString:
                        System.Text.StringBuilder sb = new System.Text.StringBuilder();

                        foreach (string str in (string[])value)
                        {
                            sb.Append(str + '\0');
                        }
                        sb.Append('\0');                                 // terminated by two null characters
                        data = System.Text.Encoding.Unicode.GetBytes(sb.ToString());
                        break;

                    case RegistryValueKind.Binary:
                        data = (byte[])value;
                        break;

                    case RegistryValueKind.DWord:
                        if (value is UInt32)
                        {
                            data = BitConverter.GetBytes((uint)value);
                        }
                        else
                        {
                            data = BitConverter.GetBytes(Convert.ToInt32(value));
                        }
                        break;

                    default:
                        SetValue(name, value);
                        return;
                    }

                    int size   = data.Length;
                    int result = RegSetValueEx(m_handle, name, 0, valueKind, data, size);


                    if (result != 0)
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error(), "Error writing to the RegistryKey");
                    }
                }
                else
                {
                    throw new ObjectDisposedException("The RegistryKey being manipulated is closed (closed keys cannot be accessed).");
                }
            }
            else
            {
                throw new UnauthorizedAccessException("Cannot set value on RegistryKey which was opened as ReadOnly");
            }
        }
Ejemplo n.º 33
0
        /// <summary>
        /// Sets the specified value.
        /// </summary>
        /// <param name="name">Name of value to store data in.</param>
        /// <param name="value">Data to store.</param>
        /// <exception cref="System.ArgumentException">The length of the specified value is longer than the maximum length allowed (255 characters).</exception>
        /// <exception cref="System.ArgumentNullException">value is null.</exception>
        /// <exception cref="System.ObjectDisposedException">The RegistryKey being set is closed (closed keys cannot be accessed).</exception>
        /// <exception cref="System.UnauthorizedAccessException">The RegistryKey being set is readonly, and cannot be written to (for example, it is a root-level node, or the key has not been opened with write-access).</exception>
        public void SetValue(string name, object value)
        {
            if (m_writable)
            {
                if (CheckHKey())
                {
                    RegistryValueKind type = 0;
                    byte[]            data;

                    switch (value.GetType().ToString())
                    {
                    case "System.String":
                        type = RegistryValueKind.String;
                        data = System.Text.Encoding.Unicode.GetBytes((string)value + '\0');
                        break;

                    case "System.String[]":
                        System.Text.StringBuilder sb = new System.Text.StringBuilder();
                        foreach (string str in (string[])value)
                        {
                            sb.Append(str + '\0');
                        }
                        sb.Append('\0');                                 // terminated by two null characters
                        type = RegistryValueKind.MultiString;
                        data = System.Text.Encoding.Unicode.GetBytes(sb.ToString());
                        break;

                    case "System.Byte[]":
                        type = RegistryValueKind.Binary;
                        data = (byte[])value;
                        break;

                    case "System.Int32":
                        type = RegistryValueKind.DWord;
                        data = BitConverter.GetBytes((int)value);
                        break;

                    case "System.UInt32":
                        type = RegistryValueKind.DWord;
                        data = BitConverter.GetBytes((uint)value);
                        break;

                    default:
                        throw new ArgumentException("value is not a supported type");
                    }

                    int size   = data.Length;
                    int result = RegSetValueEx(m_handle, name, 0, type, data, size);


                    if (result != 0)
                    {
                        throw new ExternalException("Error writing to the RegistryKey");
                    }
                }
                else
                {
                    throw new ObjectDisposedException("The RegistryKey being manipulated is closed (closed keys cannot be accessed).");
                }
            }
            else
            {
                throw new UnauthorizedAccessException("Cannot set value on RegistryKey which was opened as ReadOnly");
            }
        }
Ejemplo n.º 34
0
        private string GetNodeString(SiteMapNode node)
        {
            System.Text.StringBuilder SB = new System.Text.StringBuilder();

            if (node.HasChildNodes)
            {
                SB.Append("<a ");
                //SB.Append("href='" + node.Url + "#" + node.Title.ToLower() + "'");
                SB.Append("id='" + node["id"] + "' ");
                if (!(string.IsNullOrWhiteSpace(node["onclick"])))
                {
                    SB.Append("onclick='" + node["onclick"] + "' ");
                }
                if (!(string.IsNullOrWhiteSpace(node["class"])))
                {
                    SB.Append("class='" + node["class"] + "' ");
                }
                SB.Append("data-toggle = 'collapse'");
                SB.Append("style = 'height:auto'");
                SB.Append("data-parent='#MainMenu' ");
            }
            else
            {
                if ((node.Title.Contains("Menu-Close")))
                {
                    SB.Append("<a href='#' ");
                    SB.Append("id='menu-toggle' ");
                    SB.Append("onclick='doTheToggle()' ");
                }
                else
                {
                    SB.Append("<a href='" + node.Url + "' ");
                }
                SB.Append("class='list-group-item' ");
                SB.Append("data-parent='#MainMenu' ");
            }

            SB.Append("id='" + node["id"] + "' > ");

            SB.Append("<em>" + node.Title + "</em>");

            if ((node.Title.Contains("Menu")))
            {
                SB.Append("<span id ='main_icon' class='" + node["glyphicon"] + "' >");
            }
            else
            {
                SB.Append("<span class='" + node["glyphicon"] + "' >");
            }


            SB.Append("</span>");

            if (node.HasChildNodes)
            {
                SB.Append("<i class='fa fa-caret-down'></i>");
                SB.Append("</a>");
                SB.Append("<div class='submenu panel-collapse collapse' id='" + node.Title.ToLower() + "'>");
            }
            else
            {
                SB.Append("</a>");
            }



            if (node.HasChildNodes)
            {
                foreach (SiteMapNode SubNode in node.ChildNodes)
                {
                    if (SubNode.Roles.Count == 0)
                    {
                        SB.Append(GetNodeStringChild(SubNode));
                    }
                    else if (Singular.Security.Security.HasAccess(SubNode.Roles[0].ToString()))
                    {
                        SB.Append(GetNodeStringChild(SubNode));
                    }
                }
            }
            if (node.HasChildNodes)
            {
                SB.Append("</div>");
            }

            return(SB.ToString());
        }
Ejemplo n.º 35
0
        private string GetNodeStringChild(SiteMapNode node)
        {
            System.Text.StringBuilder SB = new System.Text.StringBuilder();

            if (node.HasChildNodes)
            {
                SB.Append("<a");

                SB.Append(" onclick='");
                SB.Append(" if (!this.parentElement.children) { return }");
                SB.Append(" if (this.parentElement.children.length <= 1) { return }");
                SB.Append(" if (this.parentElement.children[1].clientHeight > 0) {");
                SB.Append("  this.parentElement.children[1].style.display = 'none';");
                SB.Append(" } else {");
                SB.Append("  this.parentElement.children[1].style.display = 'block';");
                SB.Append(" };' ");
                SB.Append(" >");
            }
            else
            {
                SB.Append("<a  href='" + node.Url + "' ");
                SB.Append("id='" + node["id"] + "' ");

                if (!(string.IsNullOrWhiteSpace(node["class"])))
                {
                    SB.Append("class='" + node["class"] + "' ");
                }

                if (!(string.IsNullOrWhiteSpace(node["onclick"])))
                {
                    SB.Append("onclick='" + node["onclick"] + "' ");
                }

                if (!(string.IsNullOrWhiteSpace(node["data-toggle"])))
                {
                    SB.Append("data-toggle='" + node["data-toggle"] + "' ");
                }

                if (!(string.IsNullOrWhiteSpace(node["parent"]) | node["parent"] == "Client"))
                {
                    SB.Append("data-parent='" + node.Url + "' ");
                }

                SB.Append(">");
            }

            SB.Append("<em>");
            SB.Append(node.Title);
            SB.Append("</em>");

            if (node["glyphicon"] != null)
            {
                SB.Append("<span class='" + node["glyphicon"] + "' ></span>");
            }
            else
            {
                if (node["font-awesome"] != null)
                {
                    SB.Append("<span class='" + node["font-awesome"] + "' ></span>");
                }
            }

            if (node.HasChildNodes)
            {
                SB.Append("<span class='' ></span>");
            }

            SB.Append("</a>");

            if (node.HasChildNodes)
            {
                foreach (SiteMapNode SubNode in node.ChildNodes)
                {
                    if (SubNode.Roles.Count == 0)
                    {
                        SB.Append(GetNodeStringChild(SubNode));
                    }
                    else if (Singular.Security.Security.HasAccess(SubNode.Roles[0].ToString()))
                    {
                        SB.Append(GetNodeStringChild(SubNode));
                    }
                }
            }

            return(SB.ToString());
        }
Ejemplo n.º 36
0
        /** Convert
         *
         *      return : 使用文字数。
         *
         */
        public static int Convert(string a_string, int a_offset, System.Text.StringBuilder a_stringbuilder)
        {
            switch (a_string[a_offset])
            {
            case '\\':
            {
                //バックスラッシュ。
                a_stringbuilder.Append(a_string[a_offset]);
                return(1);
            } break;

            case '\"':
            {
                //ダブルクォーテーション。
                a_stringbuilder.Append(a_string[a_offset]);
                return(1);
            } break;

            case 'n':
            {
                //キャリッジリターン。
                a_stringbuilder.Append('\n');
                return(1);
            } break;

            case '0':
            {
                //ヌル。
                a_stringbuilder.Append('\0');
                return(1);
            } break;

            case '\'':
            {
                //シングルクォーテーション。
                a_stringbuilder.Append(a_string[a_offset]);
                return(1);
            } break;

            case '/':
            {
                //スラッシュ。
                a_stringbuilder.Append(a_string[a_offset]);
                return(1);
            } break;

            case 'b':
            {
                //バックスペース。
                a_stringbuilder.Append('\b');
                return(1);
            } break;

            case 'f':
            {
                //ニューページ。
                a_stringbuilder.Append('\f');
                return(1);
            } break;

            case 'r':
            {
                //ラインフィード。
                a_stringbuilder.Append('\r');
                return(1);
            } break;

            case 't':
            {
                //タブ。
                a_stringbuilder.Append('\t');
                return(1);
            } break;

            case 'u':
            {
                //UTF16。
                if ((a_offset + 4) < a_string.Length)
                {
                    char t_char = StringConvert.Utf16CodeStringToChar.Convert_NoCheck(a_string, a_offset + 1);
                    a_stringbuilder.Append(t_char);
                    return(5);
                }
                else
                {
                    //失敗。
                    return(0);
                }
            } break;
            }

            //失敗。
            return(0);
        }
Ejemplo n.º 37
0
        private void Fill(string Project)
        {
            abcd.HRef = "?k=abcd&project=" + Project;
            efgh.HRef = "?k=efgh&project=" + Project;
            ijkl.HRef = "?k=ijkl&project=" + Project;
            mnop.HRef = "?k=mnop&project=" + Project;
            qrst.HRef = "?k=qrst&project=" + Project;
            uvwx.HRef = "?k=uvwx&project=" + Project;
            yz09.HRef = "?k=yz09&project=" + Project;

            string aq = "";

            switch (Request.QueryString["k"])
            {
            case "abcd":
                aq = " AND LEFT(Nama,1) IN ('a','b','c','d')";
                break;

            case "efgh":
                aq = " AND LEFT(Nama,1) IN ('e','f','g','h')";
                break;

            case "ijkl":
                aq = " AND LEFT(Nama,1) IN ('i','j','k','l')";
                break;

            case "mnop":
                aq = " AND LEFT(Nama,1) IN ('m','n','o','p')";
                break;

            case "qrst":
                aq = " AND LEFT(Nama,1) IN ('q','r','s','t')";
                break;

            case "uvwx":
                aq = " AND LEFT(Nama,1) IN ('u','v','w','x')";
                break;

            case "yz09":
                aq = " AND LEFT(Nama,1) IN ('y','z','0','1','2','3','4','5','6','7','8','9')";
                break;
            }

            string strSql = "SELECT "
                            + " NoAgent"
                            + ",Nama"
                            + ",LEFT(Nama,1) AS Alfa "
                            + " FROM MS_AGENT "
                            + " WHERE Status = 'A' " + aq
                            + " AND Project = '" + Project + "'"
                            + " ORDER BY Nama, NoAgent";

            DataTable rs = Db.Rs(strSql);

            string p = "";

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

            Rpt.NoData(x, rs, "Tidak ada agent dengan nama yang berawalan : " + Request.QueryString["k"] + ".");

            for (int i = 0; i < rs.Rows.Count; i++)
            {
                if (!Response.IsClientConnected)
                {
                    break;
                }

                string alfa = rs.Rows[i]["Alfa"].ToString().ToUpper();
                if (p != alfa)
                {
                    p = alfa;
                    x.Append("<br><h1>" + alfa + "</h1>");
                }

                //x.Append("<p><a show-modal='#ModalPopUp' modal-title='Edit Agent' modal-url='AgentEdit.aspx?NoAgent=" + rs.Rows[i]["NoAgent"] + "'>"
                x.Append("<p><a href=\"javascript:call('" + rs.Rows[i]["NoAgent"] + "')\">"
                         + rs.Rows[i]["Nama"]
                         + " (" + rs.Rows[i]["NoAgent"].ToString().PadLeft(5, '0') + ")"
                         + "</a></p>");
            }

            list.Text = x.ToString();
        }
Ejemplo n.º 38
0
        public ManifestToken GetNextToken()
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            bool   isEscape = false, isFinished = false, stringBlock = false;
            string escapecode = null;

            System.Text.StringBuilder sbEscape = null;
            ManifestToken             curToken = null;

            while (idx < content.Length)
            {
                if (curToken != null && isFinished)
                {
                    curToken.Text = sb.ToString();
                    lastToken2    = lastToken;
                    lastToken     = curToken;
                    return(curToken);
                }
                char c = content[idx];

                if (curToken == null)
                {
                    if (c == ' ')
                    {
                        curToken = new ManifestTabStop();
                    }
                    else if (c == '\n')
                    {
                        curToken              = new ManifestEOL();
                        curToken.LineNumber   = line;
                        curToken.ColumnNumber = column;
                        curToken.Text         = "";
                        lastToken2            = lastToken;
                        lastToken             = curToken;
                        line++;
                        idx++;
                        column = 1;
                        return(curToken);
                    }
                    else if (c == '\r')
                    {
                        idx++;
                        column++;
                        continue;
                    }
                    else if (c == '{')
                    {
                        curToken = new ManifestPropertyBegin();
                    }
                    else if (c == '}')
                    {
                        curToken = new ManifestPropertyEnd();
                    }
                    else if (c == ',')
                    {
                        curToken = new ManifestComma();
                    }
                    else if (c == ':')
                    {
                        curToken = new ManifestNodeToken();
                    }
                    else if (c == '-')
                    {
                        if (lastToken == null || lastToken.Type == ManifestTokenTypes.EOL)
                        {
                            curToken = new ManifestValueBegin();
                        }
                        else
                        {
                            curToken = new ManifestStringToken();
                        }
                    }
                    else
                    {
                        curToken = new ManifestStringToken();
                    }

                    curToken.LineNumber   = line;
                    curToken.ColumnNumber = column;
                }

                switch (curToken.Type)
                {
                case ManifestTokenTypes.EOL:
                case ManifestTokenTypes.PropertyBegin:
                case ManifestTokenTypes.PropertyEnd:
                case ManifestTokenTypes.ValueBegin:
                case ManifestTokenTypes.Comma:
                case ManifestTokenTypes.EOF:
                case ManifestTokenTypes.Node:
                    isFinished = true;
                    break;

                case ManifestTokenTypes.Tabstop:
                {
                    if (c != ' ')
                    {
                        isFinished = true;
                        ((ManifestTabStop)curToken).Count = sb.Length;
                        continue;
                    }
                }
                break;

                case ManifestTokenTypes.String:
                {
                    if (IsTerminalChar(c) && !stringBlock)
                    {
                        isFinished = true;
                        if (isEscape)
                        {
                            sb.Append(FinishEscape(escapecode, sbEscape.ToString()));
                            isEscape = false;
                        }
                        continue;
                    }
                    if (isEscape)
                    {
                        if (escapecode == null)
                        {
                            escapecode = c.ToString();
                        }
                        else
                        {
                            sbEscape.Append(c);
                            if (sbEscape.Length >= GetEscapeLength(escapecode))
                            {
                                sb.Append(FinishEscape(escapecode, sbEscape.ToString()));
                                isEscape = false;
                            }
                        }
                        idx++;
                        column++;
                        continue;
                    }
                    else
                    {
                        if (c == '\\')
                        {
                            isEscape   = true;
                            sbEscape   = new System.Text.StringBuilder();
                            escapecode = null;
                            idx++;
                            column++;
                            continue;
                        }
                        if (c == '\"')
                        {
                            stringBlock = !stringBlock;
                            idx++;
                            column++;
                            continue;
                        }
                    }
                }
                break;
                }
                idx++;
                column++;

                sb.Append(c);
            }
            if (idx >= content.Length)
            {
                lastToken2             = lastToken;
                lastToken              = new ManifestEOF();
                lastToken.LineNumber   = line;
                lastToken.ColumnNumber = column;
                isFinished             = true;
                return(LastToken);
            }

            return(null);
        }
Ejemplo n.º 39
0
        private void EmitPendingBuffers(bool doAll, bool mustWait)
        {
            // When combining parallel compression with a ZipSegmentedStream, it's
            // possible for the ZSS to throw from within this method.  In that
            // case, Close/Dispose will be called on this stream, if this stream
            // is employed within a using or try/finally pair as required. But
            // this stream is unaware of the pending exception, so the Close()
            // method invokes this method AGAIN. This can lead to a deadlock.
            // Therefore, failfast if re-entering.

            if (emitting) return;
            emitting = true;

            if (doAll || mustWait)
                this.newlyCompressedBlob.WaitOne();

            do
            {
                int firstSkip = -1;
                int millisecondsToWait = doAll ? 200 : (mustWait ? -1 : 0);
                int nextToWrite = -1;

                do
                {
                    if (Monitor.TryEnter(this.toWrite, millisecondsToWait))
                    {
                        nextToWrite = -1;
                        try
                        {
                            if (this.toWrite.Count > 0)
                                nextToWrite = this.toWrite.Dequeue();
                        }
                        finally
                        {
                            Monitor.Exit(this.toWrite);
                        }

                        if (nextToWrite >= 0)
                        {
                            WorkItem workitem = this.pool[nextToWrite];
                            if (workitem.ordinal != this.lastWritten + 1)
                            {
                                // out of order. requeue and try again.
                                lock(this.toWrite)
                                {
                                    this.toWrite.Enqueue(nextToWrite);
                                }

                                if (firstSkip == nextToWrite)
                                {
                                    // We went around the list once.
                                    // None of the items in the list is the one we want.
                                    // Now wait for a compressor to signal again.
                                    this.newlyCompressedBlob.WaitOne();
                                    firstSkip = -1;
                                }
                                else if (firstSkip == -1)
                                    firstSkip = nextToWrite;

                                continue;
                            }

                            firstSkip = -1;

                            TraceOutput(TraceBits.Write,
                                        "Writing block {0}", workitem.ordinal);

                            // write the data to the output
                            var bw2 = workitem.bw;
                            bw2.Flush(); // not bw2.FinishAndPad()!
                            var ms = workitem.ms;
                            ms.Seek(0,SeekOrigin.Begin);

                            // cannot dump bytes!!
                            // ms.WriteTo(this.output);
                            //
                            // must do byte shredding:
                            int n;
                            int y = -1;
                            long totOut = 0;
                            var buffer = new byte[1024];
                            while ((n = ms.Read(buffer,0,buffer.Length)) > 0)
                            {
#if Trace
                                if (y == -1) // diagnostics only
                                {
                                    var sb1 = new System.Text.StringBuilder();
                                    sb1.Append("first 16 whole bytes in block: ");
                                    for (int z=0; z < 16; z++)
                                        sb1.Append(String.Format(" {0:X2}", buffer[z]));
                                    TraceOutput(TraceBits.Write, sb1.ToString());
                                }
#endif
                                y = n;
                                for (int k=0; k < n; k++)
                                {
                                    this.bw.WriteByte(buffer[k]);
                                }
                                totOut += n;
                            }
#if Trace
                            TraceOutput(TraceBits.Write,"out block length (bytes): {0} (0x{0:X})", totOut);
                            var sb = new System.Text.StringBuilder();
                            sb.Append("final 16 whole bytes in block: ");
                            for (int z=0; z < 16; z++)
                                sb.Append(String.Format(" {0:X2}", buffer[y-1-12+z]));
                            TraceOutput(TraceBits.Write, sb.ToString());
#endif

                            // and now any remaining bits
                            TraceOutput(TraceBits.Write,
                                        " remaining bits: {0} 0x{1:X}",
                                        bw2.NumRemainingBits,
                                        bw2.RemainingBits);
                            if (bw2.NumRemainingBits > 0)
                            {
                                this.bw.WriteBits(bw2.NumRemainingBits, bw2.RemainingBits);
                            }

                            TraceOutput(TraceBits.Crc," combined CRC (before): {0:X8}",
                                        this.combinedCRC);
                            this.combinedCRC = (this.combinedCRC << 1) | (this.combinedCRC >> 31);
                            this.combinedCRC ^= (uint) workitem.Compressor.Crc32;

                            TraceOutput(TraceBits.Crc,
                                        " block    CRC         : {0:X8}",
                                        workitem.Compressor.Crc32);
                            TraceOutput(TraceBits.Crc,
                                        " combined CRC (after) : {0:X8}",
                                        this.combinedCRC);
                            TraceOutput(TraceBits.Write,
                                        "total written out: {0} (0x{0:X})",
                                        this.bw.TotalBytesWrittenOut);
                            TraceOutput(TraceBits.Write | TraceBits.Crc, "");

                            this.totalBytesWrittenOut += totOut;

                            bw2.Reset();
                            this.lastWritten = workitem.ordinal;
                            workitem.ordinal = -1;
                            this.toFill.Enqueue(workitem.index);

                            // don't wait next time through
                            if (millisecondsToWait == -1) millisecondsToWait = 0;
                        }
                    }
                    else
                        nextToWrite = -1;

                } while (nextToWrite >= 0);

            } while (doAll && (this.lastWritten != this.latestCompressed));

            if (doAll)
            {
                TraceOutput(TraceBits.Crc,
                            " combined CRC (final) : {0:X8}", this.combinedCRC);
            }

            emitting = false;
        }
        /// <summary>
        /// Read the data from the database.
        /// </summary>
        /// <param name="transaction">
        /// The current transaction to the database.
        /// </param>
        /// <param name="partition">
        /// The database partition (schema) where the requested resource is stored.
        /// </param>
        /// <param name="ids">
        /// Ids to retrieve from the database.
        /// </param>
        /// <param name="isCachedDtoReadEnabledAndInstant">
        /// The value indicating whether to get cached last state of Dto from revision history.
        /// </param>
        /// <returns>
        /// List of instances of <see cref="CDP4Common.DTO.ParameterizedCategoryRule"/>.
        /// </returns>
        public virtual IEnumerable <CDP4Common.DTO.ParameterizedCategoryRule> Read(NpgsqlTransaction transaction, string partition, IEnumerable <Guid> ids = null, bool isCachedDtoReadEnabledAndInstant = false)
        {
            using (var command = new NpgsqlCommand())
            {
                var sqlBuilder = new System.Text.StringBuilder();

                if (isCachedDtoReadEnabledAndInstant)
                {
                    sqlBuilder.AppendFormat("SELECT \"Jsonb\" FROM \"{0}\".\"ParameterizedCategoryRule_Cache\"", partition);

                    if (ids != null && ids.Any())
                    {
                        sqlBuilder.Append(" WHERE \"Iid\" = ANY(:ids)");
                        command.Parameters.Add("ids", NpgsqlDbType.Array | NpgsqlDbType.Uuid).Value = ids;
                    }

                    sqlBuilder.Append(";");

                    command.Connection  = transaction.Connection;
                    command.Transaction = transaction;
                    command.CommandText = sqlBuilder.ToString();

                    // log the sql command
                    this.LogCommand(command);

                    using (var reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            var thing = this.MapJsonbToDto(reader);
                            if (thing != null)
                            {
                                yield return(thing as ParameterizedCategoryRule);
                            }
                        }
                    }
                }
                else
                {
                    sqlBuilder.AppendFormat("SELECT * FROM \"{0}\".\"ParameterizedCategoryRule_View\"", partition);

                    if (ids != null && ids.Any())
                    {
                        sqlBuilder.Append(" WHERE \"Iid\" = ANY(:ids)");
                        command.Parameters.Add("ids", NpgsqlDbType.Array | NpgsqlDbType.Uuid).Value = ids;
                    }

                    sqlBuilder.Append(";");

                    command.Connection  = transaction.Connection;
                    command.Transaction = transaction;
                    command.CommandText = sqlBuilder.ToString();

                    // log the sql command
                    this.LogCommand(command);

                    using (var reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            yield return(this.MapToDto(reader));
                        }
                    }
                }
            }
        }
Ejemplo n.º 41
0
        /// <summary>Returns a debug string for this path.</summary>
        internal override string DebugString(PathLog logMode)
        {
            if (logMode == PathLog.None || (!error && logMode == PathLog.OnlyErrors))
            {
                return("");
            }

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

            DebugStringPrefix(logMode, text);

            if (!error && logMode == PathLog.Heavy)
            {
                if (hasEndPoint && endNode != null)
                {
                    PathNode nodeR = pathHandler.GetPathNode(endNode);
                    text.Append("\nEnd Node\n	G: ");
                    text.Append(nodeR.G);
                    text.Append("\n	H: ");
                    text.Append(nodeR.H);
                    text.Append("\n	F: ");
                    text.Append(nodeR.F);
                    text.Append("\n	Point: ");
                    text.Append(((Vector3)endPoint).ToString());
                    text.Append("\n	Graph: ");
                    text.Append(endNode.GraphIndex);
                }

                text.Append("\nStart Node");
                text.Append("\n	Point: ");
                text.Append(((Vector3)startPoint).ToString());
                text.Append("\n	Graph: ");
                if (startNode != null)
                {
                    text.Append(startNode.GraphIndex);
                }
                else
                {
                    text.Append("< null startNode >");
                }
            }

            DebugStringSuffix(logMode, text);

            return(text.ToString());
        }
        public virtual string ToString(object start, object stop)
        {
            Console.Out.WriteLine("toString");
            if (start == null || stop == null)
            {
                return(null);
            }
            if (p == -1)
            {
                throw new InvalidOperationException("Buffer is not yet filled.");
            }
            //Console.Out.WriteLine( "stop: " + stop );
            if (start is CommonTree)
            {
                Console.Out.Write("toString: " + ((CommonTree)start).Token + ", ");
            }
            else
            {
                Console.Out.WriteLine(start);
            }
            if (stop is CommonTree)
            {
                Console.Out.WriteLine(((CommonTree)stop).Token);
            }
            else
            {
                Console.Out.WriteLine(stop);
            }
            // if we have the token stream, use that to dump text in order
            if (tokens != null)
            {
                int beginTokenIndex = adaptor.GetTokenStartIndex(start);
                int endTokenIndex   = adaptor.GetTokenStopIndex(stop);
                // if it's a tree, use start/stop index from start node
                // else use token range from start/stop nodes
                if (adaptor.GetType(stop) == TokenTypes.Up)
                {
                    endTokenIndex = adaptor.GetTokenStopIndex(start);
                }
                else if (adaptor.GetType(stop) == TokenTypes.EndOfFile)
                {
                    endTokenIndex = Count - 2; // don't use EOF
                }
                return(tokens.ToString(beginTokenIndex, endTokenIndex));
            }
            // walk nodes looking for start
            object t = null;
            int    i = 0;

            for (; i < nodes.Count; i++)
            {
                t = nodes[i];
                if (t == start)
                {
                    break;
                }
            }
            // now walk until we see stop, filling string buffer with text
            StringBuilder buf = new StringBuilder();

            t = nodes[i];
            while (t != stop)
            {
                string text = adaptor.GetText(t);
                if (text == null)
                {
                    text = " " + adaptor.GetType(t).ToString();
                }
                buf.Append(text);
                i++;
                t = nodes[i];
            }
            // include stop node too
            string text2 = adaptor.GetText(stop);

            if (text2 == null)
            {
                text2 = " " + adaptor.GetType(stop).ToString();
            }
            buf.Append(text2);
            return(buf.ToString());
        }
Ejemplo n.º 43
0
        public System.Text.StringBuilder Csv(
            Context context,
            SiteSettings ss,
            System.Text.StringBuilder csv,
            IEnumerable <ExportColumn> exportColumns)
        {
            var idColumn = Rds.IdColumn(ss.ReferenceType);

            DataRows.ForEach(dataRow =>
            {
                var dataId        = dataRow.Long(idColumn).ToString();
                var data          = new List <string>();
                var tenants       = new Dictionary <string, TenantModel>();
                var depts         = new Dictionary <string, DeptModel>();
                var groups        = new Dictionary <string, GroupModel>();
                var registrations = new Dictionary <string, RegistrationModel>();
                var users         = new Dictionary <string, UserModel>();
                var sites         = new Dictionary <string, SiteModel>();
                var issues        = new Dictionary <string, IssueModel>();
                var results       = new Dictionary <string, ResultModel>();
                var wikis         = new Dictionary <string, WikiModel>();
                exportColumns.ForEach(exportColumn =>
                {
                    var column = exportColumn.Column;
                    var key    = column.TableName();
                    switch (column.SiteSettings?.ReferenceType)
                    {
                    case "Users":
                        if (!users.ContainsKey(key))
                        {
                            users.Add(key, new UserModel(
                                          context: context,
                                          ss: column.SiteSettings,
                                          dataRow: dataRow,
                                          tableAlias: column.TableAlias));
                        }
                        data.Add(users.Get(key).CsvData(
                                     context: context,
                                     ss: column.SiteSettings,
                                     column: column,
                                     exportColumn: exportColumn,
                                     mine: users.Get(key).Mine(context: context)));
                        break;

                    case "Issues":
                        if (!issues.ContainsKey(key))
                        {
                            issues.Add(key, new IssueModel(
                                           context: context,
                                           ss: column.SiteSettings,
                                           dataRow: dataRow,
                                           tableAlias: column.TableAlias));
                        }
                        data.Add(issues.Get(key).CsvData(
                                     context: context,
                                     ss: column.SiteSettings,
                                     column: column,
                                     exportColumn: exportColumn,
                                     mine: issues.Get(key).Mine(context: context)));
                        break;

                    case "Results":
                        if (!results.ContainsKey(key))
                        {
                            results.Add(key, new ResultModel(
                                            context: context,
                                            ss: column.SiteSettings,
                                            dataRow: dataRow,
                                            tableAlias: column.TableAlias));
                        }
                        data.Add(results.Get(key).CsvData(
                                     context: context,
                                     ss: column.SiteSettings,
                                     column: column,
                                     exportColumn: exportColumn,
                                     mine: results.Get(key).Mine(context: context)));
                        break;
                    }
                });
                csv.Append(data.Join(","), "\n");
            });
            return(csv);
        }
Ejemplo n.º 44
0
        //public static string Parse(this System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<string, Microsoft.Extensions.Primitives.StringValues>> values)
        //{
        //    if (values == null)
        //    {
        //        throw new System.ArgumentNullException();
        //    }

        //    var result = new System.Text.StringBuilder();

        //    foreach(var keyValuePair in values)
        //    {
        //        result.AppendWithDelimiter($"{keyValuePair.Key}={keyValuePair.Value}", "&");
        //    }

        //    return result.ToString();
        //}

        /// <summary>
        /// Creates a string from an IEnumerable by converting them each to a string and then concatenating them all together.
        /// </summary>
        /// <param name="collection">
        /// The collection.
        /// </param>
        /// <param name="delimiter">
        /// A delimiter to go between each of the strings.
        /// </param>
        /// <param name="fieldName">
        /// The name of the field of each source object that contains the data for the array
        /// </param>
        /// <param name="propertyName">
        /// The name of the property of each source object that contains the data for the array
        /// </param>
        /// <param name="encaseInQuotes">
        /// Indicates whether to encase each array item in quotes
        /// </param>
        /// <returns>
        /// A string representation of all the objects.
        /// </returns>
        public static string ToString(this System.Collections.IEnumerable collection, string delimiter, string fieldName = null, string propertyName = null, bool encaseInQuotes = false)
        {
            if (!string.IsNullOrWhiteSpace(fieldName) && !string.IsNullOrWhiteSpace(propertyName))
            {
                throw new System.ArgumentException("Both parameters \"fieldName\" and \"propertyName\" must not be set.");
            }

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

            if (collection != null)
            {
                foreach (var item in collection.Cast <object>().Where(item => item != null))
                {
                    var stringToWrite = item.ToString();

                    if (!string.IsNullOrWhiteSpace(fieldName))
                    {
                        var fieldInfo = item.GetType().GetField(fieldName);
                        if (fieldInfo == null)
                        {
                            continue;
                        }

                        var fieldValue = fieldInfo.GetValue(item);

                        if (fieldValue != null)
                        {
                            stringToWrite = fieldValue.ToString();
                        }
                    }
                    else if (!string.IsNullOrWhiteSpace(propertyName))
                    {
                        var propertyInfo = item.GetType().GetProperty(propertyName);
                        if (propertyInfo == null)
                        {
                            continue;
                        }

                        var propertyValue = propertyInfo.GetValue(item);

                        if (propertyValue != null)
                        {
                            stringToWrite = propertyValue.ToString();
                        }
                    }

                    if (builder.Length > 0)
                    {
                        builder.Append(delimiter);
                    }

                    if (encaseInQuotes)
                    {
                        builder.Append("\"");
                    }

                    builder.Append(stringToWrite);

                    if (encaseInQuotes)
                    {
                        builder.Append("\"");
                    }
                }
            }

            return(builder.ToString());
        }
Ejemplo n.º 45
0
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <exception cref="SwaggerException">A server side error occurred.</exception>
        public async System.Threading.Tasks.Task <System.Collections.ObjectModel.ObservableCollection <Category> > ListAsync(System.Threading.CancellationToken cancellationToken)
        {
            var urlBuilder_ = new System.Text.StringBuilder();

            urlBuilder_.Append("category/all");

            var client_ = _httpClient;

            try
            {
                using (var request_ = new System.Net.Http.HttpRequestMessage())
                {
                    request_.Method = new System.Net.Http.HttpMethod("GET");
                    request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json"));

                    PrepareRequest(client_, request_, urlBuilder_);
                    var url_ = urlBuilder_.ToString();
                    request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
                    PrepareRequest(client_, request_, url_);

                    var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);

                    try
                    {
                        var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value);
                        if (response_.Content != null && response_.Content.Headers != null)
                        {
                            foreach (var item_ in response_.Content.Headers)
                            {
                                headers_[item_.Key] = item_.Value;
                            }
                        }

                        ProcessResponse(client_, response_);

                        var status_ = ((int)response_.StatusCode).ToString();
                        if (status_ == "200")
                        {
                            var objectResponse_ = await ReadObjectResponseAsync <System.Collections.ObjectModel.ObservableCollection <Category> >(response_, headers_).ConfigureAwait(false);

                            return(objectResponse_.Object);
                        }
                        else
                        if (status_ != "200" && status_ != "204")
                        {
                            var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null);
                        }

                        return(default(System.Collections.ObjectModel.ObservableCollection <Category>));
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
            }
        }
Ejemplo n.º 46
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string roleID = Request.QueryString["roleid"];
            Guid   roleGuid;

            if (!roleID.IsGuid(out roleGuid))
            {
                Response.Write("[]");
                Response.End();
            }

            RoadFlow.Platform.RoleApp BRoleApp = new RoadFlow.Platform.RoleApp();
            var appDt = BRoleApp.GetAllDataTableByRoleID(roleGuid);

            if (appDt.Rows.Count == 0)
            {
                Response.Write("[]");
                Response.End();
            }

            var root = appDt.Select("ParentID='" + Guid.Empty.ToString() + "'");

            if (root.Length == 0)
            {
                Response.Write("[]");
                Response.End();
            }

            var apps = appDt.Select("ParentID='" + root[0]["ID"].ToString() + "'");

            System.Text.StringBuilder json   = new System.Text.StringBuilder("[", 1000);
            System.Data.DataRow       rootDr = root[0];
            json.Append("{");
            json.AppendFormat("\"id\":\"{0}\",", rootDr["ID"]);
            json.AppendFormat("\"title\":\"{0}\",", rootDr["Title"]);
            json.AppendFormat("\"ico\":\"{0}\",", rootDr["Ico"]);
            json.AppendFormat("\"link\":\"{0}\",", rootDr["Address"]);
            json.AppendFormat("\"type\":\"{0}\",", "0");
            json.AppendFormat("\"model\":\"{0}\",", rootDr["OpenMode"]);
            json.AppendFormat("\"width\":\"{0}\",", rootDr["Width"]);
            json.AppendFormat("\"height\":\"{0}\",", rootDr["Height"]);
            json.AppendFormat("\"hasChilds\":\"{0}\",", apps.Length > 0 ? "1" : "0");
            json.AppendFormat("\"childs\":[");

            for (int i = 0; i < apps.Length; i++)
            {
                System.Data.DataRow dr = apps[i];
                var childs             = appDt.Select("ParentID='" + dr["ID"].ToString() + "'");
                json.Append("{");
                json.AppendFormat("\"id\":\"{0}\",", dr["ID"]);
                json.AppendFormat("\"title\":\"{0}\",", dr["Title"]);
                json.AppendFormat("\"ico\":\"{0}\",", dr["Ico"]);
                json.AppendFormat("\"link\":\"{0}\",", dr["Address"]);
                json.AppendFormat("\"type\":\"{0}\",", "0");
                json.AppendFormat("\"model\":\"{0}\",", dr["OpenMode"]);
                json.AppendFormat("\"width\":\"{0}\",", dr["Width"]);
                json.AppendFormat("\"height\":\"{0}\",", dr["Height"]);
                json.AppendFormat("\"hasChilds\":\"{0}\",", childs.Length > 0 ? "1" : "0");
                json.AppendFormat("\"childs\":[");
                json.Append("]");
                json.Append("}");
                if (i < apps.Length - 1)
                {
                    json.Append(",");
                }
            }
            json.Append("]");
            json.Append("}");
            json.Append("]");

            Response.Write(json.ToString());
        }
Ejemplo n.º 47
0
        // save
        /// <summary>Saves an instance of the Train class into a specified file.</summary>
        /// <param name="FileName">The train.dat file to save.</param>
        /// <param name="t">An instance of the Train class to save.</param>
        internal static void Save(string FileName, Train t)
        {
            System.Globalization.CultureInfo Culture = System.Globalization.CultureInfo.InvariantCulture;
            System.Text.StringBuilder        b       = new System.Text.StringBuilder();
            b.AppendLine("OPENBVE");
            b.AppendLine("#ACCELERATION");
            if (t.Acceleration.Entries.Length > t.Handle.PowerNotches)
            {
                Array.Resize <Acceleration.Entry>(ref t.Acceleration.Entries, t.Handle.PowerNotches);
            }
            for (int i = 0; i < t.Acceleration.Entries.Length; i++)
            {
                b.Append(t.Acceleration.Entries[i].a0.ToString(Culture) + ",");
                b.Append(t.Acceleration.Entries[i].a1.ToString(Culture) + ",");
                b.Append(t.Acceleration.Entries[i].v1.ToString(Culture) + ",");
                b.Append(t.Acceleration.Entries[i].v2.ToString(Culture) + ",");
                b.AppendLine(t.Acceleration.Entries[i].e.ToString(Culture));
            }
            int n = 15;

            b.AppendLine("#PERFORMANCE");
            b.AppendLine(t.Performance.Deceleration.ToString(Culture).PadRight(n, ' ') + "; Deceleration");
            b.AppendLine(t.Performance.CoefficientOfStaticFriction.ToString(Culture).PadRight(n, ' ') + "; CoefficientOfStaticFriction");
            b.AppendLine("0".PadRight(n, ' ') + "; Reserved (not used)");
            b.AppendLine(t.Performance.CoefficientOfRollingResistance.ToString(Culture).PadRight(n, ' ') + "; CoefficientOfRollingResistance");
            b.AppendLine(t.Performance.AerodynamicDragCoefficient.ToString(Culture).PadRight(n, ' ') + "; AerodynamicDragCoefficient");
            b.AppendLine("#DELAY");
            b.AppendLine(t.Delay.DelayPowerUp.ToString(Culture).PadRight(n, ' ') + "; DelayPowerUp");
            b.AppendLine(t.Delay.DelayPowerDown.ToString(Culture).PadRight(n, ' ') + "; DelayPowerDown");
            b.AppendLine(t.Delay.DelayBrakeUp.ToString(Culture).PadRight(n, ' ') + "; DelayBrakeUp");
            b.AppendLine(t.Delay.DelayBrakeDown.ToString(Culture).PadRight(n, ' ') + "; DelayBrakeDown");
            b.AppendLine("#MOVE");
            b.AppendLine(t.Move.JerkPowerUp.ToString(Culture).PadRight(n, ' ') + "; JerkPowerUp");
            b.AppendLine(t.Move.JerkPowerDown.ToString(Culture).PadRight(n, ' ') + "; JerkPowerDown");
            b.AppendLine(t.Move.JerkBrakeUp.ToString(Culture).PadRight(n, ' ') + "; JerkBrakeUp");
            b.AppendLine(t.Move.JerkBrakeDown.ToString(Culture).PadRight(n, ' ') + "; JerkBrakeDown");
            b.AppendLine(t.Move.BrakeCylinderUp.ToString(Culture).PadRight(n, ' ') + "; BrakeCylinderUp");
            b.AppendLine(t.Move.BrakeCylinderDown.ToString(Culture).PadRight(n, ' ') + "; BrakeCylinderDown");
            b.AppendLine("#BRAKE");
            b.AppendLine(((int)t.Brake.BrakeType).ToString(Culture).PadRight(n, ' ') + "; BrakeType");
            b.AppendLine(((int)t.Brake.BrakeControlSystem).ToString(Culture).PadRight(n, ' ') + "; BrakeControlSystem");
            b.AppendLine(t.Brake.BrakeControlSpeed.ToString(Culture).PadRight(n, ' ') + "; BrakeControlSpeed");
            b.AppendLine("#PRESSURE");
            b.AppendLine(t.Pressure.BrakeCylinderServiceMaximumPressure.ToString(Culture).PadRight(n, ' ') + "; BrakeCylinderServiceMaximumPressure");
            b.AppendLine(t.Pressure.BrakeCylinderEmergencyMaximumPressure.ToString(Culture).PadRight(n, ' ') + "; BrakeCylinderEmergencyMaximumPressure");
            b.AppendLine(t.Pressure.MainReservoirMinimumPressure.ToString(Culture).PadRight(n, ' ') + "; MainReservoirMinimumPressure");
            b.AppendLine(t.Pressure.MainReservoirMaximumPressure.ToString(Culture).PadRight(n, ' ') + "; MainReservoirMaximumPressure");
            b.AppendLine(t.Pressure.BrakePipeNormalPressure.ToString(Culture).PadRight(n, ' ') + "; BrakePipeNormalPressure");
            b.AppendLine("#HANDLE");
            b.AppendLine(((int)t.Handle.HandleType).ToString(Culture).PadRight(n, ' ') + "; HandleType");
            b.AppendLine(t.Handle.PowerNotches.ToString(Culture).PadRight(n, ' ') + "; PowerNotches");
            b.AppendLine(t.Handle.BrakeNotches.ToString(Culture).PadRight(n, ' ') + "; BrakeNotches");
            b.AppendLine(t.Handle.PowerNotchReduceSteps.ToString(Culture).PadRight(n, ' ') + "; PowerNotchReduceSteps");
            b.AppendLine("#CAB");
            b.AppendLine(t.Cab.X.ToString(Culture).PadRight(n, ' ') + "; X");
            b.AppendLine(t.Cab.Y.ToString(Culture).PadRight(n, ' ') + "; Y");
            b.AppendLine(t.Cab.Z.ToString(Culture).PadRight(n, ' ') + "; Z");
            b.AppendLine(t.Cab.DriverCar.ToString(Culture).PadRight(n, ' ') + "; DriverCar");
            b.AppendLine("#CAR");
            b.AppendLine(t.Car.MotorCarMass.ToString(Culture).PadRight(n, ' ') + "; MotorCarMass");
            b.AppendLine(t.Car.NumberOfMotorCars.ToString(Culture).PadRight(n, ' ') + "; NumberOfMotorCars");
            b.AppendLine(t.Car.TrailerCarMass.ToString(Culture).PadRight(n, ' ') + "; TrailerCarMass");
            b.AppendLine(t.Car.NumberOfTrailerCars.ToString(Culture).PadRight(n, ' ') + "; NumberOfTrailerCars");
            b.AppendLine(t.Car.LengthOfACar.ToString(Culture).PadRight(n, ' ') + "; LengthOfACar");
            b.AppendLine((t.Car.FrontCarIsAMotorCar ? "1" : "0").PadRight(n, ' ') + "; FrontCarIsAMotorCar");
            b.AppendLine(t.Car.WidthOfACar.ToString(Culture).PadRight(n, ' ') + "; WidthOfACar");
            b.AppendLine(t.Car.HeightOfACar.ToString(Culture).PadRight(n, ' ') + "; HeightOfACar");
            b.AppendLine(t.Car.CenterOfGravityHeight.ToString(Culture).PadRight(n, ' ') + "; CenterOfGravityHeight");
            b.AppendLine(t.Car.ExposedFrontalArea.ToString(Culture).PadRight(n, ' ') + "; ExposedFrontalArea");
            b.AppendLine(t.Car.UnexposedFrontalArea.ToString(Culture).PadRight(n, ' ') + "; UnexposedFrontalArea");
            b.AppendLine("#DEVICE");
            b.AppendLine(((int)t.Device.Ats).ToString(Culture).PadRight(n, ' ') + "; Ats");
            b.AppendLine(((int)t.Device.Atc).ToString(Culture).PadRight(n, ' ') + "; Atc");
            b.AppendLine((t.Device.Eb ? "1" : "0").PadRight(n, ' ') + "; Eb");
            b.AppendLine((t.Device.ConstSpeed ? "1" : "0").PadRight(n, ' ') + "; ConstSpeed");
            b.AppendLine((t.Device.HoldBrake ? "1" : "0").PadRight(n, ' ') + "; HoldBrake");
            b.AppendLine(((int)t.Device.ReAdhesionDevice).ToString(Culture).PadRight(n, ' ') + "; ReAdhesionDevice");
            b.AppendLine(t.Device.LoadCompensatingDevice.ToString(Culture).PadRight(n, ' ') + "; Reserved (not used)");
            b.AppendLine(((int)t.Device.PassAlarm).ToString(Culture).PadRight(n, ' ') + "; PassAlarm");
            b.AppendLine(((int)t.Device.DoorOpenMode).ToString(Culture).PadRight(n, ' ') + "; DoorOpenMode");
            b.AppendLine(((int)t.Device.DoorCloseMode).ToString(Culture).PadRight(n, ' ') + "; DoorCloseMode");
            for (int i = 0; i < 4; i++)
            {
                Motor m = null;
                switch (i)
                {
                case 0:
                    b.AppendLine("#MOTOR_P1");
                    m = t.MotorP1;
                    break;

                case 1:
                    b.AppendLine("#MOTOR_P2");
                    m = t.MotorP2;
                    break;

                case 2:
                    b.AppendLine("#MOTOR_B1");
                    m = t.MotorB1;
                    break;

                case 3:
                    b.AppendLine("#MOTOR_B2");
                    m = t.MotorB2;
                    break;
                }
                int k;
                for (k = m.Entries.Length - 1; k >= 0; k--)
                {
                    if (m.Entries[k].SoundIndex >= 0)
                    {
                        break;
                    }
                }
                k = Math.Min(k + 2, m.Entries.Length);
                Array.Resize <Motor.Entry>(ref m.Entries, k);
                for (int j = 0; j < m.Entries.Length; j++)
                {
                    b.Append(m.Entries[j].SoundIndex.ToString(Culture) + ",");
                    b.Append(m.Entries[j].Pitch.ToString(Culture) + ",");
                    b.AppendLine(m.Entries[j].Volume.ToString(Culture));
                }
            }
            System.IO.File.WriteAllText(FileName, b.ToString(), new System.Text.UTF8Encoding(true));
        }
Ejemplo n.º 48
0
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        /// <exception cref="SwaggerException">A server side error occurred.</exception>
        public async System.Threading.Tasks.Task <FileResponse> EndEventAsync(string eventId, System.Threading.CancellationToken cancellationToken)
        {
            var urlBuilder_ = new System.Text.StringBuilder();

            urlBuilder_.Append("event/end?");
            urlBuilder_.Append(System.Uri.EscapeDataString("eventId") + "=").Append(System.Uri.EscapeDataString(eventId != null ? ConvertToString(eventId, System.Globalization.CultureInfo.InvariantCulture) : "")).Append("&");
            urlBuilder_.Length--;

            var client_ = _httpClient;

            try
            {
                using (var request_ = new System.Net.Http.HttpRequestMessage())
                {
                    request_.Content = new System.Net.Http.StringContent(string.Empty, System.Text.Encoding.UTF8, "application/octet-stream");
                    request_.Method  = new System.Net.Http.HttpMethod("POST");
                    request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/octet-stream"));

                    PrepareRequest(client_, request_, urlBuilder_);
                    var url_ = urlBuilder_.ToString();
                    request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
                    PrepareRequest(client_, request_, url_);

                    var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);

                    try
                    {
                        var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value);
                        if (response_.Content != null && response_.Content.Headers != null)
                        {
                            foreach (var item_ in response_.Content.Headers)
                            {
                                headers_[item_.Key] = item_.Value;
                            }
                        }

                        ProcessResponse(client_, response_);

                        var status_ = ((int)response_.StatusCode).ToString();
                        if (status_ == "200" || status_ == "206")
                        {
                            var responseStream_ = response_.Content == null ? System.IO.Stream.Null : await response_.Content.ReadAsStreamAsync().ConfigureAwait(false);

                            var fileResponse_ = new FileResponse((int)response_.StatusCode, headers_, responseStream_, null, response_);
                            client_ = null; response_ = null; // response and client are disposed by FileResponse
                            return(fileResponse_);
                        }
                        else
                        if (status_ != "200" && status_ != "204")
                        {
                            var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false);

                            throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null);
                        }

                        return(default(FileResponse));
                    }
                    finally
                    {
                        if (response_ != null)
                        {
                            response_.Dispose();
                        }
                    }
                }
            }
            finally
            {
            }
        }
Ejemplo n.º 49
0
 public void print(bool b)
 {
     line.Append(java.lang.SYSTEM.str(b));
 }
 /// <summary>
 /// Returns the string representation of this instance.
 /// </summary>
 /// <returns>The string representation of this instance.</returns>
 public override string ToString()
 {
     System.Text.StringBuilder dynStr = new System.Text.StringBuilder(GetType().Name);
     dynStr.Append(':');
     dynStr.Append("  Customer_acct_id=");
     dynStr.Append(Customer_acct_id);
     dynStr.Append("  Date_time=");
     dynStr.Append(Date_time);
     dynStr.Append("  Previous_amount=");
     dynStr.Append(Previous_amount);
     dynStr.Append("  Payment_amount=");
     dynStr.Append(Payment_amount);
     dynStr.Append("  Comments=");
     dynStr.Append(Comments);
     dynStr.Append("  Person_id=");
     dynStr.Append(Person_id);
     dynStr.Append("  Balance_adjustment_reason_id=");
     dynStr.Append(Balance_adjustment_reason_id);
     return(dynStr.ToString());
 }
Ejemplo n.º 51
0
        private void Page_Load(object sender, System.EventArgs e)
        {
            Classi.SiteModule _SiteModule = (Classi.SiteModule)HttpContext.Current.Items["SiteModule"];

            this.btnsCompletaOdl.Visible = _SiteModule.IsEditable;

            FunId    = _SiteModule.ModuleId;
            HelpLink = _SiteModule.HelpLink;
            this.PageTitle1.Title             = _SiteModule.ModuleTitle;
            this.GridTitle1.hplsNuovo.Visible = false;

            String scriptString = "<script language=JavaScript>var dettaglio;\n";

            scriptString += "function chiudi() {\n";
            scriptString += "if (dettaglio!=null)";
            scriptString += "if (document.Form1.hidRicerca.value=='0'){";
            scriptString += " dettaglio.close();}";
            scriptString += " else{";
            scriptString += "document.Form1.hidRicerca.value='1';}}<";
            scriptString += "/";
            scriptString += "script>";


            if (!this.IsClientScriptBlockRegistered("clientScript"))
            {
                this.RegisterClientScriptBlock("clientScript", scriptString);
            }

            System.Text.StringBuilder sbValid = new System.Text.StringBuilder();
            sbValid.Append("if (typeof(ControllaData) == 'function') { ");
            sbValid.Append("if (ControllaData() == false) { return false; }} ");
            sbValid.Append(this.Page.GetPostBackEventReference(this.btnsCompletaOdl));
            sbValid.Append(";");
            this.btnsCompletaOdl.Attributes.Add("onclick", sbValid.ToString());

            if (!Page.IsPostBack)
            {
                Session.Remove("DatiListMP");

                if (Context.Handler is TheSite.ManutenzioneProgrammata.CompletamentoMP)
                {
                    _fp = (TheSite.ManutenzioneProgrammata.CompletamentoMP)Context.Handler;
                    this.ViewState.Add("mioContenitore", _fp._Contenitore);
                }
                if (Context.Handler is TheSite.ManutenzioneProgrammata.SfogliaRdlOdl_MP)
                {
                    SfogliaRdlOdl_MP _fp2 = (TheSite.ManutenzioneProgrammata.SfogliaRdlOdl_MP)Context.Handler;
                    this.ViewState.Add("mioContenitore", _fp2._Contenitore);
                    this.ViewState.Add("paginardl", "paginardl");
                }

                ViewState["UrlReferrer"] = Request.UrlReferrer.ToString();
                if (Request.QueryString["wo_id"] != null)
                {
                    this.wo_id = Request.QueryString["wo_id"];
                }
                if (Context.Items["wo_id"] != null)
                {
                    this.wo_id = (string)Context.Items["wo_id"];
                }

                Ricerca(Int32.Parse(this.wo_id));
            }
            else
            {
                if (hiddenreload.Value == "1")
                {
                    Ricerca(Int32.Parse(this.wo_id));
                }
            }
        }
Ejemplo n.º 52
0
        public JSONObject(string str)
        {
            if (str == "")
            {
                type = Type.NULL;
                return;
            }

            if (str.Length > 0)
            {
                if (string.Compare(str, "true", true) == 0)
                {
                    type = Type.BOOL;
                    b    = true;
                }
                else if (string.Compare(str, "false", true) == 0)
                {
                    type = Type.BOOL;
                    b    = false;
                }
                else if (str == "null")
                {
                    type = Type.NULL;
                }
                else if (str == INFINITY)
                {
                    type = Type.NUMBER;
                    n    = double.PositiveInfinity;
                }
                else if (str == NEGINFINITY)
                {
                    type = Type.NUMBER;
                    n    = double.NegativeInfinity;
                }
                else if (str[0] == '"')
                {
                    type = Type.STRING;

                    // unescape backslashes and unicode
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    for (int i = 1; i < str.Length - 1; i++)
                    {
                        char thisChar = str[i];
                        if (thisChar == '\\')
                        {
                            // backslash
                            i++;
                            if (i < str.Length - 5 && str[i] == 'u')
                            {
                                // unicode
                                byte[] uniBytes = new byte[2];
                                uniBytes[1] = Convert.ToByte(str[++i].ToString() + str[++i], 16);
                                uniBytes[0] = Convert.ToByte(str[++i].ToString() + str[++i], 16);
                                sb.Append(System.Text.UTF8Encoding.UTF8.GetChars(uniBytes));
                            }
                            else if (i < str.Length - 1)
                            {
                                sb.Append(str[i]);
                            }
                            else
                            {
                                sb.Append('\\');
                            }
                        }
                        else                           // plain char
                        {
                            sb.Append(thisChar);
                        }
                    }

                    this.str = sb.ToString();
                }
                else
                {
                    try
                    {
                        // check for number type
                        n    = System.Convert.ToDouble(str);
                        type = Type.NUMBER;
                    }
                    catch (System.FormatException)
                    {
                        int token_tmp = 0;

                        /*
                         * Checking for the following formatting (www.json.org)
                         * object - {"field1":value,"field2":value}
                         * array - [value,value,value]
                         * value - string   - "string"
                         *     - number - 0.0
                         *     - bool      - true -or- false
                         *     - null      - null
                         */
                        switch (str[0])
                        {
                        case '{':
                            type  = Type.OBJECT;
                            keys  = new List <string>();
                            props = new List <JSONObject>();
                            break;

                        case '[':
                            type  = Type.ARRAY;
                            props = new List <JSONObject>();
                            break;

                        default:
                            type = Type.NULL;
                            return;
                        }

                        int  depth     = 0;
                        bool openquote = false;
                        bool inProp    = false;
                        for (int i = 1; i < str.Length; i++)
                        {
        #if !FROMTWITTER
                            // Twitter feeds may have these characters in their statuses
                            if (str[i] == '\\' || str[i] == '\t' || str[i] == '\n' || str[i] == '\r')
                            {
                                i++;
                                continue;
                            }
        #else
                            if (str[i] == '\\')
                            {
                                if (str.Length >= i & str[i + 1] == '\"')
                                {
                                    i++;
                                    continue;
                                }
                            }
        #endif

                            if (str[i] == '"')
                            {
                                openquote = !openquote;
                            }
                            else if (str[i] == '[' || str[i] == '{')
                            {
                                depth++;
                            }

                            if (depth == 0 && !openquote)
                            {
                                if (str[i] == ':' && !inProp)
                                {
                                    inProp = true;
                                    try {
                                        keys.Add(str.Substring(token_tmp + 2, i - token_tmp - 3));
                                    } catch {  }
                                    token_tmp = i;
                                }
                                if (str[i] == ',')
                                {
                                    inProp = false;
                                    props.Add(new JSONObject(str.Substring(token_tmp + 1, i - token_tmp - 1)));
                                    token_tmp = i;
                                }
                                if (str[i] == ']' || str[i] == '}')
                                {
                                    if (str[i - 1] != '[' && str[i - 1] != '{')
                                    {
                                        props.Add(new JSONObject(str.Substring(token_tmp + 1, i - token_tmp - 1)));
                                    }
                                }
                            }

                            if (str[i] == ']' || str[i] == '}')
                            {
                                depth--;
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 53
0
		/*!
		 * Summarizes the information contained in this object in English.
		 * \param[in] verbose Determines whether or not detailed information about large areas of data will be printed cs.
		 * \return A string containing a summary of the information within the object in English.  This is the function that Niflyze calls to generate its analysis, so the output is the same.
		 */
		public override string AsString(bool verbose = false)
		{
			var s = new System.Text.StringBuilder();
			s.Append(base.AsString());
			return s.ToString();
		}
Ejemplo n.º 54
0
        public static string FormatJSON(string str)
        {
            str = (str ?? "").Replace("{}", @"\{\}").Replace("[]", @"\[\]");

            var  inserts = new List <int[]>();
            bool quoted = false, escape = false;
            int  depth = 0 /*-1*/;

            for (int i = 0, N = str.Length; i < N; i++)
            {
                var chr = str[i];

                if (!escape && !quoted)
                {
                    switch (chr)
                    {
                    case '{':
                    case '[':
                        inserts.Add(new[] { i, +1, 0, INDENT_SIZE * ++depth });
                        break;

                    case ',':
                        inserts.Add(new[] { i, +1, 0, INDENT_SIZE * depth });
                        break;

                    case '}':
                    case ']':
                        inserts.Add(new[] { i, -1, INDENT_SIZE * --depth, 0 });
                        break;

                    case ':':
                        inserts.Add(new[] { i, 0, 1, 1 });
                        break;
                    }
                }

                quoted = (chr == '"') ? !quoted : quoted;
                escape = (chr == '\\') ? !escape : false;
            }

            if (inserts.Count > 0)
            {
                var sb = new System.Text.StringBuilder(str.Length * 2);

                int lastIndex = 0;
                foreach (var insert in inserts)
                {
                    int  index = insert[0], before = insert[2], after = insert[3];
                    bool nlBefore = (insert[1] == -1), nlAfter = (insert[1] == +1);

                    sb.Append(str.Substring(lastIndex, index - lastIndex));

                    if (nlBefore)
                    {
                        sb.AppendLine();
                    }
                    if (before > 0)
                    {
                        sb.Append(new String(' ', before));
                    }

                    sb.Append(str[index]);

                    if (nlAfter)
                    {
                        sb.AppendLine();
                    }
                    if (after > 0)
                    {
                        sb.Append(new String(' ', after));
                    }

                    lastIndex = index + 1;
                }

                str = sb.ToString();
            }

            return(str.Replace(@"\{\}", "{}").Replace(@"\[\]", "[]"));
        } // end of FormatJSON
Ejemplo n.º 55
0
        public override string ToString()
        {
            System.Text.StringBuilder sbuf = new System.Text.StringBuilder();
            switch (type)
            {
            case Parser.TCL_TOKEN_WORD:  {
                sbuf.Append("\n  Token Type: TCL_TOKEN_WORD");
                break;
            }

            case Parser.TCL_TOKEN_SIMPLE_WORD:  {
                sbuf.Append("\n  Token Type: TCL_TOKEN_SIMPLE_WORD");
                break;
            }

            case Parser.TCL_TOKEN_TEXT:  {
                sbuf.Append("\n  Token Type: TCL_TOKEN_TEXT");
                break;
            }

            case Parser.TCL_TOKEN_BS:  {
                sbuf.Append("\n  Token Type: TCL_TOKEN_BS");
                break;
            }

            case Parser.TCL_TOKEN_COMMAND:  {
                sbuf.Append("\n  Token Type: TCL_TOKEN_COMMAND");
                break;
            }

            case Parser.TCL_TOKEN_VARIABLE:  {
                sbuf.Append("\n  Token Type: TCL_TOKEN_VARIABLE");
                break;
            }
            }
            sbuf.Append("\n  String:      " + TokenString);
            sbuf.Append("\n  String Size: " + TokenString.Length);
            sbuf.Append("\n  ScriptIndex: " + script_index);
            sbuf.Append("\n  NumComponents: " + numComponents);
            sbuf.Append("\n  Token Size: " + size);
            return(sbuf.ToString());
        }
Ejemplo n.º 56
0
        /// <summary>
        /// ToString
        /// </summary>
        public override string ToString()
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            sb.Append(_account_id.ToString());
            sb.Append("|");

            sb.Append(_account_name.ToString());
            sb.Append("|");

            sb.Append(_account_status.ToString());
            sb.Append("|");

            sb.Append(_account_saldo.ToString());
            sb.Append("|");

            sb.Append(_account_desc.ToString());
            sb.Append("|");

            sb.Append(_account_position.ToString());
            sb.Append("|");

            sb.Append(_modified_by.ToString());
            sb.Append("|");

            sb.Append(_modified_date.ToString());
            return(sb.ToString());
        }
Ejemplo n.º 57
0
        private static void SendError(HttpContext context, int code, string message)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append("<?xml version=\"1.0\"?>");
            sb.Append("<methodResponse>");
            sb.Append("<fault>");
            sb.Append("<value>");
            sb.Append("<struct>");
            sb.Append("<member>");
            sb.Append("<name>faultCode</name>");
            sb.AppendFormat("<value><int>{0}</int></value>", code);
            sb.Append("</member>");
            sb.Append("<member>");
            sb.Append("<name>faultString</name>");
            sb.AppendFormat("<value><string>{0}</string></value>", message);
            sb.Append("</member>");
            sb.Append("</struct>");
            sb.Append("</value>");
            sb.Append("</fault>");
            sb.Append("</methodResponse>");

            context.Response.Write(sb.ToString());
        }
Ejemplo n.º 58
0
 internal void Append(string text)
 {
     _builder.Append(text);
 }
Ejemplo n.º 59
0
        public void OnLocalize(bool Force = false)
        {
            if (!Force && (!enabled || gameObject == null || !gameObject.activeInHierarchy))
            {
                return;
            }

            if (string.IsNullOrEmpty(LocalizationManager.CurrentLanguage))
            {
                return;
            }

            if (!AlwaysForceLocalize && !Force && !LocalizeCallBack.HasCallback() && LastLocalizedLanguage == LocalizationManager.CurrentLanguage)
            {
                return;
            }
            LastLocalizedLanguage = LocalizationManager.CurrentLanguage;

            if (!HasTargetCache() && !FindTarget())
            {
                return;
            }

            // These are the terms actually used (will be mTerm/mSecondaryTerm or will get them from the objects if those are missing. e.g. Labels' text and font name)
            if (string.IsNullOrEmpty(FinalTerm) || string.IsNullOrEmpty(FinalSecondaryTerm))
            {
                GetFinalTerms(out FinalTerm, out FinalSecondaryTerm);
            }


            bool hasCallback = LocalizationManager.IsPlaying() && LocalizeCallBack.HasCallback();

            if (!hasCallback && string.IsNullOrEmpty(FinalTerm) && string.IsNullOrEmpty(FinalSecondaryTerm))
            {
                return;
            }

            CallBackTerm          = FinalTerm;
            CallBackSecondaryTerm = FinalSecondaryTerm;
            MainTranslation       = string.IsNullOrEmpty(FinalTerm) || FinalTerm == "-" ? null : LocalizationManager.GetTranslation(FinalTerm, false);
            SecondaryTranslation  = string.IsNullOrEmpty(FinalSecondaryTerm) || FinalSecondaryTerm == "-" ? null : LocalizationManager.GetTranslation(FinalSecondaryTerm, false);

            if (!hasCallback && /*string.IsNullOrEmpty (MainTranslation)*/ string.IsNullOrEmpty(FinalTerm) && string.IsNullOrEmpty(SecondaryTranslation))
            {
                return;
            }

            CurrentLocalizeComponent = this;
            //if (LocalizationManager.IsPlaying())
            {
                LocalizeCallBack.Execute(this);                   // This allows scripts to modify the translations :  e.g. "Player {0} wins"  ->  "Player Red wins"
                LocalizationManager.ApplyLocalizationParams(ref MainTranslation, gameObject);
            }
            bool applyRTL = LocalizationManager.IsRight2Left && !IgnoreRTL;

            if (applyRTL)
            {
                if (mLocalizeTarget.AllowMainTermToBeRTL() && !string.IsNullOrEmpty(MainTranslation))
                {
                    MainTranslation = LocalizationManager.ApplyRTLfix(MainTranslation, MaxCharactersInRTL, IgnoreNumbersInRTL);
                }
                if (mLocalizeTarget.AllowSecondTermToBeRTL() && !string.IsNullOrEmpty(SecondaryTranslation))
                {
                    SecondaryTranslation = LocalizationManager.ApplyRTLfix(SecondaryTranslation);
                }
            }

            if (PrimaryTermModifier != TermModification.DontModify)
            {
                MainTranslation = MainTranslation ?? string.Empty;
            }

            switch (PrimaryTermModifier)
            {
            case TermModification.ToUpper: MainTranslation = MainTranslation.ToUpper(); break;

            case TermModification.ToLower: MainTranslation = MainTranslation.ToLower(); break;

            case TermModification.ToUpperFirst: MainTranslation = GoogleTranslation.UppercaseFirst(MainTranslation); break;

            case TermModification.ToTitle: MainTranslation = GoogleTranslation.TitleCase(MainTranslation); break;
            }

            if (SecondaryTermModifier != TermModification.DontModify)
            {
                SecondaryTranslation = SecondaryTranslation ?? string.Empty;
            }

            switch (SecondaryTermModifier)
            {
            case TermModification.ToUpper: SecondaryTranslation = SecondaryTranslation.ToUpper();  break;

            case TermModification.ToLower: SecondaryTranslation = SecondaryTranslation.ToLower();  break;

            case TermModification.ToUpperFirst: SecondaryTranslation = GoogleTranslation.UppercaseFirst(SecondaryTranslation); break;

            case TermModification.ToTitle: SecondaryTranslation = GoogleTranslation.TitleCase(SecondaryTranslation); break;
            }
            if (!string.IsNullOrEmpty(TermPrefix))
            {
                MainTranslation = applyRTL ? MainTranslation + TermPrefix : TermPrefix + MainTranslation;
            }
            if (!string.IsNullOrEmpty(TermSuffix))
            {
                MainTranslation = applyRTL ? TermSuffix + MainTranslation : MainTranslation + TermSuffix;
            }

            if (AddSpacesToJoinedLanguages && LocalizationManager.HasJoinedWords && !string.IsNullOrEmpty(MainTranslation))
            {
                var sb = new System.Text.StringBuilder();
                sb.Append(MainTranslation[0]);
                for (int i = 1, imax = MainTranslation.Length; i < imax; ++i)
                {
                    sb.Append(' ');
                    sb.Append(MainTranslation[i]);
                }

                MainTranslation = sb.ToString();
            }
            mLocalizeTarget.DoLocalize(this, MainTranslation, SecondaryTranslation);

            CurrentLocalizeComponent = null;
        }
Ejemplo n.º 60
0
        /// <summary>
        /// decodes url
        /// </summary>
        /// <param name="escaped"></param>
        /// <returns></returns>
        protected static String urlDecode(String escaped)
        {
            // Should we better use HttpUtility.UrlDecode?
            // Is HttpUtility.UrlDecode available for all platforms?
            // What about encoding like UTF8?

            if (escaped == null)
            {
                return(null);
            }
            char[] escapedArray = escaped.ToCharArray();

            int first = findFirstEscape(escapedArray);

            if (first < 0)
            {
                return(escaped);
            }

            int max = escapedArray.Length;
            // final length is at most 2 less than original due to at least 1 unescaping
            var unescaped = new System.Text.StringBuilder(max - 2);

            // Can append everything up to first escape character
            unescaped.Append(escapedArray, 0, first);

            for (int i = first; i < max; i++)
            {
                char c = escapedArray[i];
                if (c == '+')
                {
                    // + is translated directly into a space
                    unescaped.Append(' ');
                }
                else if (c == '%')
                {
                    // Are there even two more chars? if not we will just copy the escaped sequence and be done
                    if (i >= max - 2)
                    {
                        unescaped.Append('%'); // append that % and move on
                    }
                    else
                    {
                        int firstDigitValue  = parseHexDigit(escapedArray[++i]);
                        int secondDigitValue = parseHexDigit(escapedArray[++i]);
                        if (firstDigitValue < 0 || secondDigitValue < 0)
                        {
                            // bad digit, just move on
                            unescaped.Append('%');
                            unescaped.Append(escapedArray[i - 1]);
                            unescaped.Append(escapedArray[i]);
                        }
                        unescaped.Append((char)((firstDigitValue << 4) + secondDigitValue));
                    }
                }
                else
                {
                    unescaped.Append(c);
                }
            }
            return(unescaped.ToString());
        }