示例#1
0
 public override string ToString()
 {
     var sb = new System.Text.StringBuilder();
     sb.AppendLine(string.Format("{0}: {1}", "X", X));
     sb.AppendLine(string.Format("{0}: {1}", "Y", Y));
     return sb.ToString();
 }
        public ActionResult FlowList(int? PageIndex, int? PageSize, Int64? qDepotID, long? qProductID, DateTime? qCreateDateStart, DateTime? qCreateDateEnd, int? orderCol)
        {
            if ((_crud & Zippy.SaaS.Entity.CRUD.Read) != Zippy.SaaS.Entity.CRUD.Read) return RedirectToAction("NoPermission", "Error");

            System.Text.StringBuilder sbMenu = new System.Text.StringBuilder();
            if ((_crud & Zippy.SaaS.Entity.CRUD.Read) == Zippy.SaaS.Entity.CRUD.Read)
                sbMenu.AppendLine("<a href='javascript:;' class='btn list img' id='search'><i class='icon i_search'></i>查询<b></b></a>");
            sbMenu.AppendLine("<a href='javascript:;' class='btn img' id='bReload'><i class='icon i_refresh'></i>刷新<b></b></a>");
            ViewData["TopMenu"] = sbMenu.ToString();

            ViewData.Add("db", db);
            ViewData.Add("PageSize", PageSize ?? 10);
            int currentPageSize = PageSize ?? 10;
            int currentPageIndex = PageIndex ?? 1;

            Hashtable hs = new Hashtable();
            hs.Add("qDepotID", qDepotID);
            hs.Add("qProductID", qProductID);
            hs.Add("qCreateDateStart", qCreateDateStart);
            hs.Add("qCreateDateEnd", qCreateDateEnd);

            PaginatedList<EAP.Logic.Z10.View.V_DepotFlow> result = Z10DepotFlowHelper.Query(db, _tenant.TenantID.Value, currentPageSize, currentPageIndex, hs, orderCol);
            result.QueryParameters = hs;
            ViewData["DepotOptions"] = EAP.Logic.Z10.HtmlHelper.DepotSelectOptions(_tenant.TenantID.Value, db);
            return View(result);
        }
示例#3
0
		//=========================================================================================
		internal string GetText(TextPoint start, TextPoint end)
		{
			if (start > end)
			{
				TextPoint temp = start;
				start = end;
				end = temp;
			}
			if (start.Line == end.Line)
				return this.Lines[start.Line].Text.Substring(start.Char, end.Char - start.Char);
			else
			{
				System.Text.StringBuilder sb = new System.Text.StringBuilder();

				string sLine = this.Lines[start.Line].Text;
				sb.AppendLine(sLine.Substring(start.Char, sLine.Length - start.Char));

				for (int i = start.Line + 1; i < end.Line; i++)
					sb.AppendLine(this.Lines[i].Text);

				sb.AppendLine(this.Lines[end.Line].Text.Substring(0, end.Char));

				return sb.ToString();
			}
		}
        protected void Page_Load(object sender, EventArgs e)
        {
            intSite = Convert.ToInt32(HttpContext.Current.Session["SiteId"].ToString());
            DataSet data = new DataSet();
            data = adds.Get_SideAdds(intSite);//product.Get_SideFeaturedProducts(intSite, intCont, intSubjId);
            System.Text.StringBuilder sbproduct = new System.Text.StringBuilder();
            int contDiv = 0;
            foreach (DataTable table in data.Tables)
            {
                foreach (DataRow row in table.Rows)
                {
                    if (contDiv == 0)
                    {
                        sbproduct.AppendLine("<a href=\"generic_x?LandingId=" + row["AddsLink"] + "\"><div class=\"pubMeetOut\"><img src=\"images\\" + row["AddsImage"] + "\"/> </div></a>");

                    }
                    else
                    {
                        sbproduct.AppendLine("<a href=\"generic_x?LandingId=" + row["AddsLink"] + "\"><div class=\"pubNeedHelp\"><img src=\"images\\" + row["AddsImage"] + "\"/> </div></a>");

                    }
                    contDiv++;
                }
            }
            if (contDiv != 0)
            {
                Product1.Controls.Add(new LiteralControl(sbproduct.ToString()));
                div_Wrapper.Visible = true;
            }
        }
示例#5
0
        public static string CheckSyntax(string script, out string stdout)
        {
            stdout = null;

            if (script.StartsWith("#fommScript")) return "Cannot syntax check a fomm script";

            string[] errors = null;
            string[] warnings = null;

            Compile(script, out errors, out warnings, out stdout);
            if (errors != null || warnings != null)
            {
                StringBuilder sb = new StringBuilder();
                if (errors != null)
                {
                    sb.AppendLine("Errors:");
                    for (int i = 0; i < errors.Length; i++) sb.AppendLine(errors[i]);
                }
                if (warnings != null)
                {
                    sb.AppendLine("Warnings:");
                    for (int i = 0; i < warnings.Length; i++) sb.AppendLine(warnings[i]);
                }
                return sb.ToString();
            }
            return null;
        }
        /// <summary>
        /// タイムカード情報を取得
        /// </summary>
        /// <param name="data"></param>
        public int GetTimeCardInfo(System.Data.DataSet data)
        {
            System.Text.StringBuilder sqlbldr = new System.Text.StringBuilder();

            sqlbldr.AppendLine("select ");
            sqlbldr.AppendLine("    t1.timecard_id ");
            sqlbldr.AppendLine("    ,t1.clock_in_time ");
            sqlbldr.AppendLine("    ,t1.clock_out_time ");
            sqlbldr.AppendLine("from eip_t_ext_timecard t1");
            sqlbldr.AppendLine("where 1 = 1");
            sqlbldr.AppendLine("and t1.user_id = :user_id");
            sqlbldr.AppendLine("and t1.punch_date = to_date(:punch_date, 'YYYY-MM-DD')");

            ExtTimeCardDataSet.search_eip_t_ext_timecardRow param = ((ExtTimeCardDataSet)data).search_eip_t_ext_timecard[0];

            ArrayList paramList = new ArrayList();
            if (!String.IsNullOrEmpty(param.user_id))
            {
                paramList.Add(DBUtility.MakeParameter("user_id", param.user_id, NpgsqlDbType.Integer));
            }
            if (!String.IsNullOrEmpty(param.punch_date))
            {
                paramList.Add(DBUtility.MakeParameter("punch_date", param.punch_date, NpgsqlDbType.Varchar));
            }

            return this.dbHelper.Select(((ExtTimeCardDataSet)data).eip_t_ext_timecard, sqlbldr.ToString(), paramList);
        }
示例#7
0
        /// <summary>
        /// Handles the Error event of the Application control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void Application_Error(object sender, EventArgs e)
        {
            Exception ex = Server.GetLastError();
            if (ex is System.Threading.ThreadAbortException)
                return;

            ex.ExceptionValueTracker(new Dictionary<string, object>() {
                {"Is AJAX Request",HttpContext.Current.Request.IsAjaxRequest().ToString()},
                {"Request URL",HttpContext.Current.Request.Url},
                {"Request Type", HttpContext.Current.Request.HttpMethod},
                {"Request Context", HttpContext.Current.Request.Form}
            });

            if (!HttpContext.Current.Request.IsAjaxRequest())
            {
                HttpContext.Current.Response.Redirect(string.Format("{0}/Error/Index?msg={1}",
                    ConfigurationManager.AppSettings["VirtualDirectory"].ToString(), ex.Message));
            }
            else
            {
                HttpContext.Current.Response.StatusCode = 500;

                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                sb.AppendLine(string.Format("Error Source: {0}", ex.InnerException.Source));
                sb.AppendLine(string.Format("Error Message: {0}", ex.InnerException.Message));
                sb.AppendLine(string.Format("Error Stack: {0}", ex.InnerException.StackTrace));
                HttpContext.Current.Response.Write(sb.ToString());
            }
        }
        protected override void Render(HtmlTextWriter writer)
        {
            var node = this.Provider.CurrentNode;
            var nodes = new Stack<SiteMapNode>();

            for (var currentNode = node; currentNode != null; currentNode = currentNode.ParentNode)
            {
                nodes.Push(currentNode);
            }

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

            sb.AppendLine(@"<ul class=""breadcrumb"" " + this.CssClass + ">");

            foreach (var currentNode in nodes)
            {
                var siteMapNode = this.Provider.CurrentNode;
                if (siteMapNode != null && currentNode.Url == siteMapNode.Url)
                {
                    sb.AppendLine(@"<li class=""active"">" + currentNode.Title + "</li>");
                }
                else
                {
                    if (currentNode != null)
                        if (currentNode.ParentNode == null)
                            sb.AppendLine(@"<li><i class='fa fa-home'></i><a href=""" + currentNode.Url + @""">" + currentNode.Title + "</a></li>");
                        else
                            sb.AppendLine(@"<li><a href=""" + currentNode.Url + @""">" + currentNode.Title + "</a></li>");
                }
            }

            sb.AppendLine(@"</ul>");

            if (writer != null) writer.Write(sb.ToString());
        }
        protected void sendButton_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid)
                return;

            string subject = string.Format("ezLooker: {0}", this.emailInput.Text);

            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.AppendLine();
            sb.AppendFormat("IP: {0}", Request.UserHostAddress).AppendLine();
            sb.AppendFormat("UserAgent: {0}", Request.UserAgent).AppendLine();
            sb.AppendFormat("Name: {0}", this.nameInput.Text).AppendLine();
            sb.AppendFormat("Email: {0}", this.emailInput.Text).AppendLine();
            sb.AppendLine("Comment:");
            sb.AppendFormat("{0}", this.commentInput.Text).AppendLine();

            try
            {
                using (MailMessage mailMessage = new MailMessage("*****@*****.**", "*****@*****.**", subject, sb.ToString()))
                {
                    using (SmtpClient smtpClient = new SmtpClient() { Host = "smtp.gmail.com", Credentials = new NetworkCredential("*****@*****.**", "ihateHTML!"), EnableSsl = true })
                    {
                        smtpClient.Send(mailMessage);
                    }
                }
            }
            catch
            {
                // TODO: Log Exeption
            }

            this.contact.ActiveViewIndex = 1;
        }
示例#10
0
        /// <summary>
        /// Creates a new TestSuite instance.
        /// </summary>
        /// <param name="openFile"> A callback that can open a file for reading. </param>
        public TestSuite(Func<string, Stream> openFile)
        {
            if (openFile == null)
                throw new ArgumentNullException("openFile");

            // Init collection.
            this.IncludedTests = new List<string>();

            // Open the excludelist.xml file to generate a list of skipped file names.
            var reader = System.Xml.XmlReader.Create(openFile(@"config\excludeList.xml"));
            reader.ReadStartElement("excludeList");
            do
            {
                if (reader.Depth == 1 && reader.NodeType == System.Xml.XmlNodeType.Element && reader.Name == "test")
                    this.skippedTestNames.Add(reader.GetAttribute("id"));
            } while (reader.Read());

            // Read the include files.
            var includeBuilder = new System.Text.StringBuilder();
            includeBuilder.AppendLine(ReadInclude(openFile, "cth.js"));
            includeBuilder.AppendLine(ReadInclude(openFile, "sta.js"));
            includeBuilder.AppendLine(ReadInclude(openFile, "ed.js"));
            this.includes = includeBuilder.ToString();

            this.zipStream = openFile(@"suite\2012-05-18.zip");
            this.zipFile = new ZipFile(this.zipStream);
            this.ApproximateTotalTestCount = (int)this.zipFile.Count;
        }
示例#11
0
 public void Summary(Exception ex, string ExtraInfo = null)
 {
     System.Text.StringBuilder message = new System.Text.StringBuilder();
     if (ExtraInfo != null) message.AppendLine(ExtraInfo + Environment.NewLine);
     message.AppendLine(ex.Description() + Environment.NewLine);
     if (this.Log != null) this.Log.Out(message.ToString(), Dumpster2.Logger.TextFormat.Box);
     var df = new frmError(ex.GetType().Name, message.ToString());
 }
示例#12
0
 public override void WriteDescriptionTo(NUnitCtr.MessageWriter writer)
 {
     var sb = new System.Text.StringBuilder();
     sb.AppendLine();
     sb.AppendFormat("Successful execution of the etl.");
     sb.AppendLine();
     writer.WritePredicate(sb.ToString());
 }
        protected override void Render(HtmlTextWriter writer)
        {
            base.Render(writer);

            try
            {

                if (this.ListToDisplay != null)
                {
                    SPList selectedList = SPContext.Current.Web.Lists[new Guid(this._listToDisplay)];
                    SPView defaultView = selectedList.DefaultView;
                    if (this.IsExternalList)
                    {
                        SPViewFieldCollection fields = defaultView.ViewFields;
                        System.Collections.Specialized.StringCollection stringCol = fields.ToStringCollection();
                        // Nik20121105 - Write the table headers;
                        System.Text.StringBuilder sb = new System.Text.StringBuilder();
                        sb.AppendLine("<table class=\"wet-boew-zebra\">");
                        sb.Append("<tr>");
                        foreach (string field in stringCol)
                        {
                            sb.Append("<th>" + field + "</th>");
                        }
                        sb.Append("</tr>");

                        foreach (SPListItem item in selectedList.Items)
                        {
                            sb.AppendLine("<tr>");
                            bool firstCol = true;
                            foreach (string field in stringCol)
                            {
                                if (firstCol)
                                {
                                    firstCol = false;
                                    sb.AppendLine("<td><a href=\"" + SPContext.Current.Web.Url + "/_layouts/listform.aspx?PageType=4&ListId={" + this._listToDisplay + "}&ID=" + item["BdcIdentity"].ToString() + "\">" + item[field].ToString() + "</a></td>");
                                }
                                else
                                {
                                    sb.AppendLine("<td>" + item[field].ToString() + "</td>");
                                }
                            }
                            sb.AppendLine("</tr>");
                        }

                        sb.AppendLine("</table>");
                        writer.Write(sb.ToString());
                    }
                    else
                    {
                        writer.Write(defaultView.RenderAsHtml());
                    }
                }
            }
            catch (Exception ex)
            {
                writer.Write(ex.ToString());
            }
        }
示例#14
0
        public void NamedQueryParametersCheck()
        {
            var namedQueryType = typeof(INamedQuery);
              var queryImplAssembly = typeof(BookWithISBN).Assembly;

              var types = from t in queryImplAssembly.GetTypes()
                  where namedQueryType.IsAssignableFrom(t)
                  && t.IsClass
                  && !t.IsAbstract
                  select t;

              var nhCfg = NHConfigurator.Configuration;

              var mappedQueries = nhCfg.NamedQueries.Keys
            .Union(nhCfg.NamedSQLQueries.Keys);

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

              foreach (var queryType in types)
              {
            var query = (INamedQuery)
              Activator.CreateInstance(queryType, new object[] { SessionFactory });

            if (!mappedQueries.Contains(query.QueryName))
            {
              errors.AppendFormat(
            "Query object {0} references non-existent named query {1}.",
            queryType, query.QueryName);

              errors.AppendLine();
              continue;
            }

            var nhQuery = Session.GetNamedQuery(query.QueryName);

            var mapParams = nhQuery.NamedParameters;
            var objParams = query.Parameters.Keys;

            foreach (var paramName in mapParams.Except(objParams))
            {
              errors.AppendFormat("{0} has param {1} in mapping, but not object",
            query.QueryName, paramName);
              errors.AppendLine();
            }

            foreach (var paramName in objParams.Except(mapParams))
            {
              errors.AppendFormat("{0} has param {1} in object, but not mapping",
            query.QueryName, paramName);
              errors.AppendLine();
            }

              }

              if (errors.Length != 0)
            Assert.Fail(errors.ToString());
        }
示例#15
0
        public override string ToString()
        {
            System.Text.StringBuilder builder = new System.Text.StringBuilder();
            builder.AppendLine("Name: " + szPname);
            builder.AppendLine("DriverVersion: " + vDriverVersion);
            builder.AppendLine("Formate: " + dwFormats.ToString());

            return builder.ToString();
        }
示例#16
0
        public override string GetInfo()
        {
            var builder = new System.Text.StringBuilder();

            builder.AppendLine("Assembly: " + m_resource.Assembly.FullName);
            builder.AppendLine("Flags: " + (m_resource.IsPublic ? "public " : " ") + (m_resource.IsPrivate ? "private " : " "));

            return builder.ToString();
        }
示例#17
0
        public static void WriteLog(string filename, string message)
        {
            var builder = new System.Text.StringBuilder();
            builder.AppendLine("=======================" + DateTime.Now.ToString() + "=======================");
            builder.AppendLine(message);
            builder.AppendLine("=================================================");

            System.IO.File.AppendAllText(filename, builder.ToString());
        }
示例#18
0
        /// <summary>Integrates Unity when the application starts.</summary>
        public static void Start()
        {
            var container = ContainerManager.GetConfiguredContainer();
            UnityConfig.RegisterTypes(container);

            FilterProviders.Providers.Remove(FilterProviders.Providers.OfType<FilterAttributeFilterProvider>().First());
            FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(container));

            DependencyResolver.SetResolver(new UnityDependencyResolver(container));

            var assemblies = AppDomain.CurrentDomain.GetAssemblies();

            try
            {
                //http://stackoverflow.com/questions/699852/how-to-find-all-the-classes-which-implement-a-given-interface
                foreach (var assembly in assemblies)
                {
                    var instances = from t in assembly.GetTypes()
                                    where t.GetInterfaces().Contains(typeof(IDependencyRegister))
                                             && t.GetConstructor(Type.EmptyTypes) != null
                                    select Activator.CreateInstance(t) as IDependencyRegister;

                    foreach (var instance in instances.OrderBy(x => x.Order))
                    {
                        instance.Register(container);
                    }
                }
            }
            catch (ReflectionTypeLoadException ex)
            {
            http://stackoverflow.com/questions/1091853/error-message-unable-to-load-one-or-more-of-the-requested-types-retrieve-the-l
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                foreach (Exception exSub in ex.LoaderExceptions)
                {
                    sb.AppendLine(exSub.Message);
                    System.IO.FileNotFoundException exFileNotFound = exSub as System.IO.FileNotFoundException;
                    if (exFileNotFound != null)
                    {
                        if (!string.IsNullOrEmpty(exFileNotFound.FusionLog))
                        {
                            sb.AppendLine("Fusion Log:");
                            sb.AppendLine(exFileNotFound.FusionLog);
                        }
                    }
                    sb.AppendLine();
                }
                string errorMessage = sb.ToString();

                throw new Exception(errorMessage, ex);
                //Display or log the error based on your application.
            }


            // TODO: Uncomment if you want to use PerRequestLifetimeManager
            // Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule));
        }
示例#19
0
文件: Computer.cs 项目: DzIvanova/OOP
 public override string ToString()
 {
     System.Text.StringBuilder output = new System.Text.StringBuilder();
     output.AppendLine("Name: " + this.Name);
     output.AppendLine("Motherboard: " + this.Motherboard.ToString());
     output.AppendLine("Processor: " + this.Processor.ToString());
     output.AppendLine("RAM: " + this.RAM.ToString());
     output.AppendLine("Total Price: " + this.PcPrice + " lv");
     return output.ToString();
 }
 public override void WriteDescriptionTo(NUnitCtr.MessageWriter writer)
 {
     var sb = new System.Text.StringBuilder();
     sb.AppendLine("Query is not syntactically correct.");
     foreach (var failure in parserResult.Errors)
     {
         sb.AppendLine(failure);
     }
     writer.WritePredicate(sb.ToString());
 }
示例#21
0
 public void Extended(Exception ex, string ExtraInfo = null)
 {
     System.Text.StringBuilder message = new System.Text.StringBuilder();
     if (ExtraInfo != null) message.AppendLine(ExtraInfo + Environment.NewLine);
     message.AppendLine(ex.Description() + Environment.NewLine);
     message.AppendLine("--Stack Trace--" + Environment.NewLine + ex.StackTrace + Environment.NewLine);
     if (ex.InnerException != null) message.AppendLine("Inner Exceptions:" + Environment.NewLine + ex.InnerExList() + Environment.NewLine);
     if (this.Log != null) this.Log.Out(message.ToString(), Dumpster2.Logger.TextFormat.Box);
     var df = new frmError(ex.GetType().Name, message.ToString());
 }
示例#22
0
        public static void Main(string[] args)
        {
            Application.Init ();

            if (!ImageMagickResolver.Resolved ()) {
                var builder = new System.Text.StringBuilder ("Hi there,");
                builder.AppendLine ();
                builder.AppendLine ("I was unable to find ImageMagick on your system which means...");
                builder.AppendLine ("a) It is not installed");
                builder.AppendLine ("b) It is in a directory I haven't checked");
                builder.AppendLine ("");
                builder.AppendLine ("If 'a' please exit the application and install ImageMagick");
                builder.AppendLine ("If 'b' then please edit the file '{0}' and insert the correct location for convert and montage");
                builder.AppendLine ();
                builder.AppendLine ("Please visit the FAQ <a href=\"http://fontwhiz.com\">http://fontwhiz.com</a> if you are unclear.");

                var messageDialog = new MessageDialog (null,
                                                       DialogFlags.Modal,
                                                       MessageType.Error,
                                                       ButtonsType.Close,
                                                       builder.ToString (), UserSettings.AppUserSettingsFile);

                messageDialog.WindowPosition = WindowPosition.Center;

                messageDialog.Run ();
                messageDialog.Destroy ();
                return;
            }

            MainWindow win = new MainWindow ();
            win.Show ();
            Application.Run ();
        }
        /// <summary>
        /// Lista os parametros de entrada da Procedure selecionada
        /// </summary>
        /// <param name="dataBaseName">Nome do banco de dados alvo</param>
        /// <param name="usr">Dados do usuario</param>
        /// <param name="procedureName">Nome da Stored Procedure alvo</param>
        /// <returns></returns>
        public List<DadosStoredProceduresParameters> ListaAllStoredProceduresParameters(string dataBaseName, DadosUsuario usr, string procedureName)
        {
            using (var cnn=Conexao.RetornaConexaoBase(usr))
            {
                var clsTables = new List<DadosStoredProceduresParameters>();
    
                cnn.Open();

                var sbSql = new System.Text.StringBuilder();
                if (cnn.ServerVersion != null && cnn.ServerVersion.Contains("5."))
                {
                    sbSql.AppendLine("SELECT TRIM(CAST(param_list AS CHAR(10000) CHARACTER SET utf8)) AS parametros FROM mysql.proc ");
                    sbSql.AppendLine(string.Format("WHERE name = '{0}' AND db='{1}';", procedureName, dataBaseName));

                    var cmd = new MySqlCommand(sbSql.ToString(), cnn);

                    using (var dr = cmd.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            var strParametros = dr[0];
                            var arrayParam = strParametros.ToString().Trim().Split(',');

                            clsTables.AddRange(arrayParam.Select(p => p.Trim().Split(' ')).Select(ajustaParam => new DadosStoredProceduresParameters
                            {
                                ParameterName = ajustaParam[1],
                                ParameterDataType = ajustaParam[2],
                                ParameterMaxBytes = RetornaBytesParametro(ajustaParam[2].ToLower()),
                                IsOutPutParameter = ajustaParam[0] != "IN",
                                ParameterDotNetType = _rorinas.RetornaTipoDadosDotNet(ajustaParam[2])
                            }));
                        }                        
                    }
                }
                else
                {
                    sbSql.AppendLine("SELECT PARAMETER_NAME, '' AS ParameterValue, DATA_TYPE AS ParameterDataType, CHARACTER_MAXIMUM_LENGTH AS ParameterMaxBytes, CASE PARAMETER_MODE WHEN 'IN' THEN 0 else 1 END AS IsOutPutParameter ");
                    sbSql.Append("FROM INFORMATION_SCHEMA.PARAMETERS ");
                    sbSql.AppendFormat("WHERE SPECIFIC_NAME='{0}' ", procedureName);
                    sbSql.Append("ORDER BY ORDINAL_POSITION;");

                    var cmd = new MySqlCommand(sbSql.ToString(), cnn);

                    using (var dr = cmd.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            clsTables.Add(new DadosStoredProceduresParameters { ParameterName = dr["PARAMETER_NAME"].ToString(), ParameterDataType = dr["ParameterDataType"].ToString(), ParameterMaxBytes = dr["ParameterMaxBytes"].ToString(), IsOutPutParameter = Convert.ToBoolean(dr["IsOutPutParameter"] ?? false), ParameterDotNetType = _rorinas.RetornaTipoDadosDotNet(dr["ParameterDataType"].ToString()) });
                        }                        
                    }
                }

                return clsTables;                
            }
        }
        /// <summary>
        /// 標準のタイムカードの日付変更時刻を取得
        /// </summary>
        /// <param name="data"></param>
        public int GetChangeHourDefault(System.Data.DataSet data)
        {
            System.Text.StringBuilder sqlbldr = new System.Text.StringBuilder();

            sqlbldr.AppendLine("select t1.change_hour ");
            sqlbldr.AppendLine("from eip_t_ext_timecard_system t1");
            sqlbldr.AppendLine("where 1 = 1");
            sqlbldr.AppendLine("and t1.system_id = '1'");

            return this.dbHelper.Select(((ExtTimeCardDataSet)data).eip_t_ext_timecard_system, sqlbldr.ToString(), null);
        }
        // Handle OnException event for this controller
        protected override void OnException(ExceptionContext filterContext)
        {
            // log error
            System.Text.StringBuilder message = new System.Text.StringBuilder();
            message.AppendLine(DateTime.Now.ToString());
            message.AppendLine(filterContext.Exception.ToString());
            message.AppendLine("=========================================");

            string logFile = HttpContext.Request.MapPath("/Log/controllererrors.txt");
            System.IO.File.AppendAllText(logFile, message.ToString());
        }
示例#26
0
        public static string PrintR(this System.Collections.Generic.List<Newtonsoft.Json.Linq.JToken> list)
        {
            var sb = new System.Text.StringBuilder();
            foreach(Newtonsoft.Json.Linq.JToken json in list) {

                sb.AppendLine(json.ToString(Newtonsoft.Json.Formatting.Indented));
                sb.AppendLine("\n==========\n");
            }

            return sb.ToString();
        }
示例#27
0
 /// <summary>
 /// 获取企业开通服务信息
 /// </summary>
 /// <returns>DataTable</returns>
 public static DataTable GetCompanyOpenSevParms()
 {
     System.Text.StringBuilder sql = new System.Text.StringBuilder();
     sql.AppendLine("select [CompanyCD],[MaxRoles],[MaxUers],[MaxDocSize],[SingleDocSize],");
     sql.AppendLine("[MaxDocNum],[DocSavePath],[MaxKeywords],[MaxUserKeywords],[OpenDate],");
     sql.AppendLine("[CloseDate],[ModifiedDate],[ModifiedUserID],[remark],[LogoImg] ");
     sql.AppendLine("from pubdba.companyOpenServ ");
     //SqlParameter[] parms = new SqlParameter[1];
     //parms[0] = SqlHelper.GetParameter("@CompanyCD", CompanyCD);
     return SqlHelper.ExecuteSql(sql.ToString());
 }
示例#28
0
        /// <summary>
        /// 提示错误信息并跳转至指定地址
        /// </summary>
        /// <param name="page">当前页类</param>
        /// <param name="message">提示错误信息</param>
        /// <param name="redirectUrl">指定的跳转地址</param>
        public static void WarmAlert(this System.Web.UI.Page page, string message, string redirectUrl)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            sb.AppendLine("<script>");
            sb.AppendFormat("alert(\"{0}\");", message);
            sb.AppendFormat("document.location.href = \"{0}\";", redirectUrl);
            sb.AppendLine("</script>");

            page.Response.Write(sb.ToString());
            page.Response.End();
        }
示例#29
0
            public string toString()
            {
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                sb.AppendLine("\r\nRob1:");
                sb.Append(tows[0].toString());
                sb.AppendLine("\r\nRob2:");
                sb.Append(tows[1].toString());
                sb.AppendLine("\r\nRob3:");
                sb.Append(tows[2].toString());

                return sb.ToString();
            }
示例#30
0
 /// <summary>
 /// Converts the statement to a string.
 /// </summary>
 /// <param name="indentLevel"> The number of tabs to include before the statement. </param>
 /// <returns> A string representing this statement. </returns>
 public override string ToString(int indentLevel)
 {
     indentLevel = Math.Max(indentLevel - 1, 0);
     var result = new System.Text.StringBuilder();
     result.Append(new string('\t', indentLevel));
     result.AppendLine("{");
     foreach (var statement in this.Statements)
         result.AppendLine(statement.ToString(indentLevel + 1));
     result.Append(new string('\t', indentLevel));
     result.Append("}");
     return result.ToString();
 }
示例#31
0
        public static void Main(string[] args)
        {
            string printername = "";

            AssemblyResolver.HandleUnresolvedAssemblies();

#if REPMAN_DOTNET2
            // Bug in .Net 1.x, don't enable, but you can use a .manifest file
#if FORMS
            Application.EnableVisualStyles();
#endif
#endif
            bool dothrow = false;



            Report rp = new Report();
            try
            {
                bool   asyncexecution  = true;
                bool   stdin           = false;
                bool   pdf             = false;
                bool   metafile        = false;
                bool   showprintdialog = false;
                string filename        = "";
                string pdffilename     = "";
                string fieldsfilename  = "";
                bool   deletereport    = false;
                bool   showprogress    = false;
                bool   preview         = false;
                bool   showparams      = false;
                bool   compressedpdf   = true;
                bool   systempreview   = false;
                bool   showdata        = false;
                bool   showfields      = false;
                bool   testconnection  = false;
                string connectionname  = "";
                bool   doprint         = true;
                bool   evaluatetext    = false;
                bool   syntaxcheck     = false;
                bool   doread          = true;
                string evaltext        = "";
                string dataset         = "";
                SortedList <string, string> ParamValues = new SortedList <string, string>();
#if REPMAN_DOTNET2
                bool   showproviders     = false;
                string providersfilename = "";
#endif
                try
                {
                    for (int i = 0; i < args.Length; i++)
                    {
                        if (args[i].Trim().Length > 0)
                        {
                            switch (args[i].ToUpper())
                            {
                            case "-STDIN":
                                stdin = true;
                                break;

                            case "-PREVIEW":
                                preview = true;
                                break;

                            case "-SHOWPARAMS":
                                showparams = true;
                                break;

                            case "-SYNCEXECUTION":
                                asyncexecution = false;
                                break;

                            case "-SYSTEMPREVIEW":
                                systempreview = true;
                                break;

                            case "-U":
                                compressedpdf = false;
                                break;

                            case "-THROW":
                                dothrow = true;
                                break;

                            case "-PDF":
                                pdf = true;
                                if (args.GetUpperBound(0) > i)
                                {
                                    i++;
                                    pdffilename = args[i];
                                }
                                break;

                            case "-M":
                                metafile = true;
                                if (args.GetUpperBound(0) > i)
                                {
                                    i++;
                                    pdffilename = args[i];
                                }
                                break;

                            case "-SHOWDATA":
                                showdata = true;
                                doprint  = false;
                                if (args.GetUpperBound(0) > i)
                                {
                                    i++;
                                    dataset = args[i];
                                }
                                break;

                            case "-TESTCONNECTION":
                                doprint        = false;
                                testconnection = true;
                                if (args.GetUpperBound(0) > i)
                                {
                                    i++;
                                    connectionname = args[i];
                                }
                                break;

                            case "-EVAL":
                                doprint      = false;
                                evaluatetext = true;
                                if (args.GetUpperBound(0) > i)
                                {
                                    i++;
                                    evaltext = args[i];
                                }
                                break;

                            case "-SYNTAX":
                                doprint     = false;
                                syntaxcheck = true;
                                if (args.GetUpperBound(0) > i)
                                {
                                    i++;
                                    evaltext = args[i];
                                }
                                break;

                            case "-SHOWFIELDS":
                                showfields = true;
                                doprint    = false;
                                if (args.GetUpperBound(0) > i)
                                {
                                    i++;
                                    dataset = args[i];
                                }
                                if (args.GetUpperBound(0) > i)
                                {
                                    i++;
                                    fieldsfilename = args[i];
                                }
                                break;

                            case "-GETPROVIDERS":
                                showproviders = true;
                                doprint       = false;
                                doread        = false;
                                if (args.GetUpperBound(0) > i)
                                {
                                    i++;
                                    providersfilename = args[i];
                                }
                                break;

                            case "-GETPRINTERS":
                                System.Text.StringBuilder nprinters = new System.Text.StringBuilder();
                                nprinters.AppendLine("Installed printers:");
                                foreach (string pname in System.Drawing.Printing.PrinterSettings.InstalledPrinters)
                                {
                                    nprinters.AppendLine(pname);
                                }
#if FORMS
                                MessageBox.Show(nprinters.ToString());
#else
                                System.Console.WriteLine(nprinters.ToString());
#endif
                                break;

                            case "-PRINTERNAME":
                                if (args.GetUpperBound(0) > i)
                                {
                                    i++;
                                    printername = args[i];
                                }
                                else
                                {
                                    throw new Exception("A printer name must be provided after -printername");
                                }
                                break;

                            case "-SHOWPROGRESS":
                                showprogress = true;
                                break;

                            case "-DELETEREPORT":
                                deletereport = true;
                                break;

                            case "-PRINTDIALOG":
                                showprintdialog = true;
                                break;

                            default:
                                // Get parameter names and values
                                string argname = args[i];
                                if (argname[0] == '-')
                                {
                                    bool correctparam = false;
                                    if (argname.Length > 7)
                                    {
                                        if (argname.Substring(0, 6).ToUpper() == "-PARAM")
                                        {
                                            argname = argname.Substring(6, argname.Length - 6);
                                            int indexequ = argname.IndexOf('=');
                                            if (indexequ < 0)
                                            {
                                                throw new Exception("Invalid syntax in -param, -paramPARAMNAME=value syntax must be used");
                                            }
                                            string paramvalue = argname.Substring(indexequ + 1, argname.Length - indexequ - 1);
                                            argname = argname.Substring(0, indexequ);
                                            ParamValues.Add(argname, paramvalue);
                                            System.Console.WriteLine("Decoded parameter: " + argname + " value " + paramvalue);
                                            correctparam = true;
                                        }
                                    }
                                    if (!correctparam)
                                    {
                                        throw new Exception("Invalid argument:" + args[i]);
                                    }
                                }
                                else
                                {
                                    if (filename.Length > 0)
                                    {
                                        filename = args[i];
                                    }
                                    else
                                    {
                                        filename = args[i];
                                    }
                                }
                                break;
                            }
                        }
                    }
                    AddCustomFactories();

#if REPMAN_DOTNET2
                    if (showproviders)
                    {
                        string messageproviders = "";

/*#if REPMAN_MONO
 *                                              if (providersfilename.Length == 0)
 *                                              {
 *                                                      foreach (Provider p in ProviderFactory.Providers)
 *                                                      {
 *                                                              if (messageproviders.Length!=0)
 *                                                                      messageproviders=messageproviders+(char)13+(char)10;
 *                                                              messageproviders=messageproviders+p.Name;
 *
 *                                                      }
 *                                                      MessageBox.Show(messageproviders,"Data providers");
 *                                              }
 *                                              else
 *                                              {
 *                                                      FileStream providersstream = new FileStream(providersfilename,System.IO.FileMode.Create,System.IO.FileAccess.Write,System.IO.FileShare.None);
 *                                                      try
 *                                                      {
 *                                                              foreach (Provider p2 in ProviderFactory.Providers)
 *                                                              {
 *                                                                      StreamUtil.SWriteLine(providersstream,p2.Name);
 *                                                              }
 *                                                      }
 *                                                      finally
 *                                                      {
 *                                                              providersstream.Close();
 *                                                      }
 *
 *                                              }
 #else*/
                        int       indexp;
                        DataTable atable = DbProviderFactories.GetFactoryClasses();
                        if (providersfilename.Length == 0)
                        {
                            bool firebirdfound = false;
                            bool mysqlfound    = false;
                            bool sqlitefound   = false;
                            for (indexp = 0; indexp < atable.Rows.Count; indexp++)
                            {
                                if (messageproviders.Length != 0)
                                {
                                    messageproviders = messageproviders + (char)13 + (char)10;
                                }
                                string nprovider = atable.Rows[indexp][2].ToString();
                                if (nprovider == DatabaseInfo.FIREBIRD_PROVIDER)
                                {
                                    firebirdfound = true;
                                }
                                if (nprovider == DatabaseInfo.MYSQL_PROVIDER)
                                {
                                    mysqlfound = true;
                                }
                                if (nprovider == DatabaseInfo.SQLITE_PROVIDER)
                                {
                                    sqlitefound = true;
                                }
                                messageproviders = messageproviders + atable.Rows[indexp][2].ToString();
                            }
                            if (!firebirdfound)
                            {
                                messageproviders = DatabaseInfo.FIREBIRD_PROVIDER + (char)13 + (char)10 + messageproviders;
                            }
                            if (!mysqlfound)
                            {
                                messageproviders = DatabaseInfo.MYSQL_PROVIDER + (char)13 + (char)10 + messageproviders;
                            }
                            if (!sqlitefound)
                            {
                                messageproviders = DatabaseInfo.SQLITE_PROVIDER + (char)13 + (char)10 + messageproviders;
                            }
#if FORMS
                            MessageBox.Show(messageproviders, "Data providers");
#else
                            System.Console.WriteLine("Data providers");
                            System.Console.WriteLine(messageproviders);
#endif
                        }
                        else
                        {
                            FileStream providersstream = new FileStream(providersfilename, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None);
                            try
                            {
                                bool    firebirdfound = false;
                                bool    mysqlfound    = false;
                                bool    sqlitefound   = false;
                                Strings nstrings      = new Strings();
                                for (indexp = 0; indexp < atable.Rows.Count; indexp++)
                                {
                                    string nprovider = atable.Rows[indexp][2].ToString();
                                    if (nprovider == DatabaseInfo.FIREBIRD_PROVIDER)
                                    {
                                        firebirdfound = true;
                                    }
                                    if (nprovider == DatabaseInfo.MYSQL_PROVIDER)
                                    {
                                        mysqlfound = true;
                                    }
                                    if (nprovider == DatabaseInfo.SQLITE_PROVIDER)
                                    {
                                        sqlitefound = true;
                                    }
                                    nstrings.Add(nprovider);
                                }
                                if (!firebirdfound)
                                {
                                    nstrings.Insert(0, DatabaseInfo.FIREBIRD_PROVIDER);
                                }
                                if (!mysqlfound)
                                {
                                    nstrings.Insert(0, DatabaseInfo.MYSQL_PROVIDER);
                                }
                                if (!sqlitefound)
                                {
                                    nstrings.Insert(0, DatabaseInfo.SQLITE_PROVIDER);
                                }

                                foreach (string nstring in nstrings)
                                {
                                    StreamUtil.SWriteLine(providersstream, nstring);
                                }
                            }
                            finally
                            {
                                providersstream.Close();
                            }
                        }
//#endif
                    }
#endif
                    if (doread)
                    {
                        if (stdin)
                        {
                            Stream astream = System.Console.OpenStandardInput();
                            rp.LoadFromStream(astream, 8192);
                        }
                        else
                        {
                            if (filename.Length == 0)
                            {
                                throw new Exception("You must provide a report filename");
                            }
                            rp.LoadFromFile(filename);
                        }

                        foreach (string nparamname in ParamValues.Keys)
                        {
                            string nvalue = ParamValues[nparamname];
                            if (rp.Params.IndexOf(nparamname) < 0)
                            {
                                System.Console.WriteLine("Warning: parameter not found created: " + nparamname);
                                Reportman.Reporting.Param xparam = new Reportman.Reporting.Param(rp);
                                xparam.Alias   = nparamname;
                                xparam.Visible = false;
                                rp.Params.Add(xparam);
                                //throw new Exception("Parameter " + nparamname + " not found");
                            }
                            rp.Params[nparamname].Value = nvalue;
                        }
                    }
                    if (showdata)
                    {
                        rp.PrintOnlyIfDataAvailable = false;
                        PrintOutPDF printpdf3 = new PrintOutPDF();
                        rp.BeginPrint(printpdf3);
#if FORMS
                        DataShow.ShowData(rp, dataset);
#else
                        rp.DataInfo[dataset].Connect();
                        ReportDataset ndataset = rp.DataInfo[dataset].Data;
                        foreach (DataColumn ncol in ndataset.Columns)
                        {
                            string nstring = ncol.ColumnName.PadLeft(30);
                            if (nstring.Length > 30)
                            {
                                nstring = nstring.Substring(0, 30);
                            }
                            System.Console.Write(nstring);
                        }
                        System.Console.WriteLine();
                        while (!ndataset.Eof)
                        {
                            foreach (DataColumn ncol in ndataset.Columns)
                            {
                                string nstring = ndataset.CurrentRow[ncol.ColumnName].ToString().PadLeft(30);
                                if (nstring.Length > 30)
                                {
                                    nstring = nstring.Substring(0, 30);
                                }
                                System.Console.Write(nstring);
                            }
                            System.Console.WriteLine();
                            ndataset.Next();
                        }
#endif
                    }
                    if (testconnection)
                    {
                        int conindex = rp.DatabaseInfo.IndexOf(connectionname);
                        if (conindex < 0)
                        {
                            throw new Exception("Connection name not found:" + connectionname);
                        }
                        rp.DatabaseInfo[conindex].Connect();
#if FORMS
                        MessageBox.Show("Connexion successfull:" + connectionname);
#else
                        System.Console.WriteLine("Connexion successfull:" + connectionname);
#endif
                    }
                    if (showfields)
                    {
                        int index = rp.DataInfo.IndexOf(dataset);
                        if (index < 0)
                        {
                            throw new Exception("Dataset not found:" + dataset);
                        }
                        rp.DataInfo[index].Connect();
                        FileStream fstream = new FileStream(fieldsfilename,
                                                            System.IO.FileMode.Create, System.IO.FileAccess.Write,
                                                            System.IO.FileShare.None);
                        try
                        {
                            rp.DataInfo[index].GetFieldsInfo(fstream);
                        }
                        finally
                        {
                            fstream.Close();
                        }
                    }
                    if ((evaluatetext) || (syntaxcheck))
                    {
                        rp.PrintOnlyIfDataAvailable = false;
                        PrintOutPDF printpdf2 = new PrintOutPDF();
                        rp.BeginPrint(printpdf2);
                        if (evaluatetext)
                        {
                            try
                            {
                                Variant aresult = rp.Evaluator.EvaluateText(evaltext);
#if FORMS
                                MessageBox.Show("Result:" + aresult.ToString());
#else
                                System.Console.WriteLine("Result:" + aresult.ToString());
#endif
                            }

                            catch (EvalException e)
                            {
#if FORMS
                                MessageBox.Show("Error Line: " + e.SourceLine.ToString() +
                                                " Error position:" + e.SourcePos.ToString() + " - " + e.Message);
#else
                                System.Console.WriteLine("Error Line: " + e.SourceLine.ToString() +
                                                         " Error position:" + e.SourcePos.ToString() + " - " + e.Message);
#endif
                            }
                            catch (Exception E)
                            {
#if FORMS
                                MessageBox.Show("Error: " + E.Message);
#else
                                System.Console.WriteLine("Error: " + E.Message);
#endif
                            }
                        }
                        else
                        {
                            try
                            {
                                rp.Evaluator.CheckSyntax(evaltext);
#if FORMS
                                MessageBox.Show("Syntax check ok");
#else
                                System.Console.WriteLine("Syntax check ok");
#endif
                            }
                            catch (Exception E)
                            {
#if FORMS
                                MessageBox.Show("Error: " + E.Message);
#else
                                System.Console.WriteLine("Error: " + E.Message);
#endif
                            }
                        }
                    }
                    // Ask for parameters?
                    if (doprint)
                    {
                        if (showparams)
                        {
#if FORMS
                            doprint = ParamsForm.ShowParams(rp);
#else
                            throw new Exception("Show params not supported in console mode");
#endif
                        }
                    }
                    if (doprint)
                    {
                        if (showprogress)
#if FORMS
                        {
                            ReportProgressForm fprogres = new ReportProgressForm();
                            fprogres.SetMetaFile(rp.MetaFile);
                            fprogres.Show();
                        }
#else
                        { throw new Exception("Show progress not supported in console mode"); }
#endif
                        if (pdf)
                        {
                            rp.AsyncExecution = false;
                            PrintOutPDF printpdf = new PrintOutPDF();
                            printpdf.FileName   = pdffilename;
                            printpdf.Compressed = compressedpdf;
                            printpdf.Print(rp.MetaFile);
                        }
                        else
                        if (metafile)
                        {
                            rp.AsyncExecution = false;
                            rp.TwoPass        = true;
                            PrintOutPDF printpdf = new PrintOutPDF();
                            printpdf.FileName   = "";
                            printpdf.Compressed = compressedpdf;
                            printpdf.Print(rp.MetaFile);
                            rp.MetaFile.SaveToFile(pdffilename, compressedpdf);
                        }
                        else
                        {
                            rp.AsyncExecution = asyncexecution;
#if FORMS
                            PrintOutReportWinForms prw = new PrintOutReportWinForms(rp);
                            prw.Preview         = preview;
                            prw.ShowInTaskbar   = true;
                            prw.SystemPreview   = systempreview;
                            prw.ShowPrintDialog = showprintdialog;
                            prw.Print(rp.MetaFile);
#else
                            PrintOutPrint prw = new PrintOutPrint();
                            if (printername.Length > 0)
                            {
                                PrintOutNet.DefaultPrinterName = printername;
                            }

                            prw.Print(rp.MetaFile);
#endif

                            //                                PrintOutWinForms prw = new PrintOutWinForms();
                            //							prw.OptimizeWMF = WMFOptimization.Gdiplus;
                        }
                    }
                }
                finally
                {
                    if (deletereport)
                    {
                        if (filename.Length > 0)
                        {
                            System.IO.File.Delete(filename);
                        }
                    }
                }
            }
            catch (Exception E)
            {
                if (!dothrow)
                {
                    int    i;
                    string amessage = E.Message + (char)13 + (char)10;
                    for (i = 0; i < args.Length; i++)
                    {
                        amessage = amessage + (char)13 + (char)10 + "Arg" + i.ToString() + ":" + args[i];
                    }
                    Strings astrings = GetParams();
                    for (i = 0; i < astrings.Count; i++)
                    {
                        amessage = amessage + (char)13 + (char)10 + astrings[i];
                    }

#if FORMS
                    MessageBox.Show(amessage, "Error");
#else
                    System.Console.WriteLine(amessage);
#endif
                    System.Console.WriteLine(E.StackTrace);
                }
                else
                {
                    PrintParams();
                    throw;
                }
                //				Variant.WriteStringToUTF8Stream(amessage,System.Console.OpenStandardError());
            }
        }
示例#32
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();
            var array_output_count = 0U;

            s.Append(base.AsString());
            arraySize = (ushort)interpArrayItems.Count;
            s.AppendLine($"      Flags:  {flags}");
            s.AppendLine($"      Array Size:  {arraySize}");
            s.AppendLine($"      Array Grow By:  {arrayGrowBy}");
            s.AppendLine($"      Weight Threshold:  {weightThreshold}");
            if (((flags & 1) == 0))
            {
                s.AppendLine($"        Interp Count:  {interpCount}");
                s.AppendLine($"        Single Index:  {singleIndex}");
                s.AppendLine($"        High Priority:  {highPriority}");
                s.AppendLine($"        Next High Priority:  {nextHighPriority}");
                s.AppendLine($"        Single Time:  {singleTime}");
                s.AppendLine($"        High Weights Sum:  {highWeightsSum}");
                s.AppendLine($"        Next High Weights Sum:  {nextHighWeightsSum}");
                s.AppendLine($"        High Ease Spinner:  {highEaseSpinner}");
                array_output_count = 0;
                for (var i4 = 0; i4 < interpArrayItems.Count; i4++)
                {
                    if (!verbose && (array_output_count > Nif.MAXARRAYDUMP))
                    {
                        s.AppendLine("<Data Truncated. Use verbose mode to see complete listing.>");
                        break;
                    }
                    s.AppendLine($"          Interpolator:  {interpArrayItems[i4].interpolator}");
                    s.AppendLine($"          Weight:  {interpArrayItems[i4].weight}");
                    s.AppendLine($"          Normalized Weight:  {interpArrayItems[i4].normalizedWeight}");
                    s.AppendLine($"          Priority:  {interpArrayItems[i4].priority}");
                    s.AppendLine($"          Ease Spinner:  {interpArrayItems[i4].easeSpinner}");
                }
            }
            s.AppendLine($"      Managed Controlled:  {managedControlled}");
            s.AppendLine($"      Only Use Highest Weight:  {onlyUseHighestWeight}");
            s.AppendLine($"      Single Interpolator:  {singleInterpolator}");
            return(s.ToString());
        }
示例#33
0
        /* String builder used for all debug logging */
        //public static System.Text.StringBuilder debugStringBuilder = new System.Text.StringBuilder ();

        /** Returns a debug string for this path.
         */
        public override string DebugString(PathLog logMode)
        {
            if (logMode == PathLog.None || (!error && logMode == PathLog.OnlyErrors))
            {
                return("");
            }

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

            text.Append(error ? "Path Failed : " : "Path Completed : ");
            text.Append("Computation Time ");

            text.Append((duration).ToString(logMode == PathLog.Heavy ? "0.000" : "0.00"));
            text.Append(" ms Searched Nodes ");
            text.Append(searchedNodes);

            if (!error)
            {
                text.Append(" Path Length ");
                text.Append(path == null ? "Null" : path.Count.ToString());

                if (logMode == PathLog.Heavy)
                {
                    text.Append("\nSearch Iterations " + searchIterations);

                    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 >");
                    }
                    //text.Append ("\nBinary Heap size at completion: ");
                    //text.Append (pathHandler.open == null ? "Null" : (pathHandler.open.numberOfItems-2).ToString ());// -2 because numberOfItems includes the next item to be added and item zero is not used
                }

                /*"\nEnd node\n	G = "+p.endNode.g+"\n	H = "+p.endNode.H+"\n	F = "+p.endNode.f+"\n	Point	"+p.endPoint
                 +"\nStart Point = "+p.startPoint+"\n"+"Start Node graph: "+p.startNode.graphIndex+" End Node graph: "+p.endNode.graphIndex+
                 * "\nBinary Heap size at completion: "+(p.open == null ? "Null" : p.open.numberOfItems.ToString ())*/
            }

            if (error)
            {
                text.Append("\nError: ");
                text.Append(errorLog);
            }

            // Can only print this from the Unity thread
            // since otherwise an exception might be thrown
            if (logMode == PathLog.Heavy && !AstarPath.active.IsUsingMultithreading)
            {
                text.Append("\nCallback references ");
                if (callback != null)
                {
                    text.Append(callback.Target.GetType().FullName).AppendLine();
                }
                else
                {
                    text.AppendLine("NULL");
                }
            }

            text.Append("\nPath Number ");
            text.Append(pathID);

            return(text.ToString());
        }
示例#34
0
        void OnStatGUI()
        {
            var sb = new System.Text.StringBuilder();

            sb.AppendFormat("num peds: {0}\n", Ped.NumPeds);
            sb.AppendFormat("num vehicles: {0}\n", Vehicle.NumVehicles);
            sb.AppendFormat("num ped state changes received: {0}\n", Ped.NumStateChangesReceived);

            sb.AppendLine();

            // info about local ped

            var ped = Ped.Instance;

            if (ped != null)
            {
                sb.AppendFormat("Local ped:\n");
                sb.AppendFormat("position: {0}\n", ped.transform.position);
                sb.AppendFormat("net id: {0}\n", ped.netId);
                sb.AppendFormat("sync interval: {0}\n", ped.NetTransform.syncInterval);
                sb.AppendFormat("state: {0}\n", ped.CurrentState != null ? ped.CurrentState.GetType().Name : "");
                sb.AppendFormat("velocity: {0}\n", ped.Velocity);
                sb.AppendFormat("is grounded: {0}\n", ped.IsGrounded);
                sb.AppendFormat("model id: {0}\n", ped.PedDef != null ? ped.PedDef.Id.ToString() : "");
                sb.AppendFormat("model name: {0}\n", ped.PedDef != null ? ped.PedDef.ModelName : "");
                sb.AppendFormat("\n");

                // info about current vehicle

                var vehicle = ped.CurrentVehicle;
                if (vehicle != null)
                {
                    List <System.Object> objects = new List <System.Object>()
                    {
                        vehicle.Velocity,
                        vehicle.Accelerator,
                        vehicle.Braking,
                        vehicle.Steering,
                        vehicle.AverageWheelHeight,
                        vehicle.NetTransform.netId,
                        vehicle.NetTransform.syncInterval,
                        vehicle.NetTransform.ComponentIndex,
                    };

                    var texts = new List <string>()
                    {
                        "velocity", "accelerator", "braking", "steering", "average wheel height",
                        "net id", "sync interval", "component index"
                    };


                    texts.Add("wheels");
                    objects.Add("");
                    foreach (var w in vehicle.Wheels)
                    {
                        texts.Add("\t" + w.Alignment);
                        objects.Add(string.Format("travel {0} rpm {1} radius {2} motor torque {3} mass {4} is grounded {5}",
                                                  w.Travel, w.Collider.rpm, w.Collider.radius, w.Collider.motorTorque, w.Collider.mass, w.Collider.isGrounded));
                    }

                    if (vehicle.Definition != null)
                    {
                        var def = vehicle.Definition;
                        texts.Add("game name");
                        texts.Add("type");
                        objects.Add(def.GameName);
                        objects.Add(def.VehicleType);
                    }

                    texts.Add("rigid body");
                    objects.Add("");
                    if (vehicle.RigidBody != null)
                    {
                        var rb = vehicle.RigidBody;
                        texts.AddRange(new string[] { "\tmass", "\tvelocity", "\tangular velocity" });
                        objects.AddRange(new object[] { rb.mass, rb.velocity, rb.angularVelocity });
                    }

                    texts.Add("seats");
                    objects.Add("");
                    foreach (var seat in vehicle.Seats)
                    {
                        texts.Add("\t" + seat.Alignment);
                        var p = seat.OccupyingPed;
                        objects.Add(p != null ? ("ped: net id " + p.netId) : "empty");
                    }

                    var closestSeat = vehicle.FindClosestSeatTransform(ped.transform.position);
                    if (closestSeat != null)
                    {
                        texts.Add("distance to closest seat");
                        objects.Add(Vector3.Distance(closestSeat.position, ped.transform.position));
                    }


                    sb.AppendFormat("Current vehicle:\n");
                    for (int i = 0; i < objects.Count; i++)
                    {
                        sb.AppendFormat("{0}: {1}\n", texts[i], objects[i]);
                    }
                    sb.AppendFormat("\n");
                }

                // info about current weapon
                var weapon = ped.CurrentWeapon;
                if (weapon != null)
                {
                    sb.AppendFormat("Current weapon:\n");

                    sb.AppendFormat("net id: {0}\n", weapon.NetWeapon.netId);

                    var def = weapon.Definition;
                    if (def != null)
                    {
                        sb.AppendFormat("model id: {0}\n", def.Id);
                        sb.AppendFormat("name: {0}\n", def.ModelName);
                    }

                    sb.AppendFormat("max range: {0}\n", weapon.MaxRange);
                    sb.AppendFormat("damage: {0}\n", weapon.Damage);
                    sb.AppendFormat("ammo clip size: {0}\n", weapon.AmmoClipSize);
                    sb.AppendFormat("ammo: {0} / {1}\n", weapon.AmmoInClip, weapon.AmmoOutsideOfClip);
                    sb.AppendFormat("slot: {0}\n", weapon.SlotIndex);

                    sb.AppendLine();
                }

                // info about all weapons
                sb.AppendFormat("All weapons:\n");
                foreach (var w in ped.WeaponHolder.AllWeapons)
                {
                    sb.AppendFormat("\tslot: {0} name: {1}\n", w.SlotIndex, w.Definition.ModelName);
                }
                sb.AppendLine();
            }

            GUILayout.Label(sb.ToString());
        }
示例#35
0
        static int MetaConstructFunctionInternal(lua_State L)
        {
            var typeObj = Lua.ObjectAtInternal(L, 1);

            Lua.Assert((typeObj != null && (typeObj is System.Type)), "Constructor needs type object.");

            var numArgs = Api.lua_gettop(L);

            int[] luaArgTypes = Lua.luaArgTypes_NoArgs;
            if (numArgs > 1)             // the first arg is class itself
            {
                luaArgTypes = new int[numArgs - 1];
                for (var i = 2; i <= numArgs; ++i)
                {
                    luaArgTypes[i - 2] = Api.lua_type(L, i);
                }
            }

            var type = (System.Type)typeObj;

            if (luaArgTypes == Lua.luaArgTypes_NoArgs && type.IsValueType)
            {
                var value = Activator.CreateInstance(type);
                Lua.PushObjectInternal(L, value);
                return(1);
            }

            var mangledName = Lua.Mangle(L, "__ctor", luaArgTypes, invokingStaticMethod: true, argStart: 2);
            var mc          = Lua.GetMethodFromCache(type, mangledName);

            System.Reflection.ParameterInfo[] parameters = null;
            if (mc == null)
            {
                var constructors = type.GetConstructors();
                System.Reflection.MethodBase selected = null;
                int highScore = int.MinValue;
                List <Exception> pendingExceptions = null;
                for (var i = 0; i < constructors.Length; ++i)
                {
                    var method = constructors[i];
                    try
                    {
                        Lua.MatchingParameters(L, 2, method, luaArgTypes, ref highScore, ref selected, ref parameters);
                    }
                    catch (System.Reflection.AmbiguousMatchException e)
                    {
                        throw e;
                    }
                    catch (Exception e)
                    {
                        if (pendingExceptions == null)
                        {
                            pendingExceptions = new List <Exception>();
                        }
                        pendingExceptions.Add(e);
                    }
                }
                if (selected != null)
                {
                    mc = Lua.CacheMethod(type, mangledName, selected, parameters);
                }
                else
                {
                    var additionalMessage = string.Empty;
                    if (pendingExceptions != null && pendingExceptions.Count > 0)
                    {
                        var sb = new System.Text.StringBuilder();
                        for (int i = 0; i < pendingExceptions.Count; ++i)
                        {
                            sb.AppendLine(pendingExceptions[i].Message);
                        }
                        additionalMessage = sb.ToString();
                    }
                    throw new Exception(string.Format("No proper constructor available, calling {0}\n{1}", Lua.GetLuaInvokingSigniture("ctor", luaArgTypes), additionalMessage));
                }
            }

            var ctor = (System.Reflection.ConstructorInfo)mc.method;

            IDisposable[] disposableArgs;
            var           args = Lua.ArgsFrom(L, mc.parameters, mc.variadicArg, 2, luaArgTypes.Length, out disposableArgs);

            Lua.PushObjectInternal(L, ctor.Invoke(args));
            if (disposableArgs != null)
            {
                foreach (var d in disposableArgs)
                {
                    if (d != null)
                    {
                        d.Dispose();
                    }
                }
            }
            return(1);
        }
示例#36
0
        public void ListStaticValue_RegtypeDeliveryPaymentTitleSafix(string SelRegType, string SelDelivery, string SelPayment, string SelTitle, string SelSafix)
        {
            List <StaticValuInfo> countries = CommonMethods.ListStaticValue();

            System.Text.StringBuilder sbPrefferedDeliveryMethodList = new System.Text.StringBuilder();
            System.Text.StringBuilder sbPrefferedPaymentMethodList  = new System.Text.StringBuilder();
            System.Text.StringBuilder sbGSTRegistrationTypeList     = new System.Text.StringBuilder();
            System.Text.StringBuilder sbTitleList = new System.Text.StringBuilder();
            System.Text.StringBuilder sbSafixList = new System.Text.StringBuilder();

            sbPrefferedDeliveryMethodList.AppendLine("<option value=\"\">Select one</option>");
            sbPrefferedPaymentMethodList.AppendLine("<option value=\"\">Select one</option>");
            sbGSTRegistrationTypeList.AppendLine("<option value=\"\">Select one</option>");
            sbTitleList.AppendLine("<option value=\"\">Select one</option>");
            sbSafixList.AppendLine("<option value=\"\">Select one</option>");

            if (countries != null && countries.Count > 0)
            {
                foreach (StaticValuInfo country in countries)
                {
                    if (country.Key == "GSTRegistrationType")
                    {
                        if (!string.IsNullOrEmpty(SelRegType) && country.Id.Trim() == SelRegType.Trim())
                        {
                            sbGSTRegistrationTypeList.AppendLine("<option value=\"" + country.Id + "\" selected=\"selected\">" + country.Value + "</option>");
                        }
                        else
                        {
                            sbGSTRegistrationTypeList.AppendLine("<option value=\"" + country.Id + "\">" + country.Value + "</option>");
                        }
                    }
                    else if (country.Key == "UserNameTitle")
                    {
                        if (!string.IsNullOrEmpty(SelTitle) && country.Id.Trim() == SelTitle.Trim())
                        {
                            sbTitleList.AppendLine("<option value=\"" + country.Id + "\" selected=\"selected\">" + country.Value + "</option>");
                        }
                        else
                        {
                            sbTitleList.AppendLine("<option value=\"" + country.Id + "\">" + country.Value + "</option>");
                        }
                    }
                    else if (country.Key == "UserNameSafix")
                    {
                        if (!string.IsNullOrEmpty(SelSafix) && country.Id.Trim() == SelSafix.Trim())
                        {
                            sbSafixList.AppendLine("<option value=\"" + country.Id + "\" selected=\"selected\">" + country.Value + "</option>");
                        }
                        else
                        {
                            sbSafixList.AppendLine("<option value=\"" + country.Id + "\">" + country.Value + "</option>");
                        }
                    }
                    else if (country.Key == "DeliveryMethod")
                    {
                        if (!string.IsNullOrEmpty(SelDelivery) && country.Id.Trim() == SelDelivery.Trim())
                        {
                            sbPrefferedDeliveryMethodList.AppendLine("<option value=\"" + country.Id + "\" selected=\"selected\">" + country.Value + "</option>");
                        }
                        else
                        {
                            sbPrefferedDeliveryMethodList.AppendLine("<option value=\"" + country.Id + "\">" + country.Value + "</option>");
                        }
                    }
                    else if (country.Key == "PaymentMethod")
                    {
                        if (!string.IsNullOrEmpty(SelPayment) && country.Id.Trim() == SelPayment.Trim())
                        {
                            sbPrefferedPaymentMethodList.AppendLine("<option value=\"" + country.Id + "\" selected=\"selected\">" + country.Value + "</option>");
                        }
                        else
                        {
                            sbPrefferedPaymentMethodList.AppendLine("<option value=\"" + country.Id + "\">" + country.Value + "</option>");
                        }
                    }
                }
            }

            ViewBag.PrefferedDeliveryMethod = sbPrefferedDeliveryMethodList.ToString();
            ViewBag.PrefferedPaymentMethod  = sbPrefferedPaymentMethodList.ToString();
            ViewBag.GSTRegistrationType     = sbGSTRegistrationTypeList.ToString();
            ViewBag.Title = sbTitleList.ToString();
            ViewBag.Safix = sbSafixList.ToString();
        }
        public string Process(Entity entity, Dictionary <string, object> TemplateCache, bool globalUsePrivateSetters, string globalProjectNamespace, out string CurrentFileName)
        {
            Actions actions = new Actions();

            if (entity.HasUserOption("Entity_MarkAsSerializable") && entity.GetUserOptionValue <bool>("Entity_MarkAsSerializable"))
            {
                entity.MappedClass.EnsureHas()
                .AttributeNamed("Serializable")
                .Finish()
                .ApplyTo(actions);
            }
            List <string> propertyNamesFromReferences = entity.DirectedReferences.Where(r => r.FromEndEnabled).Select(d => d.FromName).ToList();
            List <string> propertyNamesFromComponents = entity.Components.Select(c => c.Name).ToList();

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

            foreach (var property in entity.Properties)
            {
                sb.AppendLine(PropertyTemplate.ProcessPropertyTemplate(entity, property));
            }

            List <ArchAngel.Providers.CodeProvider.DotNet.Property> codeProps = ProcessTemplateProperties(sb.ToString());
            Dictionary <ArchAngel.Providers.EntityModel.Model.EntityLayer.Property, ArchAngel.Providers.CodeProvider.DotNet.Property> propMap = new Dictionary <Property, ArchAngel.Providers.CodeProvider.DotNet.Property>();

            for (int i = 0; i < entity.Properties.Count(); i++)
            {
                propMap.Add(entity.Properties.ElementAt(i), codeProps[i]);
            }

            foreach (var property in entity.Properties)
            {
                //sb.AppendLine(PropertyTemplate.ProcessPropertyTemplate(entity, property));
                PropertyConstraintBuilder propertyConstraint = null;

                if (entity.ForeignKeyPropertiesToExclude.Contains(property))
                {
                    if (propertyNamesFromReferences.Contains(property.Name) ||
                        propertyNamesFromComponents.Contains(property.Name))
                    {
                        // Don't mark this property for removal, because it's actually going to be added by a reference or component further down.
                        continue;
                    }
                    propertyConstraint = entity.MappedClass.EnsureDoesNotHaveProperty(propMap[property].Name, property.OldNames);
                }
                else
                {
                    // Add property's current name to its old name list
                    if (property.OldNames.Count == 0 || !property.OldNames.Contains(propMap[property].Name))
                    {
                        property.OldNames.Add(propMap[property].Name);
                    }

                    propertyConstraint =
                        entity.MappedClass.EnsureHasProperty(propMap[property].Name, property.OldNames)
                        .WithType(propMap[property].DataType.Name.Replace(string.Format("{0}.Model.", globalProjectNamespace), ""))
                        .WithModifiers(propMap[property].Modifiers.ToArray())
                        .WithGetAccessorBody(propMap[property].GetAccessor.BodyText)
                        .WithSetAccessorBody(propMap[property].SetAccessor.BodyText);


                    //bool propertyUsePrivateSetter = property.HasUserOption("Property_UsePrivateSetter") && property.GetUserOptionValue<bool>("Property_UsePrivateSetter");

                    //if (propertyUsePrivateSetter || globalUsePrivateSetters)
                    if (propMap[property].SetAccessor.Modifier == "private")
                    {
                        propertyConstraint.WithSetAccessorAccessibility("private");
                    }

                    // Code insertions stuff for NHibernate Validator Attributes. Replaced with XML specs.
                    //if(property.MaximumLength.HasValue && property.MaximumLength > 0 && property.MaximumLength < int.MaxValue)
                    //{
                    //    propertyConstraint.WithAttribute("Length")
                    //        .WithParameter(property.MaximumLength.Value.ToString());
                    //}
                }
                propertyConstraint.ApplyTo(actions);
            }

            #region DirectedReferences

            sb = new System.Text.StringBuilder();

            foreach (var reference in entity.DirectedReferences)
            {
                sb.AppendLine(PropertyTemplate.ProcessReferenceTemplate(entity, reference));
            }

            List <ArchAngel.Providers.CodeProvider.DotNet.Property> codeRefProps = ProcessTemplateProperties(sb.ToString());
            Dictionary <ArchAngel.Providers.EntityModel.Model.EntityLayer.DirectedReference, ArchAngel.Providers.CodeProvider.DotNet.Property> refPropMap = new Dictionary <DirectedReference, ArchAngel.Providers.CodeProvider.DotNet.Property>();

            for (int i = 0; i < entity.DirectedReferences.Count(); i++)
            {
                refPropMap.Add(entity.DirectedReferences.ElementAt(i), codeRefProps[i]);
            }

            foreach (var reference in entity.DirectedReferences.Where(r => r.FromEndEnabled).OrderBy(r => r.FromName))
            {
                // Add reference's current name to its old name list
                if (reference.OldFromNames.Count == 0 || !reference.OldFromNames.Contains(refPropMap[reference].Name))
                {
                    reference.OldFromNames.Add(refPropMap[reference].Name);
                }

                var propertyConstraint = entity.MappedClass.EnsureHasProperty(refPropMap[reference].Name, reference.OldFromNames)
                                         .WithType(refPropMap[reference].DataType.Name.Replace(string.Format("{0}.Model.", globalProjectNamespace), ""))
                                         .WithModifiers(refPropMap[reference].Modifiers.ToArray())
                                         .WithGetAccessorBody(refPropMap[reference].GetAccessor.BodyText)
                                         .WithSetAccessorBody(refPropMap[reference].SetAccessor.BodyText);

                if (refPropMap[reference].SetAccessor.Modifier == "private")
                {
                    propertyConstraint.WithSetAccessorAccessibility("private");
                }

                propertyConstraint.ApplyTo(actions);
            }
            #endregion

            #region Component Definitions

            sb = new System.Text.StringBuilder();

            foreach (var component in entity.Components)
            {
                sb.AppendLine(PropertyTemplate.ProcessComponentTemplate(entity, component));
            }

            List <ArchAngel.Providers.CodeProvider.DotNet.Property> codeComponentProps = ProcessTemplateProperties(sb.ToString());
            Dictionary <ArchAngel.Providers.EntityModel.Model.EntityLayer.Component, ArchAngel.Providers.CodeProvider.DotNet.Property> componentPropMap = new Dictionary <Component, ArchAngel.Providers.CodeProvider.DotNet.Property>();

            for (int i = 0; i < entity.Components.Count(); i++)
            {
                componentPropMap.Add(entity.Components.ElementAt(i), codeComponentProps[i]);
            }

            foreach (var component in entity.Components.OrderBy(c => c.Name))
            {
                // Add component's current name to its old name list
                if (component.OldNames.Count == 0 || !component.OldNames.Contains(componentPropMap[component].Name))
                {
                    component.OldNames.Add(componentPropMap[component].Name);
                }

                var propertyConstraint = entity.MappedClass.EnsureHasProperty(componentPropMap[component].Name, component.OldNames)
                                         .WithType(componentPropMap[component].DataType.Name.Replace(string.Format("{0}.Model.", globalProjectNamespace), ""))
                                         .WithModifiers(componentPropMap[component].Modifiers.ToArray())
                                         .WithGetAccessorBody(componentPropMap[component].GetAccessor.BodyText)
                                         .WithSetAccessorBody(componentPropMap[component].SetAccessor.BodyText);

                if (componentPropMap[component].SetAccessor.Modifier == "private")
                {
                    propertyConstraint.WithSetAccessorAccessibility("private");
                }

                propertyConstraint.ApplyTo(actions);
            }

            #endregion

            // Load the existing C# file up
            var filename = entity.EntitySet.MappingSet.CodeParseResults.GetFilenameForParsedClass(entity.MappedClass);

            CurrentFileName = filename;

            string outputText;
            if (TemplateCache.ContainsKey(filename) ||
                !System.IO.File.Exists(filename))
            {
                outputText = actions.RunActions((string)TemplateCache[filename], entity.MappedClass.Controller.Root, false);
            }
            else
            {
                outputText = actions.RunActions(System.IO.File.ReadAllText(filename), entity.MappedClass.Controller.Root, true);
            }

            TemplateCache[filename] = outputText;

            return(outputText);
        }
示例#38
0
        /** Returns a debug string for this path.
         */
        public virtual string DebugString(PathLog logMode)
        {
            if (logMode == PathLog.None || (!error && logMode == PathLog.OnlyErrors))
            {
                return("");
            }

            //debugStringBuilder.Length = 0;

            System.Text.StringBuilder text = pathHandler.DebugStringBuilder;
            text.Length = 0;

            text.Append(error ? "Path Failed : " : "Path Completed : ");
            text.Append("Computation Time ");

            text.Append((duration).ToString(logMode == PathLog.Heavy ? "0.000 ms " : "0.00 ms "));
            text.Append("Searched Nodes ");
            text.Append(searchedNodes);

            if (!error)
            {
                text.Append(" Path Length ");
                text.Append(path == null ? "Null" : path.Count.ToString());

                if (logMode == PathLog.Heavy)
                {
                    text.Append("\nSearch Iterations " + searchIterations);

                    //text.Append ("\nBinary Heap size at complete: ");

                    // -2 because numberOfItems includes the next item to be added and item zero is not used
                    //text.Append (pathHandler.open == null ? "null" : (pathHandler.open.numberOfItems-2).ToString ());
                }

                /*"\nEnd node\n	G = "+p.endNode.g+"\n	H = "+p.endNode.h+"\n	F = "+p.endNode.f+"\n	Point	"+p.endPoint
                 +"\nStart Point = "+p.startPoint+"\n"+"Start Node graph: "+p.startNode.graphIndex+" End Node graph: "+p.endNode.graphIndex+
                 * "\nBinary Heap size at completion: "+(p.open == null ? "Null" : p.open.numberOfItems.ToString ())*/
            }

            if (error)
            {
                text.Append("\nError: ");
                text.Append(errorLog);
            }

            if (logMode == PathLog.Heavy && !AstarPath.IsUsingMultithreading)
            {
                text.Append("\nCallback references ");
                if (callback != null)
                {
                    text.Append(callback.Target.GetType().FullName).AppendLine();
                }
                else
                {
                    text.AppendLine("NULL");
                }
            }

            text.Append("\nPath Number ");
            text.Append(pathID);

            return(text.ToString());
        }
        public void DoGUI(HierarchyFrameDataView frameDataView, bool fetchData, ref bool updateViewLive, ProfilerViewType viewType)
        {
            using (m_DoGUIMarker.Auto())
            {
                if (Event.current.type != EventType.Layout && m_ThreadIndexDuringLastNonLayoutEvent != threadIndexInThreadNames)
                {
                    m_ThreadIndexDuringLastNonLayoutEvent = threadIndexInThreadNames;
                    EditorGUIUtility.ExitGUI();
                }
                InitIfNeeded();

                var isSearchAllowed = string.IsNullOrEmpty(treeView.searchString) || !(m_ProfilerWindow.ProfilerWindowOverheadIsAffectingProfilingRecordingData() && ProfilerDriver.deepProfiling);

                var isDataAvailable = frameDataView != null && frameDataView.valid;

                var showDetailedView = isDataAvailable && m_DetailedViewType != DetailedViewType.None;
                if (showDetailedView)
                {
                    SplitterGUILayout.BeginHorizontalSplit(m_DetailedViewSpliterState);
                }

                // Hierarchy view area
                GUILayout.BeginVertical();

                if (isDataAvailable && (threadIndex != frameDataView.threadIndex || threadName != frameDataView.threadName))
                {
                    SetFrameDataView(frameDataView);
                }

                DrawToolbar(frameDataView, showDetailedView, ref updateViewLive, viewType);

                if (!string.IsNullOrEmpty(dataAvailabilityMessage))
                {
                    GUIStyle style = BaseStyles.label;

                    if (dataAvailabilityMessage.Contains("PlayerSettings."))
                    {
                        // Don't do hyperlinks if we're in standalone profiler since we can't easily connect back to the main process.
                        if (UnityEditor.MPE.ProcessService.level == UnityEditor.MPE.ProcessLevel.Secondary)
                        {
                            dataAvailabilityMessage = Regex.Replace(dataAvailabilityMessage, @"\(<a playersettingslink=.*<\/a>\)", "");
                        }
                        else
                        {
                            style.richText              = true;
                            EditorGUI.hyperLinkClicked -= EditorGUI_OpenSettingsOnHyperlinkClicked;
                            EditorGUI.hyperLinkClicked += EditorGUI_OpenSettingsOnHyperlinkClicked;
                        }
                    }

                    var rect = GUILayoutUtility.GetRect(GUIContent.Temp(dataAvailabilityMessage), style);
                    EditorGUI.SelectableLabel(rect, dataAvailabilityMessage, style);
                }
                else if (!isDataAvailable)
                {
                    if (!fetchData && !updateViewLive)
                    {
                        GUILayout.Label(BaseStyles.liveUpdateMessage, BaseStyles.label);
                    }
                    else
                    {
                        GUILayout.Label(BaseStyles.noData, BaseStyles.label);
                    }
                }
                else if (!isSearchAllowed)
                {
                    GUILayout.Label(BaseStyles.disabledSearchText, BaseStyles.label);
                }
                else
                {
                    var rect = GUILayoutUtility.GetRect(GUIContent.none, GUIStyle.none, GUILayout.ExpandHeight(true), GUILayout.ExpandHeight(true));

                    m_TreeView.SetFrameDataView(frameDataView);
                    m_TreeView.OnGUI(rect, updateViewLive);

                    if (m_TreeView.HasSelection() && m_TreeView.proxySelectionInfo.hasProxySelection)
                    {
                        if (m_TreeView.proxySelectionInfo.cachedDisplayContent == null)
                        {
                            var diff = Math.Abs(m_TreeView.proxySelectionInfo.pathLengthDifferenceForProxy);
                            m_TreeView.proxySelectionInfo.cachedDisplayContent = new GUIContent(
                                BaseStyles.selectionExtraInfoHierarhcyView + string.Format(
                                    BaseStyles.proxySampleMessage,
                                    m_TreeView.proxySelectionInfo.nonProxyName, diff,
                                    diff == 1 ? BaseStyles.proxySampleMessageScopeSingular : BaseStyles.proxySampleMessageScopePlural),
                                BaseStyles.warningTriangle.image);
                        }
                        GUILayout.BeginHorizontal();
                        GUILayout.Box(m_TreeView.proxySelectionInfo.cachedDisplayContent, BaseStyles.selectionExtraInfoArea);
                        var rectForSampleStackButton = GUILayoutUtility.GetRect(BaseStyles.showDetailsDropdownContent, BaseStyles.tooltipDropdown, GUILayout.ExpandHeight(false), GUILayout.ExpandHeight(false));
                        if (GUI.Button(rectForSampleStackButton, BaseStyles.showDetailsDropdownContent, BaseStyles.tooltipDropdown))
                        {
                            var selection  = m_TreeView.GetSelection();
                            var selectedId = (selection != null && selection.Count > 0) ? selection[0] : ProfilerFrameDataHierarchyView.invalidTreeViewId;
                            if (selectedId >= 0)
                            {
                                var menu = new GenericMenu();

                                // Show Sample Selection:
                                var rawSampleIndices = new List <int>(frameDataView.GetItemMergedSamplesCount(selectedId));
                                frameDataView.GetItemRawFrameDataViewIndices(selectedId, rawSampleIndices);
                                var actualMarkerIdPath = new List <int>(frameDataView.GetItemDepth(selectedId));
                                using (var iterator = new RawFrameDataView(frameDataView.frameIndex, frameDataView.threadIndex))
                                {
                                    string name     = null;
                                    var    rawIndex = ProfilerTimelineGUI.GetItemMarkerIdPath(iterator, cpuModule, rawSampleIndices[0], ref name, ref actualMarkerIdPath);
                                }

                                var actualMarkerPath = new List <string>(actualMarkerIdPath.Count);
                                foreach (var id in actualMarkerIdPath)
                                {
                                    if ((frameDataView.GetMarkerFlags(id) & Unity.Profiling.LowLevel.MarkerFlags.AvailabilityEditor) != 0)
                                    {
                                        actualMarkerPath.Add(string.Format("EditorOnly [{0}]", frameDataView.GetMarkerName(id)));
                                    }
                                    else
                                    {
                                        actualMarkerPath.Add(frameDataView.GetMarkerName(id));
                                    }
                                }

                                // admittedly, it'd be nice to only generate the text if sample selection option was chosen...
                                // however, that would need to happen in an OnGui call and not within the callback of the generic menu,
                                // to be able to calculate the needed window size and avoid glitches on first displaying it.
                                // at least the user already clicked on the dropdown for this...

                                string selectedSampleStackText = null;
                                var    sampleStackSb           = new System.Text.StringBuilder();
                                if (m_TreeView.proxySelectionInfo.nonProxySampleStack != null && m_TreeView.proxySelectionInfo.nonProxySampleStack.Count > 0)
                                {
                                    for (int i = m_TreeView.proxySelectionInfo.nonProxySampleStack.Count - 1; i >= 0; i--)
                                    {
                                        sampleStackSb.AppendLine(m_TreeView.proxySelectionInfo.nonProxySampleStack[i]);
                                    }
                                    selectedSampleStackText = sampleStackSb.ToString();
                                }
                                string actualSampleStackText = null;
                                if (actualMarkerPath != null && actualMarkerPath.Count > 0)
                                {
                                    sampleStackSb.Clear();

                                    for (int i = actualMarkerPath.Count - 1; i >= 0; i--)
                                    {
                                        sampleStackSb.AppendLine(actualMarkerPath[i]);
                                    }
                                    actualSampleStackText = sampleStackSb.ToString();
                                }

                                var selectionSampleStackContent = selectedSampleStackText != null ? new GUIContent(selectedSampleStackText) : null;
                                var actualSampleStackContent    = actualSampleStackText != null ? new GUIContent(actualSampleStackText) : null;
                                var sampleStackWindowSize       = SelectedSampleStackWindow.CalculateSize(selectionSampleStackContent, actualSampleStackContent);
                                menu.AddItem(BaseStyles.showSelectedSampleStacks, false, () =>
                                {
                                    SelectedSampleStackWindow.ShowSampleStackWindow(GUIUtility.GUIToScreenRect(rectForSampleStackButton).position, sampleStackWindowSize, selectionSampleStackContent, actualSampleStackContent);
                                });
                                menu.DropDown(rectForSampleStackButton);
                            }
                        }
                        GUILayout.EndHorizontal();
                    }
                }

                GUILayout.EndVertical();

                if (showDetailedView)
                {
                    GUILayout.BeginVertical();

                    // Detailed view area
                    EditorGUILayout.BeginHorizontal(BaseStyles.toolbar);

                    DrawDetailedViewPopup();
                    GUILayout.FlexibleSpace();

                    cpuModule.DrawOptionsMenuPopup();
                    EditorGUILayout.EndHorizontal();

                    switch (m_DetailedViewType)
                    {
                    case DetailedViewType.Objects:
                        detailedObjectsView.DoGUI(BaseStyles.header, frameDataView, m_TreeView.GetSelection());
                        break;

                    case DetailedViewType.CallersAndCallees:
                        detailedCallsView.DoGUI(BaseStyles.header, frameDataView, m_TreeView.GetSelection());
                        break;
                    }

                    GUILayout.EndVertical();

                    SplitterGUILayout.EndHorizontalSplit();
                }

                HandleKeyboardEvents();
            }
        }
示例#40
0
        public string BuildStatistics()
        {
            // First just calculate the column widths so we can format them nicely.  We'll save the formatted tick counts
            // so we don't have to regenerate them later.

            string[] formattedTime   = new string[timingRecords.Count];
            int      nameColumnWidth = 0;
            int      timeColumnWidth = 0;

            for (int i = 0; i < timingRecords.Count; i++)
            {
                var timingRecord = timingRecords[i];

                formattedTime[i] = string.Format("{0:#,0}ms", timingRecord.Milliseconds);

                if (formattedTime[i].Length > timeColumnWidth)
                {
                    timeColumnWidth = formattedTime[i].Length;
                }

                int          nameWidth = timingRecord.Name.Length;
                TimingRecord parent    = GetParent(timingRecord);

                while (parent != null)
                {
                    nameWidth += 2;
                    parent     = GetParent(parent);
                }

                if (nameWidth > nameColumnWidth)
                {
                    nameColumnWidth = nameWidth;
                }
            }


            // Now generate the output

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

            for (int i = 0; i < timingRecords.Count; i++)
            {
                var timingRecord = timingRecords[i];

                int          nameWidth = 0;
                TimingRecord parent    = GetParent(timingRecord);

                while (parent != null)
                {
                    output.Append("- ");
                    nameWidth += 2;
                    parent     = GetParent(parent);
                }

                output.Append(timingRecord.Name);
                nameWidth += timingRecord.Name.Length;

                output.Append(' ', nameColumnWidth + 2 - nameWidth);
                output.Append(' ', timeColumnWidth - formattedTime[i].Length);

                output.Append(formattedTime[i]);

                parent = GetParent(timingRecord);
                if (parent != null)
                {
                    output.Append(string.Format(" {0,3}%", ((timingRecord.Milliseconds * 100) / parent.Milliseconds)));
                }

                output.AppendLine();
            }

            return(output.ToString());
        }
示例#41
0
 public void DLog(object data)
 {
     log.AppendLine(data.ToString());
     Debug.Log(data, null);
     NLog(data.ToString());
 }
示例#42
0
        private static bool GenerateShaderPass(PBRMasterNode masterNode, Pass pass, GenerationMode mode, SurfaceMaterialOptions materialOptions, ShaderGenerator result)
        {
            var templateLocation = Path.Combine(Path.Combine(Path.Combine(HDEditorUtils.GetHDRenderPipelinePath(), "Editor"), "ShaderGraph"), pass.TemplateName);

            if (!File.Exists(templateLocation))
            {
                // TODO: produce error here
                return(false);
            }

            // grab all of the active nodes
            var activeNodeList = ListPool <INode> .Get();

            NodeUtils.DepthFirstCollectNodesFromNode(activeNodeList, masterNode, NodeUtils.IncludeSelf.Include, pass.PixelShaderSlots);

            // graph requirements describe what the graph itself requires
            var graphRequirements = ShaderGraphRequirements.FromNodes(activeNodeList, ShaderStageCapability.Fragment);

            ShaderStringBuilder graphNodeFunctions = new ShaderStringBuilder();

            graphNodeFunctions.IncreaseIndent();
            var functionRegistry = new FunctionRegistry(graphNodeFunctions);

            // Build the list of active slots based on what the pass requires
            // TODO: this can be a shared function -- From here through GraphUtil.GenerateSurfaceDescription(..)
            var activeSlots = new List <MaterialSlot>();

            foreach (var id in pass.PixelShaderSlots)
            {
                MaterialSlot slot = masterNode.FindSlot <MaterialSlot>(id);
                if (slot != null)
                {
                    activeSlots.Add(slot);
                }
            }

            // build the graph outputs structure to hold the results of each active slots (and fill out activeFields to indicate they are active)
            string graphInputStructName           = "SurfaceDescriptionInputs";
            string graphOutputStructName          = "SurfaceDescription";
            string graphEvalFunctionName          = "SurfaceDescriptionFunction";
            ShaderStringBuilder graphEvalFunction = new ShaderStringBuilder();
            ShaderStringBuilder graphOutputs      = new ShaderStringBuilder();
            PropertyCollector   graphProperties   = new PropertyCollector();

            // build the graph outputs structure, and populate activeFields with the fields of that structure
            HashSet <string> activeFields = new HashSet <string>();

            GraphUtil.GenerateSurfaceDescriptionStruct(graphOutputs, activeSlots, true);
            //GraphUtil.GenerateSurfaceDescriptionStruct(graphOutputs, activeSlots, true, graphOutputStructName, activeFields);

            // Build the graph evaluation code, to evaluate the specified slots
            GraphUtil.GenerateSurfaceDescriptionFunction(
                activeNodeList,
                masterNode,
                masterNode.owner as AbstractMaterialGraph,
                graphEvalFunction,
                functionRegistry,
                graphProperties,
                graphRequirements,  // TODO : REMOVE UNUSED
                mode,
                graphEvalFunctionName,
                graphOutputStructName,
                null,
                activeSlots,
                graphInputStructName);

            var blendCode     = new ShaderStringBuilder();
            var cullCode      = new ShaderStringBuilder();
            var zTestCode     = new ShaderStringBuilder();
            var zWriteCode    = new ShaderStringBuilder();
            var stencilCode   = new ShaderStringBuilder();
            var colorMaskCode = new ShaderStringBuilder();

            HDSubShaderUtilities.BuildRenderStatesFromPassAndMaterialOptions(pass, materialOptions, blendCode, cullCode, zTestCode, zWriteCode, stencilCode, colorMaskCode);

            if (masterNode.twoSided.isOn)
            {
                activeFields.Add("DoubleSided");
                if (pass.ShaderPassName != "SHADERPASS_VELOCITY")   // HACK to get around lack of a good interpolator dependency system
                {                                                   // we need to be able to build interpolators using multiple input structs
                                                                    // also: should only require isFrontFace if Normals are required...
                    activeFields.Add("DoubleSided.Mirror");         // TODO: change this depending on what kind of normal flip you want..
                    activeFields.Add("FragInputs.isFrontFace");     // will need this for determining normal flip mode
                }
            }

            if (pass.PixelShaderSlots != null)
            {
                foreach (var slotId in pass.PixelShaderSlots)
                {
                    var slot = masterNode.FindSlot <MaterialSlot>(slotId);
                    if (slot != null)
                    {
                        var rawSlotName    = slot.RawDisplayName().ToString();
                        var descriptionVar = string.Format("{0}.{1}", graphOutputStructName, rawSlotName);
                        activeFields.Add(descriptionVar);
                    }
                }
            }

            var packedInterpolatorCode = new ShaderGenerator();
            var graphInputs            = new ShaderGenerator();

            HDRPShaderStructs.Generate(
                packedInterpolatorCode,
                graphInputs,
                graphRequirements,
                pass.RequiredFields,
                CoordinateSpace.World,
                activeFields);

            // debug output all active fields
            var interpolatorDefines = new ShaderGenerator();
            {
                interpolatorDefines.AddShaderChunk("// ACTIVE FIELDS:");
                foreach (string f in activeFields)
                {
                    interpolatorDefines.AddShaderChunk("//   " + f);
                }
            }

            ShaderGenerator defines = new ShaderGenerator();
            {
                defines.AddShaderChunk(string.Format("#define SHADERPASS {0}", pass.ShaderPassName), true);
                if (pass.ExtraDefines != null)
                {
                    foreach (var define in pass.ExtraDefines)
                    {
                        defines.AddShaderChunk(define);
                    }
                }
                defines.AddGenerator(interpolatorDefines);
            }

            var shaderPassIncludes = new ShaderGenerator();

            if (pass.Includes != null)
            {
                foreach (var include in pass.Includes)
                {
                    shaderPassIncludes.AddShaderChunk(include);
                }
            }


            // build graph code
            var graph = new ShaderGenerator();

            graph.AddShaderChunk("// Graph Inputs");
            graph.Indent();
            graph.AddGenerator(graphInputs);
            graph.Deindent();
            graph.AddShaderChunk("// Graph Outputs");
            graph.Indent();
            graph.AddShaderChunk(graphOutputs.ToString());
            //graph.AddGenerator(graphOutputs);
            graph.Deindent();
            graph.AddShaderChunk("// Graph Properties (uniform inputs)");
            graph.AddShaderChunk(graphProperties.GetPropertiesDeclaration(1));
            graph.AddShaderChunk("// Graph Node Functions");
            graph.AddShaderChunk(graphNodeFunctions.ToString());
            graph.AddShaderChunk("// Graph Evaluation");
            graph.Indent();
            graph.AddShaderChunk(graphEvalFunction.ToString());
            //graph.AddGenerator(graphEvalFunction);
            graph.Deindent();

            // build the hash table of all named fragments      TODO: could make this Dictionary<string, ShaderGenerator / string>  ?
            Dictionary <string, string> namedFragments = new Dictionary <string, string>();

            namedFragments.Add("${Defines}", defines.GetShaderString(2, false));
            namedFragments.Add("${Graph}", graph.GetShaderString(2, false));
            namedFragments.Add("${LightMode}", pass.LightMode);
            namedFragments.Add("${PassName}", pass.Name);
            namedFragments.Add("${Includes}", shaderPassIncludes.GetShaderString(2, false));
            namedFragments.Add("${InterpolatorPacking}", packedInterpolatorCode.GetShaderString(2, false));
            namedFragments.Add("${Blending}", blendCode.ToString());
            namedFragments.Add("${Culling}", cullCode.ToString());
            namedFragments.Add("${ZTest}", zTestCode.ToString());
            namedFragments.Add("${ZWrite}", zWriteCode.ToString());
            namedFragments.Add("${Stencil}", stencilCode.ToString());
            namedFragments.Add("${ColorMask}", colorMaskCode.ToString());
            namedFragments.Add("${LOD}", materialOptions.lod.ToString());
            namedFragments.Add("${VariantDefines}", GetVariantDefines(masterNode));

            // process the template to generate the shader code for this pass   TODO: could make this a shared function
            string[] templateLines            = File.ReadAllLines(templateLocation);
            System.Text.StringBuilder builder = new System.Text.StringBuilder();
            foreach (string line in templateLines)
            {
                ShaderSpliceUtil.PreprocessShaderCode(line, activeFields, namedFragments, builder);
                builder.AppendLine();
            }

            result.AddShaderChunk(builder.ToString(), false);

            return(true);
        }
示例#43
0
 /// <summary> Wrapper for AppendLine(). Appends a newline to the end of the StringBuilder, resizing if necessary. </summary>
 public StringBuilder AppendLine()
 {
     str.AppendLine(); return(this);
 }
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!Page.IsPostBack)
     {
         try
         {
             lblmsg.Text = string.Empty;
             CargarDetalle();
         }
         catch (Exception ex)
         {
             lblmsg.Text = "Error interno en el sistema contacte a su administrador " + " Detalle:" + ex.Message;
             msgError.Clear();
             msgError.AppendLine("Fecha:" + DateTime.Now.ToString());
             msgError.AppendLine("Descripción:" + ex.Message);
             msgError.AppendLine("Detalle:" + ex.StackTrace);
             log.Error(msgError.ToString());
         }
     }
 }
        static string ConvertNodesToYarnText(IEnumerable <Loader.NodeInfo> nodes)
        {
            var sb = new System.Text.StringBuilder();

            var properties = typeof(Loader.NodeInfo).GetProperties();

            foreach (var node in nodes)
            {
                foreach (var property in properties)
                {
                    // ignore the body attribute
                    if (property.Name == "body")
                    {
                        continue;
                    }

                    // piggy-back off the JsonIgnoreAttribute to sense items that should not be serialised
                    if (property.GetCustomAttributes(typeof(JsonIgnoreAttribute), false).Length > 0)
                    {
                        continue;
                    }

                    var field = property.Name;

                    string value;

                    var propertyType = property.PropertyType;
                    if (propertyType.IsAssignableFrom(typeof(string)))
                    {
                        value = (string)property.GetValue(node, null);

                        // avoid storing nulls when we could store the empty string instead
                        if (value == null)
                        {
                            value = "";
                        }
                    }
                    else if (propertyType.IsAssignableFrom(typeof(int)))
                    {
                        value = ((int)property.GetValue(node, null)).ToString(CultureInfo.InvariantCulture);
                    }
                    else if (propertyType.IsAssignableFrom(typeof(Loader.NodeInfo.Position)))
                    {
                        var position = (Loader.NodeInfo.Position)property.GetValue(node, null);

                        value = string.Format(CultureInfo.InvariantCulture, "{0},{1}", position.x, position.y);
                    }
                    else
                    {
                        YarnSpinnerConsole.Error(string.Format(CultureInfo.CurrentCulture, "Internal error: Node {0}'s property {1} has unsupported type {2}", node.title, property.Name, propertyType.FullName));

                        // will never be run, but prevents the compiler being mean about us not returning a value
                        throw new Exception();
                    }

                    var header = string.Format(CultureInfo.InvariantCulture, "{0}: {1}", field, value);

                    sb.AppendLine(header);
                }
                // now write the body
                sb.AppendLine("---");

                sb.AppendLine(node.body);

                sb.AppendLine("===");
            }

            return(sb.ToString());
        }
示例#46
0
        private void StoragePermissonGranted()
        {
            if (!_downloadStarted)
            {
                _downloadStarted = true;
                // Before we do anything, are the files we expect already here and
                // delivered (presumably by Market)
                // For free titles, this is probably worth doing. (so no Market
                // request is necessary)
                bool delivered = AreExpansionFilesDelivered();

                if (delivered)
                {
                    StartActivity(typeof(ActivityMain));
                    Finish();
                    return;
                }

                if (!IsFromGooglePlay(this))
                {
                    PackageInfo packageInfo    = PackageManager.GetPackageInfo(PackageName, 0);
                    int         packageVersion = 0;
                    if (packageInfo != null)
                    {
                        packageVersion = packageInfo.VersionCode;
                    }
                    string obbFileName = string.Format(CultureInfo.InvariantCulture, "main.{0}.{1}.obb", packageVersion, PackageName);

                    Java.IO.File[] obbDirs;
                    // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression
                    if (Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat)
                    {
                        obbDirs = GetObbDirs();
                    }
                    else
                    {
                        obbDirs = new[] { ObbDir };
                    }

                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    foreach (Java.IO.File dir in obbDirs)
                    {
                        if (dir != null && !string.IsNullOrEmpty(dir.AbsolutePath))
                        {
                            if (sb.Length > 0)
                            {
                                sb.AppendLine();
                            }
                            sb.Append(@"'");
                            sb.Append(dir.AbsolutePath);
                            sb.Append(@"'");
                        }
                    }

                    string obbDirsName = sb.ToString();
                    if (string.IsNullOrEmpty(obbDirsName))
                    {
                        obbDirsName = "-";
                    }

                    string      message     = string.Format(CultureInfo.InvariantCulture, GetString(Resource.String.exp_down_obb_missing), obbFileName, obbDirsName);
                    AlertDialog alertDialog = new AlertDialog.Builder(this)
                                              .SetMessage(message)
                                              .SetTitle(Resource.String.alert_title_error)
                                              .SetNeutralButton(Resource.String.button_ok, (s, e) => { })
                                              .Show();
                    alertDialog.DismissEvent += (sender, args) =>
                    {
                        if (!_activityActive)
                        {
                            return;
                        }
                        Finish();
                    };
                    return;
                }

                if (!GetExpansionFiles())
                {
                    InitializeDownloadUi();
                }

                if (_activityActive)
                {
                    _downloaderServiceConnection?.Connect(this);
                }
            }
        }
示例#47
0
        async Task <byte[]> UnaryServerMethod <TRequest, TResponse>(byte[] request, ServerCallContext context)
        {
            var isErrorOrInterrupted = false;
            var serviceContext       = new ServiceContext(ServiceType, MethodInfo, AttributeLookup, this.MethodType, context, resolver, logger, this)
            {
                Request = request
            };

            byte[] response = emptyBytes;
            try
            {
                logger.BeginInvokeMethod(serviceContext, request, typeof(TRequest));
                if (enableCurrentContext)
                {
                    ServiceContext.currentServiceContext.Value = serviceContext;
                }
                await this.methodBody(serviceContext).ConfigureAwait(false);

                response = serviceContext.Result ?? emptyBytes;
            }
            catch (ReturnStatusException ex)
            {
                isErrorOrInterrupted = true;
                context.Status       = ex.ToStatus();
                response             = emptyBytes;
            }
            catch (Exception ex)
            {
                isErrorOrInterrupted = true;
                if (isReturnExceptionStackTraceInErrorDetail)
                {
                    // Trim data.
                    var msg       = ex.ToString();
                    var lineSplit = msg.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
                    var sb        = new System.Text.StringBuilder();
                    for (int i = 0; i < lineSplit.Length; i++)
                    {
                        if (!(lineSplit[i].Contains("System.Runtime.CompilerServices") ||
                              lineSplit[i].Contains("直前に例外がスローされた場所からのスタック トレースの終わり") ||
                              lineSplit[i].Contains("End of stack trace from the previous location where the exception was thrown")
                              ))
                        {
                            sb.AppendLine(lineSplit[i]);
                        }
                        if (sb.Length >= 5000)
                        {
                            sb.AppendLine("----Omit Message(message size is too long)----");
                            break;
                        }
                    }
                    var str = sb.ToString();

                    context.Status = new Status(StatusCode.Unknown, str);
                    LogError(ex, context);
                    response = emptyBytes;
                }
                else
                {
                    throw;
                }
            }
            finally
            {
                logger.EndInvokeMethod(serviceContext, response, typeof(TResponse), (DateTime.UtcNow - serviceContext.Timestamp).TotalMilliseconds, isErrorOrInterrupted);
            }

            return(response);
        }
示例#48
0
        Execute(
            Bam.Core.ExecutionContext context,
            string executablePath,
            Bam.Core.StringArray commandLineArguments,
            string workingDirectory = null,
            Bam.Core.StringArray inheritedEnvironmentVariables = null,
            System.Collections.Generic.Dictionary <string, Bam.Core.TokenizedStringArray> addedEnvironmentVariables = null,
            string useResponseFileOption = null)
        {
            var processStartInfo = new System.Diagnostics.ProcessStartInfo();

            processStartInfo.FileName    = executablePath;
            processStartInfo.ErrorDialog = true;
            if (null != workingDirectory)
            {
                processStartInfo.WorkingDirectory = workingDirectory;
            }

            var cachedEnvVars = new System.Collections.Generic.Dictionary <string, string>();

            // first get the inherited environment variables from the system environment
            if (null != inheritedEnvironmentVariables)
            {
                int envVarCount;
                if (inheritedEnvironmentVariables.Count == 1 &&
                    inheritedEnvironmentVariables[0] == "*")
                {
                    foreach (System.Collections.DictionaryEntry envVar in processStartInfo.EnvironmentVariables)
                    {
                        cachedEnvVars.Add(envVar.Key as string, envVar.Value as string);
                    }
                }
                else if (inheritedEnvironmentVariables.Count == 1 &&
                         System.Int32.TryParse(inheritedEnvironmentVariables[0], out envVarCount) &&
                         envVarCount < 0)
                {
                    envVarCount += processStartInfo.EnvironmentVariables.Count;
                    foreach (var envVar in processStartInfo.EnvironmentVariables.Cast <System.Collections.DictionaryEntry>().OrderBy(item => item.Key))
                    {
                        cachedEnvVars.Add(envVar.Key as string, envVar.Value as string);
                        --envVarCount;
                        if (0 == envVarCount)
                        {
                            break;
                        }
                    }
                }
                else
                {
                    foreach (var envVar in inheritedEnvironmentVariables)
                    {
                        if (!processStartInfo.EnvironmentVariables.ContainsKey(envVar))
                        {
                            Bam.Core.Log.Info("Environment variable '{0}' does not exist", envVar);
                            continue;
                        }
                        cachedEnvVars.Add(envVar, processStartInfo.EnvironmentVariables[envVar]);
                    }
                }
            }
            processStartInfo.EnvironmentVariables.Clear();
            if (null != inheritedEnvironmentVariables)
            {
                foreach (var envVar in cachedEnvVars)
                {
                    processStartInfo.EnvironmentVariables[envVar.Key] = envVar.Value;
                }
            }
            if (null != addedEnvironmentVariables)
            {
                foreach (var envVar in addedEnvironmentVariables)
                {
                    processStartInfo.EnvironmentVariables[envVar.Key] = envVar.Value.ToString(System.IO.Path.PathSeparator);
                }
            }

            processStartInfo.UseShellExecute        = false;
            processStartInfo.RedirectStandardOutput = true;
            processStartInfo.RedirectStandardError  = true;
            processStartInfo.RedirectStandardInput  = true;

            var arguments = commandLineArguments.ToString(' ');

            if (Bam.Core.OSUtilities.IsWindowsHosting)
            {
                //TODO: should this include the length of the executable path too?
                if (arguments.Length >= 32767)
                {
                    if (null == useResponseFileOption)
                    {
                        throw new Bam.Core.Exception("Command line is {0} characters long, but response files are not supported by the tool {1}", arguments.Length, executablePath);
                    }

                    var responseFilePath = System.IO.Path.GetTempFileName();
                    using (System.IO.StreamWriter writer = new System.IO.StreamWriter(responseFilePath))
                    {
                        Bam.Core.Log.DebugMessage("Written response file {0} containing:\n{1}", responseFilePath, arguments);
                        writer.WriteLine(arguments);
                    }

                    arguments = System.String.Format("{0}{1}", useResponseFileOption, responseFilePath);
                }
            }
            processStartInfo.Arguments = arguments;

            Bam.Core.Log.Detail("{0} {1}", processStartInfo.FileName, processStartInfo.Arguments);

            // useful debugging of the command line processor
            Bam.Core.Log.DebugMessage("Working directory: '{0}'", processStartInfo.WorkingDirectory);
            if (processStartInfo.EnvironmentVariables.Count > 0)
            {
                Bam.Core.Log.DebugMessage("Environment variables:");
                foreach (var envVar in processStartInfo.EnvironmentVariables.Cast <System.Collections.DictionaryEntry>().OrderBy(item => item.Key))
                {
                    Bam.Core.Log.DebugMessage("\t{0} = {1}", envVar.Key, envVar.Value);
                }
            }

            System.Diagnostics.Process process = null;
            int exitCode = -1;

            try
            {
                process                     = new System.Diagnostics.Process();
                process.StartInfo           = processStartInfo;
                process.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(context.OutputDataReceived);
                process.ErrorDataReceived  += new System.Diagnostics.DataReceivedEventHandler(context.ErrorDataReceived);
                process.Start();
                process.StandardInput.Close();
            }
            catch (System.ComponentModel.Win32Exception ex)
            {
                throw new Bam.Core.Exception("'{0}': process filename '{1}'", ex.Message, processStartInfo.FileName);
            }
            if (null != process)
            {
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
                // TODO: need to poll for an external cancel op?
                // poll for the process to exit, as some processes seem to get stuck (hdiutil attach, for example)
                while (!process.HasExited)
                {
                    process.WaitForExit(2000);
                }
                // this additional WaitForExit appears to be needed in order to finish reading the output and error streams asynchronously
                // without it, output is missing from a Native build when executed in many threads
                process.WaitForExit();

                exitCode = process.ExitCode;
                //Bam.Core.Log.DebugMessage("Tool exit code: {0}", exitCode);
                process.Close();
            }

            if (exitCode != 0)
            {
                var message = new System.Text.StringBuilder();
                message.AppendFormat("Command failed: {0} {1}", processStartInfo.FileName, processStartInfo.Arguments);
                message.AppendLine();
                message.AppendFormat("Command exit code: {0}", exitCode);
                message.AppendLine();
                throw new Bam.Core.Exception(message.ToString());
            }
        }
示例#49
0
        public String LocalSetupGet(my.MySqlClient.MySqlConnection conn)
        {
            string strQuery = String.Empty;

            strQuery = string.Format("SELECT username, domain, ipaddress, computer_name, process_name, process_path, process_starttime, processid, process_description, process_exittime, version, productname, companyname, semester, process_path_commandline, sid, fullname, department, role, idactivity FROM app_performance.activity WHERE process_exittime BETWEEN '2016-10-06 11:00:30' AND '2016-11-09 20:21:30'");

            my.MySqlClient.MySqlCommand cmd = new my.MySqlClient.MySqlCommand(strQuery, conn);


            my.MySqlClient.MySqlDataReader myReader = null;



            try
            {
                myReader = cmd.ExecuteReader();
                int n = 0;

                try {
                    System.IO.Directory.CreateDirectory(@"C:\bithubReports");
                } catch (Exception ex) {
                    return(ex.Message.ToString());
                }

                //var filepath = @"C:\bithubReports\report.txt";

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


                while (myReader.Read())
                {
                    HttpContext.Current.Response.Write(myReader.GetString(0) + "\n");
                    string result = "";
                    string name, domain, ip, cpu, proc, procPath, procStart, procID, procDesc, procExit, v, pName, cName, sem, ppcl, sid, fName, dep, role, id;
                    if (myReader.IsDBNull(0))
                    {
                        name = " ";
                    }
                    else
                    {
                        name = String.Format("{0}", myReader.GetString(0));
                    }
                    if (myReader.IsDBNull(1))
                    {
                        domain = " ";
                    }
                    else
                    {
                        domain = String.Format("{0}", myReader.GetString(1));
                    }
                    if (myReader.IsDBNull(2))
                    {
                        ip = " ";
                    }
                    else
                    {
                        ip = String.Format("{0}", myReader.GetString(2));
                    }
                    if (myReader.IsDBNull(3))
                    {
                        cpu = " ";
                    }
                    else
                    {
                        cpu = String.Format("{0}", myReader.GetString(3));
                    }
                    if (myReader.IsDBNull(4))
                    {
                        proc = " ";
                    }
                    else
                    {
                        proc = String.Format("{0}", myReader.GetString(4));
                    }
                    if (myReader.IsDBNull(5))
                    {
                        procPath = " ";
                    }
                    else
                    {
                        procPath = String.Format("{0}", myReader.GetString(5));
                    }
                    if (myReader.IsDBNull(6))
                    {
                        procStart = " ";
                    }
                    else
                    {
                        procStart = String.Format("{0}", myReader.GetDateTime(6));
                    }
                    if (myReader.IsDBNull(7))
                    {
                        procID = " ";
                    }
                    else
                    {
                        procID = String.Format("{0}", myReader.GetInt64(7));
                    }
                    if (myReader.IsDBNull(8))
                    {
                        procDesc = " ";
                    }
                    else
                    {
                        procDesc = String.Format("{0}", myReader.GetString(8));
                    }
                    if (myReader.IsDBNull(9))
                    {
                        procExit = " ";
                    }
                    else
                    {
                        procExit = String.Format("{0}", myReader.GetDateTime(9));
                    }
                    if (myReader.IsDBNull(10))
                    {
                        v = " ";
                    }
                    else
                    {
                        v = String.Format("{0}", myReader.GetString(10));
                    }
                    if (myReader.IsDBNull(11))
                    {
                        pName = " ";
                    }
                    else
                    {
                        pName = String.Format("{0}", myReader.GetString(11));
                    }
                    if (myReader.IsDBNull(12))
                    {
                        cName = " ";
                    }
                    else
                    {
                        cName = String.Format("{0}", myReader.GetString(12));
                    }
                    if (myReader.IsDBNull(13))
                    {
                        sem = " ";
                    }
                    else
                    {
                        sem = String.Format("{0}", myReader.GetString(13));
                    }
                    if (myReader.IsDBNull(14))
                    {
                        ppcl = " ";
                    }
                    else
                    {
                        ppcl = String.Format("{0}", myReader.GetString(14));
                    }
                    if (myReader.IsDBNull(15))
                    {
                        sid = " ";
                    }
                    else
                    {
                        sid = String.Format("{0}", myReader.GetString(15));
                    }
                    if (myReader.IsDBNull(16))
                    {
                        fName = " ";
                    }
                    else
                    {
                        fName = String.Format("{0}", myReader.GetString(16));
                    }
                    if (myReader.IsDBNull(17))
                    {
                        dep = " ";
                    }
                    else
                    {
                        dep = String.Format("{0}", myReader.GetString(17));
                    }
                    if (myReader.IsDBNull(18))
                    {
                        role = " ";
                    }
                    else
                    {
                        role = String.Format("{0}", myReader.GetString(18));
                    }
                    if (myReader.IsDBNull(19))
                    {
                        id = " ";
                    }
                    else
                    {
                        id = String.Format("{0}", myReader.GetString(19));
                    }

                    result = name + "," + domain + "," + ip + "," + cpu + "," + proc + "," + procPath + "," + procStart + "," + procID + "," + procDesc + "," + procExit + "," + v + "," + pName + "," + cName + "," + sem + "," + ppcl + "," + sid + "," + fName + "," + dep + "," + role + "," + id;

                    string line = result;

                    try{
                        csv.AppendLine(line);
                    } catch (Exception ex) {
                        return(ex.Message.ToString());
                    }
                    n = 0;
                }


                try{
                    System.IO.File.WriteAllText(filepath, csv.ToString());
                } catch (Exception ex) {
                    return(ex.Message.ToString());
                }
            }
            catch (Exception ex)
            {
                return(ex.Message.ToString());
            }

            try
            {
                String email = "*****@*****.**";
                send_email(email);
            }
            catch (Exception ex)
            {
                return(ex.Message.ToString());
            }

            if (myReader != null)
            {
                if (myReader.IsClosed == false)
                {
                    myReader.Close();
                    myReader.Dispose();
                }
            }


            if (conn != null)
            {
                if (conn.State == System.Data.ConnectionState.Open)
                {
                    conn.Close();
                    conn.Dispose();
                }
            }
            HttpContext.Current.Response.Write("Success");
            return("Success");
        }
示例#50
0
        /// <summary>
        /// override <see cref="v_AICompanion.StateRoutine()"/>
        /// ps: this rotine work with internal while loop
        /// </summary>
        /// <returns></returns>
        protected IEnumerator CompanionStateRoutine()
        {
            while (this.enabled)
            {
                yield return(new WaitForEndOfFrame());

                System.Text.StringBuilder debugString = new System.Text.StringBuilder();
                debugString.AppendLine("----DEBUG----");
                debugString.AppendLine("Agressive : " + agressiveAtFirstSight);

                CheckIsOnNavMesh();
                CheckAutoCrouch();
                SetTarget();

                //Companion Behavior (override Aicontroller Behavior)
                switch (companionState)
                {
                    #region Companion rotine
                case CompanionState.Follow:
                    if (canSeeTarget && nearOfCompanion)
                    {
                        yield return(StartCoroutine(base.Chase()));
                    }
                    else
                    {
                        yield return(StartCoroutine(FollowCompanion()));
                    }

                    debugString.AppendLine(canSeeTarget && nearOfCompanion ? "Chase/Follow" : "Follow");

                    break;

                case CompanionState.MoveTo:
                    if (canSeeTarget)
                    {
                        yield return(StartCoroutine(base.Chase()));
                    }
                    else
                    {
                        yield return(StartCoroutine(MoveTo()));
                    }

                    debugString.AppendLine(canSeeTarget ? "Chase/MoveTo" : "MoveTo");
                    break;

                case CompanionState.Stay:
                    if (canSeeTarget)
                    {
                        yield return(StartCoroutine(base.Chase()));
                    }
                    else
                    {
                        yield return(StartCoroutine(Stay()));
                    }
                    debugString.AppendLine(canSeeTarget ? "Chase/Stay" : "Stay");
                    break;

                    #endregion
                case CompanionState.None:
                    //Aicontroller Behavior
                    #region Ai controller Normal Rotine
                    debugString.AppendLine("None : using normal AI routine");
                    switch (currentState)
                    {
                    case AIStates.Idle:
                        debugString.AppendLine("idle");
                        yield return(StartCoroutine(base.Idle()));

                        break;

                    case AIStates.Chase:
                        yield return(StartCoroutine(base.Chase()));

                        break;
                    }
                    break;
                    #endregion
                }
                if (debugUIText != null && debug)
                {
                    debugUIText.text = debugString.ToString();
                }
            }
        }
示例#51
0
        //Only use this when exceptions in the api.
        //
        public static string GetContextData()
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            if (HttpContext.Current != null)
            {
                //Session
                if (HttpContext.Current.Session != null)
                {
                    foreach (string key in HttpContext.Current.Session.Keys)
                    {
                        sb.AppendLine($"Session: Key:{key} Value:{HttpContext.Current.Session[key]}");
                    }
                }

                //Cookie
                if (HttpContext.Current.Request.Cookies != null)
                {
                    foreach (string cookie in HttpContext.Current.Request.Cookies)
                    {
                        sb.AppendLine($"Cookie: Key:{HttpContext.Current.Request.Cookies[cookie].Name} Value:{HttpContext.Current.Request.Cookies[cookie].Value}");
                    }
                }


                //Form
                if (HttpContext.Current.Request.Form != null)
                {
                    foreach (string item in HttpContext.Current.Request.Form)
                    {
                        sb.AppendLine($"Form: Key:{item} Value:{HttpContext.Current.Request.Form[item]}");
                    }
                }

                //URL
                string[] urlParms = HttpContext.Current.Request.Url.Query.Split('&');
                if (urlParms.Length > 0)
                {
                    foreach (string parm in urlParms)
                    {
                        string[] de  = parm.Split('=');
                        string   val = de.Length == 2 ? de[1] : string.Empty;
                        sb.AppendLine($"URL: Key:{de[0]} Value:{val}");
                    }
                }

                sb.AppendLine($"Method: {HttpContext.Current.Request.HttpMethod}");
                sb.AppendLine($"IsAuthenticated: {HttpContext.Current.Request.IsAuthenticated}");
                sb.AppendLine($"IsLocal: {HttpContext.Current.Request.IsLocal}");
                sb.AppendLine($"IsSecureConnection: {HttpContext.Current.Request.IsSecureConnection}");
                sb.AppendLine($"RequestType: {HttpContext.Current.Request.RequestType}");
                sb.AppendLine($"Url: {HttpContext.Current.Request.Url}");
                sb.AppendLine($"UrlReferrer: {HttpContext.Current.Request.UrlReferrer}");
                sb.AppendLine($"UserAgent: {HttpContext.Current.Request.UserAgent}");
                sb.AppendLine($"UserHostAddress: {HttpContext.Current.Request.UserHostAddress}");

                if (HttpContext.Current.Request.ServerVariables.Count > 0)
                {
                    foreach (string sVar in HttpContext.Current.Request.ServerVariables)
                    {
                        if (sVar != "ALL_HTTP" && sVar != "ALL_RAW" && sVar != "AUTH_PASSWORD")
                        {
                            sb.AppendLine($"Server: Key:{sVar} Value:{HttpContext.Current.Request.ServerVariables[sVar]}");
                        }
                    }
                }
            }

            return(sb.ToString());
        }
示例#52
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();
            var array_output_count = 0U;

            s.Append(base.AsString());
            numSubShapes = (uint)subShapes.Count;
            s.AppendLine($"      Num Sub Shapes:  {numSubShapes}");
            array_output_count = 0;
            for (var i3 = 0; i3 < subShapes.Count; i3++)
            {
                if (!verbose && (array_output_count > Nif.MAXARRAYDUMP))
                {
                    s.AppendLine("<Data Truncated. Use verbose mode to see complete listing.>");
                    break;
                }
                if (!verbose && (array_output_count > Nif.MAXARRAYDUMP))
                {
                    break;
                }
                s.AppendLine($"        Sub Shapes[{i3}]:  {subShapes[i3]}");
                array_output_count++;
            }
            s.AppendLine($"      Unknown Int:  {material.unknownInt}");
            s.AppendLine($"      Material:  {material.material_ob}");
            s.AppendLine($"      Material:  {material.material_fo}");
            s.AppendLine($"      Material:  {material.material_sk}");
            s.AppendLine($"      Radius:  {radius}");
            s.AppendLine($"      Unknown Int 1:  {unknownInt1}");
            s.AppendLine($"      Unknown Float 1:  {unknownFloat1}");
            s.AppendLine($"      Data:  {childShapeProperty.data}");
            s.AppendLine($"      Size:  {childShapeProperty.size}");
            s.AppendLine($"      Capacity and Flags:  {childShapeProperty.capacityAndFlags}");
            s.AppendLine($"      Unknown Byte 1:  {unknownByte1}");
            s.AppendLine($"      Unknown Float 2:  {unknownFloat2}");
            return(s.ToString());
        }
        private async void TakeMapOfflineButton_Click(object sender, EventArgs e)
        {
            // Show the loading indicator.
            _loadingIndicator.StartAnimating();

            // Create a path for the output mobile map.
            string tempPath = $"{Path.GetTempPath()}";

            string[] outputFolders = Directory.GetDirectories(tempPath, "NapervilleWaterNetwork*");

            // Loop through the folder names and delete them.
            foreach (string dir in outputFolders)
            {
                try
                {
                    // Delete the folder.
                    Directory.Delete(dir, true);
                }
                catch (Exception)
                {
                    // Ignore exceptions (files might be locked, for example).
                }
            }

            // Create a new folder for the output mobile map.
            string packagePath = Path.Combine(tempPath, @"NapervilleWaterNetwork");
            int    num         = 1;

            while (Directory.Exists(packagePath))
            {
                packagePath = Path.Combine(tempPath, @"NapervilleWaterNetwork" + num);
                num++;
            }

            // Create the output directory.
            Directory.CreateDirectory(packagePath);

            try
            {
                // Show the loading overlay while the job is running.
                _statusLabel.Text = "Taking map offline...";

                // Create an offline map task with the current (online) map.
                OfflineMapTask takeMapOfflineTask = await OfflineMapTask.CreateAsync(_myMapView.Map);

                // Create the default parameters for the task, pass in the area of interest.
                GenerateOfflineMapParameters parameters = await takeMapOfflineTask.CreateDefaultGenerateOfflineMapParametersAsync(_areaOfInterest);

                // Create the job with the parameters and output location.
                _generateOfflineMapJob = takeMapOfflineTask.GenerateOfflineMap(parameters, packagePath);

                // Handle the progress changed event for the job.
                _generateOfflineMapJob.ProgressChanged += OfflineMapJob_ProgressChanged;

                // Await the job to generate geodatabases, export tile packages, and create the mobile map package.
                GenerateOfflineMapResult results = await _generateOfflineMapJob.GetResultAsync();

                // Check for job failure (writing the output was denied, e.g.).
                if (_generateOfflineMapJob.Status != JobStatus.Succeeded)
                {
                    // Report failure to the user.
                    UIAlertController messageAlert = UIAlertController.Create("Error", "Failed to take the map offline.", UIAlertControllerStyle.Alert);
                    messageAlert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                    PresentViewController(messageAlert, true, null);
                }

                // Check for errors with individual layers.
                if (results.LayerErrors.Any())
                {
                    // Build a string to show all layer errors.
                    System.Text.StringBuilder errorBuilder = new System.Text.StringBuilder();
                    foreach (KeyValuePair <Layer, Exception> layerError in results.LayerErrors)
                    {
                        errorBuilder.AppendLine(string.Format("{0} : {1}", layerError.Key.Id, layerError.Value.Message));
                    }

                    // Show layer errors.
                    UIAlertController messageAlert = UIAlertController.Create("Error", errorBuilder.ToString(), UIAlertControllerStyle.Alert);
                    messageAlert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                    PresentViewController(messageAlert, true, null);
                }

                // Display the offline map.
                _myMapView.Map = results.OfflineMap;

                // Apply the original viewpoint for the offline map.
                _myMapView.SetViewpoint(new Viewpoint(_areaOfInterest));

                // Enable map interaction so the user can explore the offline data.
                _myMapView.InteractionOptions.IsEnabled = true;

                // Change the title and disable the "Take map offline" button.
                _statusLabel.Text             = "Map is offline";
                _takeMapOfflineButton.Enabled = false;
            }
            catch (TaskCanceledException)
            {
                // Generate offline map task was canceled.
                UIAlertController messageAlert = UIAlertController.Create("Canceled", "Taking map offline was canceled", UIAlertControllerStyle.Alert);
                messageAlert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                PresentViewController(messageAlert, true, null);
            }
            catch (Exception ex)
            {
                // Exception while taking the map offline.
                UIAlertController messageAlert = UIAlertController.Create("Error", ex.Message, UIAlertControllerStyle.Alert);
                messageAlert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                PresentViewController(messageAlert, true, null);
            }
            finally
            {
                // Hide the loading overlay when the job is done.
                _loadingIndicator.StopAnimating();
            }
        }
示例#54
0
 internal static void SaveConfig()
 {
     try
     {
         CultureInfo Culture = CultureInfo.InvariantCulture;
         System.Text.StringBuilder Builder = new System.Text.StringBuilder();
         Builder.AppendLine("; Options");
         Builder.AppendLine("; =======");
         Builder.AppendLine("; This file was automatically generated. Please modify only if you know what you're doing.");
         Builder.AppendLine("; Test Plugin specific options file");
         Builder.AppendLine();
         Builder.AppendLine("[clock]");
         Builder.AppendLine("is_display = " + IsDisplayClock.ToString(Culture));
         Builder.AppendLine();
         Builder.AppendLine("[speed]");
         Builder.AppendLine("is_display = " + IsDisplaySpeed.ToString(Culture));
         Builder.AppendLine("display_mode = " + SpeedDisplayMode.ToString(Culture));
         Builder.AppendLine();
         Builder.AppendLine("[gradient]");
         Builder.AppendLine("is_display = " + IsDisplayGradient.ToString(Culture));
         Builder.AppendLine("display_mode = " + GradientDisplayMode.ToString(Culture));
         Builder.AppendLine();
         Builder.AppendLine("[dist_next_station]");
         Builder.AppendLine("is_display = " + IsDisplayDistNextStation.ToString(Culture));
         Builder.AppendLine("display_mode = " + DistNextStationDisplayMode.ToString(Culture));
         Builder.AppendLine();
         Builder.AppendLine("[fps]");
         Builder.AppendLine("is_display = " + IsDisplayFps.ToString(Culture));
         string configFile = OpenBveApi.Path.CombineFile(FileSystem.SettingsFolder, "1.5.0/options_ddp.cfg");
         System.IO.File.WriteAllText(configFile, Builder.ToString(), new System.Text.UTF8Encoding(true));
     }
     catch
     {
         MessageBox.Show("An error occured whilst saving the options to disk." + System.Environment.NewLine +
                         "Please check you have write permission.");
     }
 }
示例#55
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();
            var array_output_count = 0U;

            s.Append(base.AsString());
            numDataLayers = (uint)dataLayers.Count;
            numStripsData = (uint)stripsData.Count;
            s.AppendLine($"      Unknown Int:  {material.unknownInt}");
            s.AppendLine($"      Material:  {material.material_ob}");
            s.AppendLine($"      Material:  {material.material_fo}");
            s.AppendLine($"      Material:  {material.material_sk}");
            s.AppendLine($"      Radius:  {radius}");
            array_output_count = 0;
            for (var i3 = 0; i3 < 5; i3++)
            {
                if (!verbose && (array_output_count > Nif.MAXARRAYDUMP))
                {
                    s.AppendLine("<Data Truncated. Use verbose mode to see complete listing.>");
                    break;
                }
                if (!verbose && (array_output_count > Nif.MAXARRAYDUMP))
                {
                    break;
                }
                s.AppendLine($"        Unused[{i3}]:  {unused[i3]}");
                array_output_count++;
            }
            s.AppendLine($"      Grow By:  {growBy}");
            s.AppendLine($"      Scale:  {scale}");
            s.AppendLine($"      Num Strips Data:  {numStripsData}");
            array_output_count = 0;
            for (var i3 = 0; i3 < stripsData.Count; i3++)
            {
                if (!verbose && (array_output_count > Nif.MAXARRAYDUMP))
                {
                    s.AppendLine("<Data Truncated. Use verbose mode to see complete listing.>");
                    break;
                }
                if (!verbose && (array_output_count > Nif.MAXARRAYDUMP))
                {
                    break;
                }
                s.AppendLine($"        Strips Data[{i3}]:  {stripsData[i3]}");
                array_output_count++;
            }
            s.AppendLine($"      Num Data Layers:  {numDataLayers}");
            array_output_count = 0;
            for (var i3 = 0; i3 < dataLayers.Count; i3++)
            {
                if (!verbose && (array_output_count > Nif.MAXARRAYDUMP))
                {
                    s.AppendLine("<Data Truncated. Use verbose mode to see complete listing.>");
                    break;
                }
                s.AppendLine($"        Layer:  {dataLayers[i3].layer_ob}");
                s.AppendLine($"        Layer:  {dataLayers[i3].layer_fo}");
                s.AppendLine($"        Layer:  {dataLayers[i3].layer_sk}");
                s.AppendLine($"        Flags and Part Number:  {dataLayers[i3].flagsAndPartNumber}");
                s.AppendLine($"        Group:  {dataLayers[i3].group}");
            }
            return(s.ToString());
        }
示例#56
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();
            var array_output_count = 0U;

            s.Append(base.AsString());
            numVertices = (ushort)vertices.Count;
            s.AppendLine($"      Group ID:  {groupId}");
            if ((!IsDerivedType(NiPSysData.TYPE)))
            {
                s.AppendLine($"        Num Vertices:  {numVertices}");
            }
            if (IsDerivedType(NiPSysData.TYPE))
            {
                s.AppendLine($"        BS Max Vertices:  {bsMaxVertices}");
            }
            s.AppendLine($"      Keep Flags:  {keepFlags}");
            s.AppendLine($"      Compress Flags:  {compressFlags}");
            s.AppendLine($"      Has Vertices:  {hasVertices}");
            if (hasVertices)
            {
                array_output_count = 0;
                for (var i4 = 0; i4 < vertices.Count; i4++)
                {
                    if (!verbose && (array_output_count > Nif.MAXARRAYDUMP))
                    {
                        s.AppendLine("<Data Truncated. Use verbose mode to see complete listing.>");
                        break;
                    }
                    if (!verbose && (array_output_count > Nif.MAXARRAYDUMP))
                    {
                        break;
                    }
                    s.AppendLine($"          Vertices[{i4}]:  {vertices[i4]}");
                    array_output_count++;
                }
            }
            s.AppendLine($"      Vector Flags:  {vectorFlags}");
            s.AppendLine($"      BS Vector Flags:  {bsVectorFlags}");
            s.AppendLine($"      Material CRC:  {materialCrc}");
            s.AppendLine($"      Has Normals:  {hasNormals}");
            if (hasNormals)
            {
                array_output_count = 0;
                for (var i4 = 0; i4 < normals.Count; i4++)
                {
                    if (!verbose && (array_output_count > Nif.MAXARRAYDUMP))
                    {
                        s.AppendLine("<Data Truncated. Use verbose mode to see complete listing.>");
                        break;
                    }
                    if (!verbose && (array_output_count > Nif.MAXARRAYDUMP))
                    {
                        break;
                    }
                    s.AppendLine($"          Normals[{i4}]:  {normals[i4]}");
                    array_output_count++;
                }
            }
            if ((hasNormals && ((vectorFlags | bsVectorFlags) & 4096)))
            {
                array_output_count = 0;
                for (var i4 = 0; i4 < tangents.Count; i4++)
                {
                    if (!verbose && (array_output_count > Nif.MAXARRAYDUMP))
                    {
                        s.AppendLine("<Data Truncated. Use verbose mode to see complete listing.>");
                        break;
                    }
                    if (!verbose && (array_output_count > Nif.MAXARRAYDUMP))
                    {
                        break;
                    }
                    s.AppendLine($"          Tangents[{i4}]:  {tangents[i4]}");
                    array_output_count++;
                }
                array_output_count = 0;
                for (var i4 = 0; i4 < bitangents.Count; i4++)
                {
                    if (!verbose && (array_output_count > Nif.MAXARRAYDUMP))
                    {
                        s.AppendLine("<Data Truncated. Use verbose mode to see complete listing.>");
                        break;
                    }
                    if (!verbose && (array_output_count > Nif.MAXARRAYDUMP))
                    {
                        break;
                    }
                    s.AppendLine($"          Bitangents[{i4}]:  {bitangents[i4]}");
                    array_output_count++;
                }
            }
            s.AppendLine($"      Center:  {center}");
            s.AppendLine($"      Radius:  {radius}");
            array_output_count = 0;
            for (var i3 = 0; i3 < 13; i3++)
            {
                if (!verbose && (array_output_count > Nif.MAXARRAYDUMP))
                {
                    s.AppendLine("<Data Truncated. Use verbose mode to see complete listing.>");
                    break;
                }
                if (!verbose && (array_output_count > Nif.MAXARRAYDUMP))
                {
                    break;
                }
                s.AppendLine($"        Unknown 13 shorts[{i3}]:  {unknown13Shorts[i3]}");
                array_output_count++;
            }
            s.AppendLine($"      Has Vertex Colors:  {hasVertexColors}");
            if (hasVertexColors)
            {
                array_output_count = 0;
                for (var i4 = 0; i4 < vertexColors.Count; i4++)
                {
                    if (!verbose && (array_output_count > Nif.MAXARRAYDUMP))
                    {
                        s.AppendLine("<Data Truncated. Use verbose mode to see complete listing.>");
                        break;
                    }
                    if (!verbose && (array_output_count > Nif.MAXARRAYDUMP))
                    {
                        break;
                    }
                    s.AppendLine($"          Vertex Colors[{i4}]:  {vertexColors[i4]}");
                    array_output_count++;
                }
            }
            s.AppendLine($"      Num UV Sets:  {numUvSets}");
            s.AppendLine($"      Has UV:  {hasUv}");
            array_output_count = 0;
            for (var i3 = 0; i3 < uvSets.Count; i3++)
            {
                if (!verbose && (array_output_count > Nif.MAXARRAYDUMP))
                {
                    s.AppendLine("<Data Truncated. Use verbose mode to see complete listing.>");
                    break;
                }
                for (var i4 = 0; i4 < uvSets[i3].Count; i4++)
                {
                    if (!verbose && (array_output_count > Nif.MAXARRAYDUMP))
                    {
                        break;
                    }
                    s.AppendLine($"          UV Sets[{i4}]:  {uvSets[i3][i4]}");
                    array_output_count++;
                }
            }
            s.AppendLine($"      Consistency Flags:  {consistencyFlags}");
            s.AppendLine($"      Additional Data:  {additionalData}");
            return(s.ToString());
        }
示例#57
0
        Main(
            string[] args)
        {
#if false
            // take control of Ctrl+C
            System.Console.CancelKeyPress += new System.ConsoleCancelEventHandler(HandleCancellation);
#endif

            try
            {
                var totalTimeProfile          = new Core.TimeProfile(Core.ETimingProfiles.TimedTotal);
                var processCommandLineProfile = new Core.TimeProfile(Core.ETimingProfiles.ProcessCommandLine);

                totalTimeProfile.StartProfile();
                processCommandLineProfile.StartProfile();

                var verbosityLevel = (Core.EVerboseLevel)Core.CommandLineProcessor.Evaluate(new Core.Options.VerbosityLevel());
                switch (verbosityLevel)
                {
                case Core.EVerboseLevel.None:
                case Core.EVerboseLevel.Info:
                case Core.EVerboseLevel.Detail:
                case Core.EVerboseLevel.Full:
                    Core.Graph.Instance.VerbosityLevel = verbosityLevel;
                    break;

                default:
                    throw new Core.Exception("Unrecognized verbosity level, {0}", verbosityLevel);
                }

                if (Core.CommandLineProcessor.Evaluate(new Core.Options.PrintHelp()))
                {
                    CommandLineArgumentHelper.PrintHelp();
                    return;
                }

                if (Core.CommandLineProcessor.Evaluate(new Core.Options.PrintVersion()))
                {
                    CommandLineArgumentHelper.PrintVersion();
                    return;
                }

                if (Core.CommandLineProcessor.Evaluate(new Core.Options.CreateDebugProject()))
                {
                    DebugProject.Create();
                    return;
                }

                if (Core.CommandLineProcessor.Evaluate(new Core.Options.MakePackage()))
                {
                    Core.PackageUtilities.MakePackage();
                    return;
                }

                if (Core.CommandLineProcessor.Evaluate(new Core.Options.AddDependentPackage()))
                {
                    Core.PackageUtilities.AddDependentPackage();
                    return;
                }

                if (Core.CommandLineProcessor.Evaluate(new Core.Options.ShowDefinitionFile()))
                {
                    Core.PackageUtilities.IdentifyAllPackages(allowDuplicates: true, enforceBamAssemblyVersions: false);
                    Core.Graph.Instance.MasterPackage.Show();
                    return;
                }

                // configure
                Core.Graph.Instance.BuildRoot = Core.CommandLineProcessor.Evaluate(new Core.Options.BuildRoot());
                Core.Graph.Instance.Mode      = Core.CommandLineProcessor.Evaluate(new Core.Options.BuildMode());
                if (null == Core.Graph.Instance.Mode)
                {
                    throw new Core.Exception("No build mode specified");
                }

                var configs          = new Core.Array <Core.Environment>();
                var requestedConfigs = Core.CommandLineProcessor.Evaluate(new Core.Options.BuildConfigurations());
                if (0 == requestedConfigs.Count)
                {
                    // default
                    requestedConfigs.Add(new Core.StringArray("debug"));
                }
                foreach (var configOption in requestedConfigs)
                {
                    foreach (var config in configOption)
                    {
                        var env = new Core.Environment();
                        env.Configuration = Core.Configuration.FromString(config);
                        configs.Add(env);
                    }
                }

                processCommandLineProfile.StopProfile();

                Core.EntryPoint.Execute(configs);

                totalTimeProfile.StopProfile();
            }
            catch (Core.Exception exception)
            {
                Core.Exception.DisplayException(exception);
                System.Environment.ExitCode = -1;
            }
            catch (System.Exception exception)
            {
                var message = new System.Text.StringBuilder();
                message.AppendFormat("{0} not handled: {1}", exception.GetType().ToString(), exception.Message);
                message.AppendLine();
                message.AppendLine(exception.StackTrace);
                Core.Log.ErrorMessage(message.ToString());
                System.Environment.ExitCode = -2;
            }
            finally
            {
                if (Core.Graph.Instance.BuildEnvironments.Count > 0)
                {
                    Core.Log.Info((0 == System.Environment.ExitCode) ? "\nBuild Succeeded" : "\nBuild Failed");

                    if (Core.CommandLineProcessor.Evaluate(new Core.Options.PrintStatistics()))
                    {
                        Core.Statistics.Display();
                    }

                    Core.Log.DebugMessage("Exit code {0}", System.Environment.ExitCode);
                }
            }
        }
示例#58
0
        /// <summary>
        /// Compiles and load scripts from a C# or VB.NET source code file.
        /// </summary>
        /// <param name="filename">The path to the code file to load.</param>
        /// <returns><c>true</c> on success, <c>false</c> otherwise</returns>
        bool LoadScriptsFromSource(string filename)
        {
            var compilerOptions = new System.CodeDom.Compiler.CompilerParameters();

            compilerOptions.CompilerOptions         = "/optimize";
            compilerOptions.GenerateInMemory        = true;
            compilerOptions.IncludeDebugInformation = true;
            compilerOptions.ReferencedAssemblies.Add("System.dll");
            compilerOptions.ReferencedAssemblies.Add("System.Core.dll");
            compilerOptions.ReferencedAssemblies.Add("System.Drawing.dll");
            compilerOptions.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            compilerOptions.ReferencedAssemblies.Add("System.XML.dll");
            compilerOptions.ReferencedAssemblies.Add("System.XML.Linq.dll");
            compilerOptions.ReferencedAssemblies.Add(typeof(ScriptDomain).Assembly.Location);

            Assembly scriptApi = null;
            // Support specifying the API version to be used in the file name like "script.3.cs"
            string apiVersionString = Path.GetExtension(Path.GetFileNameWithoutExtension(filename));

            if (!string.IsNullOrEmpty(apiVersionString) && int.TryParse(apiVersionString.Substring(1), out int apiVersion))
            {
                scriptApi = CurrentDomain.scriptApis.FirstOrDefault(x => x.GetName().Version.Major == apiVersion);
            }
            // Reference the oldest scripting API by default to stay compatible with existing scripts
            if (scriptApi is null)
            {
                scriptApi = scriptApis.First();
            }
            compilerOptions.ReferencedAssemblies.Add(scriptApi.Location);

            string extension = Path.GetExtension(filename);

            System.CodeDom.Compiler.CodeDomProvider compiler = null;

            if (extension.Equals(".cs", StringComparison.OrdinalIgnoreCase))
            {
                compiler = new Microsoft.CSharp.CSharpCodeProvider();
                compilerOptions.CompilerOptions += " /unsafe";
            }
            else if (extension.Equals(".vb", StringComparison.OrdinalIgnoreCase))
            {
                compiler = new Microsoft.VisualBasic.VBCodeProvider();
            }
            else
            {
                return(false);
            }

            System.CodeDom.Compiler.CompilerResults compilerResult = compiler.CompileAssemblyFromFile(compilerOptions, filename);

            if (!compilerResult.Errors.HasErrors)
            {
                Log.Message(Log.Level.Debug, "Successfully compiled ", Path.GetFileName(filename), ".");
                return(LoadScriptsFromAssembly(compilerResult.CompiledAssembly, filename));
            }
            else
            {
                var errors = new System.Text.StringBuilder();

                foreach (System.CodeDom.Compiler.CompilerError error in compilerResult.Errors)
                {
                    errors.Append("   at line ");
                    errors.Append(error.Line);
                    errors.Append(": ");
                    errors.Append(error.ErrorText);
                    errors.AppendLine();
                }

                Log.Message(Log.Level.Error, "Failed to compile ", Path.GetFileName(filename), " with ", compilerResult.Errors.Count.ToString(), " error(s):", Environment.NewLine, errors.ToString());
                return(false);
            }
        }
示例#59
0
 private void WriteLine(string text)
 {
     __sb.AppendLine(text);
 }
        /// <summary>
        /// データ書き出し
        /// </summary>
        /// <param name="configurationFolder"></param>
        public override void Export(string directoryName, string savePath, List <ConfigurationFile> cnfigurationFile)
        {
            //ファイル名
            string cfgFilename = Common.File.CombinePath(savePath, directoryName + "_ScienceDefs" + ".cfg");

            //格納用
            var exportData = new System.Text.StringBuilder();


            //サイエンスレポート用書き出し用データ作成
            foreach (ConfigurationFile cfgFile in cnfigurationFile)
            {
                foreach (Text.TextData textData in cfgFile.TextDataList)
                {
                    if (textData.DataType == DataType.ScienceDefs)
                    {
                        ///サイエンスレポート
                        var tData = (Text.TextDataScienceDefs)textData;


                        if (tData.TranslateTextList.Count >= 1)
                        {
                            if (directoryName.Equals(VanillaDirectoryName, StringComparison.CurrentCultureIgnoreCase))
                            {
                                //(Vanilla
                                exportData.AppendLine(String.Format("@EXPERIMENT_DEFINITION:HAS[#id[{0}]]", tData.ID));
                            }
                            else
                            {
                                //MOD
                                exportData.AppendLine(String.Format("@EXPERIMENT_DEFINITION:HAS[#id[{0}]]:NEEDS[{1}]:FINAL", tData.ID, directoryName));
                            }
                            exportData.AppendLine("{");
                            exportData.AppendLine("\t//Title");
                            exportData.AppendLine("\t//\t" + tData.Title);

                            exportData.AppendLine("\t@RESULTS");
                            exportData.AppendLine("\t{");

                            foreach (Translate.TranslateText translateText in tData.TranslateTextList)
                            {
                                var tText = (Translate.TranslateTextScienceDefs)translateText;

                                exportData.AppendLine("\t//English Text");
                                exportData.AppendLine("\t//\t" + String.Format(@"{0},{1} = {2}", tText.Result.ResultText, tText.Result.ResultIndex, tText.SourceText));
                                exportData.AppendLine("\t//Japanese Text");
                                if (tText.JapaneseText.Equals("") || tText.JapaneseText.Equals(tText.SourceText))
                                {
                                    exportData.AppendLine("\t//\t" + String.Format(@"@{0},{1} = ", tText.Result.ResultText, tText.Result.ResultIndex));
                                }
                                else
                                {
                                    if (!tText.Comment.Equals(""))
                                    {
                                        exportData.AppendLine("\t//\t" + tText.Comment);
                                    }
                                    exportData.AppendLine("\t\t" + String.Format(@"@{0},{1} = {2}", tText.Result.ResultText, tText.Result.ResultIndex, tText.JapaneseText));
                                }
                                exportData.AppendLine("");
                            }

                            exportData.AppendLine("\t}");
                            exportData.AppendLine("}");
                            exportData.AppendLine("");
                        }
                    }
                }
            }


            //データがあればファイル書き出し
            this.DataWrite(cfgFilename, exportData);
        }