예제 #1
0
		/// <summary>
		/// <para>生成一个新的URL,将会增加或修改参数,还有可能会忽略一些值。</para>
		/// <para>说明:这个方法不会修改现有的查询字符串参数。</para>
		/// </summary>
		/// <param name="name">参数名称</param>
		/// <param name="newValue">新的参数值</param>
		/// <param name="skipKeys">要忽略的Key名称</param>
		/// <returns>新的URL字符串</returns>
		public string GetNewUrl(string name, string newValue, params string[] skipKeys)
		{
			System.Text.StringBuilder sb = new System.Text.StringBuilder();

			int n = this.Count;
			bool isExist = false;

			for( int i = 0; i < n; i++ ) {
				string key = this.GetKey(i);

				if( skipKeys != null && skipKeys.Length > 0 ) {
					if( Array.IndexOf<string>(skipKeys, key) >= 0 )
						continue;
				}

				if( string.Compare(key, name, true) == 0 ) {
					isExist = true;
					if( !string.IsNullOrEmpty(newValue) )
						sb.AppendFormat("&{0}={1}", key, HttpUtility.UrlEncode(newValue));
				}
				else {
					sb.AppendFormat("&{0}={1}", key, HttpUtility.UrlEncode(this[i]));
				}
			}

			if( (!isExist) && (!string.IsNullOrEmpty(name)) && (!string.IsNullOrEmpty(newValue)) )
				sb.AppendFormat("&{0}={1}", name, newValue);

			return string.Concat(this.m_requestPath,
				(sb.Length > 0 ? string.Concat("?", sb.ToString().Substring(1)) : string.Empty));
		}
예제 #2
0
        private static MvcForm FormHelper(this AjaxHelper ajaxHelper, string formId, string formAction, bool isAjax, string eventName, string updateId, string cssClassNames, 
            IDictionary<string, object> htmlAttributes)
        {
            var tagBuilder = new TagBuilder("form");

            tagBuilder.MergeAttributes(htmlAttributes);
            tagBuilder.MergeAttribute("action", formAction);
            tagBuilder.MergeAttribute("method", @"post");

            var metadataBuilder = new System.Text.StringBuilder();
            metadataBuilder.AppendFormat("IsAjax: {0}", isAjax.ToJavascriptString());
            
            if(!string.IsNullOrEmpty(eventName))
                metadataBuilder.AppendFormat(", EventName: '{0}'", eventName);

            if (!string.IsNullOrEmpty(updateId))
                metadataBuilder.AppendFormat(", UpdateId: '{0}'", updateId);

            var metadata = "{" + metadataBuilder.ToString() + "}";

            tagBuilder.MergeAttribute("autocomplete", @"off");
            tagBuilder.MergeAttribute("class", "jqAjaxForm " + (!string.IsNullOrEmpty(cssClassNames) ? cssClassNames : string.Empty) + @" " + metadata);
            tagBuilder.GenerateId(formId);
            ajaxHelper.ViewContext.Writer.Write(tagBuilder.ToString(TagRenderMode.StartTag));

            var form = new MvcForm(ajaxHelper.ViewContext);
            if (ajaxHelper.ViewContext.ClientValidationEnabled)
                ajaxHelper.ViewContext.FormContext.FormId = tagBuilder.Attributes["id"];

            return form;
        }
예제 #3
0
		//=========================================================================================
		/// <summary>Получить текстовое описание ожидаемых литералов.</summary>
		internal string GetExpectationToString()
		{
			if (_ExpectationString == null)
			{
				System.Text.StringBuilder sb = new System.Text.StringBuilder("Expected ");
				if (this.Entries.Count == 0)
				{
					if (this.ElseState != null)
						sb.AppendFormat("'{0}'", this.ElseState.Name);
					else
						throw new NullReferenceException("Links for " + this.Name);
				}
				bool bFirst = true;
				foreach (var oKey in this.Entries.Keys)
				{
					if (bFirst)
						bFirst = false;
					else
						sb.Append(" or ");
					sb.AppendFormat("'{0}'", oKey);
				}
				this._ExpectationString = sb.ToString();
			}
			return this._ExpectationString;
		}
        public static void logon(contentManagerService1 cmService,
			string userName, string userPassword, string userNamespace)
        {
            try
            {
                System.Text.StringBuilder credentialXML = new System.Text.StringBuilder("<credential>" );
                credentialXML.AppendFormat( "<namespace>{0}</namespace>", userNamespace );
                credentialXML.AppendFormat( "<username>{0}</username>", userName );
                credentialXML.AppendFormat( "<password>{0}</password>", userPassword );
                credentialXML.Append( "</credential>" );

                //TODO - encode this, don't just toString it.
                string encodedCredentials = credentialXML.ToString ();
                xmlEncodedXML xmlEncodedCredentials = new xmlEncodedXML();
                xmlEncodedCredentials.Value = encodedCredentials;

                cmService.logon(xmlEncodedCredentials, null);

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

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

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

            return sb.ToString();
        }
예제 #6
0
        /// <summary>
        /// 支付宝绑定
        /// </summary>
        /// <param name="OrderId"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        protected string BindZhiFuBao(string orderId, object status, object zhifu, object xiafei)
        {
            System.Text.StringBuilder zhifubao = new System.Text.StringBuilder();

            Eyousoft_yhq.Model.OrderState OrderStatus = (Eyousoft_yhq.Model.OrderState)status;

            Eyousoft_yhq.Model.PaymentState PayStatus = (Eyousoft_yhq.Model.PaymentState)zhifu;

            Eyousoft_yhq.Model.ConSumState ConSumState = (Eyousoft_yhq.Model.ConSumState)xiafei;

            if (Eyousoft_yhq.Model.OrderState.待付款 == OrderStatus || Eyousoft_yhq.Model.OrderState.已成交 == OrderStatus)
            {
                if (PayStatus == Eyousoft_yhq.Model.PaymentState.已支付)
                {
                    zhifubao.Append("<span class=\"yifu\">" + ConSumState.ToString() + "</span>");
                }
                else
                {
                    zhifubao.AppendFormat("<a data-id=\"{0}\" class=\"yueZF\" href=\"javascript:;\"><span class=\"daifu\">账户支付</span></a>", orderId);
                    zhifubao.AppendFormat("<a href=\"http://{1}/AppPage/weixin/GoPay.aspx?OrderId={0}\"><span class=\"daifu\">支付宝支付</span></a>", orderId, HttpContext.Current.Request.Url.Host);
                }
            }
            else
            {
                zhifubao.AppendFormat("<span class=\"daifu\">{0}</span>", OrderStatus.ToString());
            }

            return zhifubao.ToString();
        }
예제 #7
0
파일: Converter.cs 프로젝트: Chrisso/Tools
        private static string GetHidimHeader(string filename, int height)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            sb.Append("hidim is torrents!");
            sb.AppendFormat("i{0}e", height);
            sb.AppendFormat("{0}:{1}", Path.GetFileName(filename).Length, Path.GetFileName(filename));

            try
            {
                using (FileStream fs = File.OpenRead(filename))
                {
                    byte[] hash = new System.Security.Cryptography.SHA1Managed().ComputeHash(fs);
                    string sha1 = BitConverter.ToString(hash).Replace("-", "");
                    sb.AppendFormat("{0}:{1}", sha1.Length, sha1);
                }
            }
            catch (Exception)
            {
                sb.AppendFormat("{0}:{1}", 40, "deadbeefdeadbeefdeadbeefdeadbeebadcoffee");
            }

            sb.AppendFormat("i{0}e", new FileInfo(filename).Length);

            return sb.ToString();
        }
예제 #8
0
        protected string GetDetailHTML(NFMT.Common.UserModel user, List<NFMT.WareHouse.Model.StockOutDetail> details)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            NFMT.WareHouse.Model.Stock stock = new NFMT.WareHouse.Model.Stock();
            NFMT.WareHouse.BLL.StockBLL stockBLL = new NFMT.WareHouse.BLL.StockBLL();
            NFMT.Common.ResultModel result = new NFMT.Common.ResultModel();

            foreach (NFMT.WareHouse.Model.StockOutDetail detail in details)
            {
                result = stockBLL.Get(user, detail.StockId);
                if (result.ResultStatus != 0)
                    continue;

                stock = result.ReturnValue as NFMT.WareHouse.Model.Stock;
                if (stock == null)
                    continue;

                sb.Append("<tr class=\"txt\">");
                sb.AppendFormat("<td>{0}</td>", stock.CardNo);
                sb.AppendFormat("<td>{0}</td>", NFMT.Data.BasicDataProvider.Assets.SingleOrDefault(a => a.AssetId == stock.AssetId).AssetName);
                sb.AppendFormat("<td>{0}</td>", NFMT.Data.BasicDataProvider.Brands.SingleOrDefault(a => a.BrandId == stock.BrandId).BrandName);
                sb.AppendFormat("<td>{0}</td>", detail.GrossAmount);
                sb.Append("<td>&nbsp;</td>");
                sb.Append("<td>&nbsp;</td>");
                sb.Append("<td>&nbsp;</td>");
                sb.Append("</tr>");

                if (string.IsNullOrEmpty(this.DPName))
                    DPName = NFMT.Data.BasicDataProvider.DeliverPlaces.SingleOrDefault(a => a.DPId == stock.DeliverPlaceId).DPName;
            }

            return sb.ToString();
        }
예제 #9
0
파일: MainForm.cs 프로젝트: bazile/Training
 public void EnumerateTable(DataTable cars)
 {
     var buffer = new System.Text.StringBuilder();
     foreach (DataColumn dc in cars.Columns)
     {
         buffer.AppendFormat("{0,15} ", dc.ColumnName);
     }
     buffer.Append("\r\n");
     foreach (DataRow dr in cars.Rows)
     {
         if (dr.RowState == DataRowState.Deleted)
         {
             buffer.Append("Deleted Row");
         }
         else
         {
             foreach (DataColumn dc in cars.Columns)
             {
                 buffer.AppendFormat("{0,15} ", dr[dc]);
             }
         }
         buffer.Append("\r\n");
     }
     //textBox1.Text = buffer.ToString();
 }
예제 #10
0
        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;
        }
예제 #11
0
        public override string ToString()
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            sb.Append("I2CVMUserProgram \n");
            sb.Append("    Program\n");
            sb.AppendFormat("        : {0} \n", Program[0]);
            sb.AppendFormat("        : {0} \n", Program[1]);
            sb.AppendFormat("        : {0} \n", Program[2]);
            sb.AppendFormat("        : {0} \n", Program[3]);
            sb.AppendFormat("        : {0} \n", Program[4]);
            sb.AppendFormat("        : {0} \n", Program[5]);
            sb.AppendFormat("        : {0} \n", Program[6]);
            sb.AppendFormat("        : {0} \n", Program[7]);
            sb.AppendFormat("        : {0} \n", Program[8]);
            sb.AppendFormat("        : {0} \n", Program[9]);
            sb.AppendFormat("        : {0} \n", Program[10]);
            sb.AppendFormat("        : {0} \n", Program[11]);
            sb.AppendFormat("        : {0} \n", Program[12]);
            sb.AppendFormat("        : {0} \n", Program[13]);
            sb.AppendFormat("        : {0} \n", Program[14]);
            sb.AppendFormat("        : {0} \n", Program[15]);
            sb.AppendFormat("        : {0} \n", Program[16]);
            sb.AppendFormat("        : {0} \n", Program[17]);
            sb.AppendFormat("        : {0} \n", Program[18]);
            sb.AppendFormat("        : {0} \n", Program[19]);

            return sb.ToString();
        }
예제 #12
0
		string ListApplications(ApplicationInstance applicationInstance)
		{
			System.Text.StringBuilder output = new System.Text.StringBuilder();
			WriteCSS();
			if (_authenticated)
			{
				output.AppendFormat("<form method=post action=''>");
			}
			output.Append("<table >\n");
			output.AppendFormat("<tr><td><a href='Tarantino.WebManagement.Application.axd'>Back</a></td><td></td></tr>");
			output.AppendFormat("<tr><td>Machine Name</td><td>{0}</td></tr>", applicationInstance.MachineName);
			output.AppendFormat("<tr><td>Version</td><td>{0}</td></tr>", applicationInstance.Version);
			output.AppendFormat("<tr><td>Unique Hostname</td><td><input type=\"text\" name=\"hostname\" value=\"{0}\"></td></tr>", applicationInstance.UniqueHostHeader);
			output.AppendFormat("<tr><td>Shared Hostname</td><td>{0}</td></tr>", applicationInstance.MaintenanceHostHeader);
			output.AppendFormat("<tr><td>Load balanaced</td><td>{0}</td></tr>", applicationInstance.AvailableForLoadBalancing ? "Online" : "Offline");
			output.AppendFormat("<tr><td>Maintenance Mode</td><td>{0}</td></tr>", applicationInstance.DownForMaintenance ? "Down" : "Online");
			output.Append("</table>\n");

			if (_authenticated)
			{
				output.AppendFormat("<input type=submit value='Submit' />");
				output.AppendFormat("</form>");
			}

			return output.ToString();
		}
예제 #13
0
파일: Alert.cs 프로젝트: zinoy/LRAdmin
        /// <summary>
        /// ���JS��ʾ��Ϣ�Ի���
        /// </summary>
        /// <param name="context">ҳ��Context</param>
        /// <param name="Msg">��Ϣ����</param>
        /// <param name="Astate">���ģʽ * ö��</param>
        /// <param name="ToUrl">��ʾ��Ҫת����URL</param>
        public static void ShowAlert(HttpContext context, string Msg, AlertState Astate, string ToUrl)
        {
            System.Text.StringBuilder mySB = new System.Text.StringBuilder();

            mySB.AppendFormat("<script type=\"text/javascript\">alert(\"{0}\");", Msg);

            switch (Astate)
            {
                case AlertState.Back:
                    mySB.Append("history.go(-1);");
                    break;

                case AlertState.CloseWindow:
                    mySB.Append("top.window.close();");
                    break;

                case AlertState.OpenInParentWindow:
                    mySB.AppendFormat("top.location = '{0}';", ToUrl);
                    break;

                case AlertState.OpenInThisWindow:
                    mySB.AppendFormat("window.location = '{0}';", ToUrl);
                    break;
                case AlertState.Nothing:
                    break;
            }

            mySB.Append("</script>");

            context.Response.Write(mySB.ToString());
        }
예제 #14
0
파일: BankBLL.cs 프로젝트: weiliji/NFMT
        public SelectModel GetSelectModel(int pageIndex, int pageSize, string orderStr, int status, string key, int bankeStatus, int capitalType, string bankEname)
        {
            NFMT.Common.SelectModel select = new NFMT.Common.SelectModel();

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

            select.ColumnName = " B.BankId,B.BankName,B.BankEname,B.BankFullName,B.BankShort,B.CapitalType,B.BankStatus,bd.StatusName,sd.DetailName,bt.BankName as ParentBankName,B.ParentId,case ISNULL(B.SwitchBack,0) when 0 then '否' when 1 then '是' end as SwitchBack ";
            select.TableName = "  dbo.Bank B left join dbo.BDStatusDetail bd on B.BankStatus = bd.DetailId left join dbo.BDStyleDetail sd on sd.StyleDetailId=B.CapitalType left join Bank bt on bt.BankId=B.ParentId ";

            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append(" bd.StatusId = 1 ");

            if (status > 0)
                sb.AppendFormat(" and  B.BankStatus = {0}", status);
            if (!string.IsNullOrEmpty(key))
                sb.AppendFormat(" and B.BankFullName like '%{0}%'", key);
            if (capitalType > 0)
                sb.AppendFormat(" and  B.CapitalType = {0}", capitalType);
            if (!string.IsNullOrEmpty(bankEname))
                sb.AppendFormat(" and B.BankEname like '%{0}%'", bankEname);
            select.WhereStr = sb.ToString();

            return select;
        }
예제 #15
0
        protected void Page_Load(object sender, EventArgs e)
        {
            footer = Sitecore.Context.Database.GetItem(footerItemPath);

            //Main Menu items
            List<PageSummaryItem> items = footer.Mainlinks.ListItems.ConvertAll(x => new PageSummaryItem(x));
            System.Text.StringBuilder markupBuilder = new System.Text.StringBuilder();
            int childcounter = 0;
            foreach (PageSummaryItem child in items)
            {
                if (!string.IsNullOrEmpty(child.NavigationTitle.Text))
                {
                    markupBuilder.AppendFormat(@"<li{2}><a href=""{0}"">{1}</a></li>", child.Url, child.NavigationTitle.Rendered, childcounter == 0 ? @" class=""first""" : "");
                    childcounter++;
                }
            }

            if (markupBuilder.Length > 0)
            {
                markupBuilder.Insert(0, "<ul>");
                markupBuilder.Insert(0, "<nav>");
                markupBuilder.AppendFormat(@"<li><a href=""{0}"" class=""external"" target=""_blank"">{1}</a></li>", Settings.CareersLink, Translate.Text("Careers"));
                markupBuilder.Append("</ul>");
                markupBuilder.Append("</nav>");
                markup = markupBuilder.ToString();
            }

            //Submenu items
            List<PageSummaryItem> subitems = footer.Sublinks.ListItems.ConvertAll(x => new PageSummaryItem(x));
            System.Text.StringBuilder markupBuilderSub = new System.Text.StringBuilder();
            childcounter = 0;
            //Set Link to Mobile Site -if we are using a Mobile device.

            if (SitecoreHelper.GetDeviceFromCookie().Equals(Settings.MobileDevice, StringComparison.OrdinalIgnoreCase))
            {
                string startPath = Sitecore.Context.Site.StartPath.ToString();
                var homeItem = Sitecore.Context.Database.GetItem(startPath);
                var options = new UrlOptions { AlwaysIncludeServerUrl = true, AddAspxExtension = false, LanguageEmbedding = LanguageEmbedding.Never };
                var homeUrl = LinkManager.GetItemUrl(homeItem, options);

                //Set return to main site link
                markupBuilderSub.AppendFormat(@"<li><a href=""{0}"">{1}</a></li>", homeUrl + "?sc_device=mobile&persisted=true", Translate.Text("Mobile Site"));
                childcounter++;
            }

            foreach (PageSummaryItem child in subitems)
            {
                if (!string.IsNullOrEmpty(child.NavigationTitle.Text))
                {
                    string url = Sitecore.Links.LinkManager.GetItemUrl(child.InnerItem);
                    markupBuilderSub.AppendFormat(@"<li><a href=""{0}"">{1}</a></li>", url, child.NavigationTitle.Rendered);
                    childcounter++;
                }
            }

            if (markupBuilderSub.Length > 0)
            {
                subMenuMarkup = markupBuilderSub.ToString();
            }
        }
예제 #16
0
		/// <summary>
		/// Ausgeben der Werte als Pseudo-CSV
		/// </summary>
		public override string ToString()
		{
			System.Text.StringBuilder builder = new System.Text.StringBuilder();
			builder.AppendFormat("{0};", this.listIndex);
			foreach (object value in objectArray)
			{
				if (value == null || value == DBNull.Value)
				{
					builder.AppendFormat("<NULL>");
				}
				else if (value.GetType() == typeof(string))
				{
					builder.AppendFormat("\"{0}\"", (string)value);
				}
				else if (value is IFormattable)
				{
					builder.AppendFormat("{0}", ((IFormattable)value).ToString("g", System.Globalization.CultureInfo.InvariantCulture));
				}
				else
				{
					builder.AppendFormat("[{0}]", value.ToString());
				}
				builder.Append(';');
			}
			return builder.ToString();
		}
예제 #17
0
        void IGeneratedSourcePolicy.GenerateSource(
            GeneratedSourceModule sender,
            Bam.Core.ExecutionContext context,
            Bam.Core.ICommandLineTool compiler,
            Bam.Core.TokenizedString generatedFilePath)
        {
            var encapsulating = sender.GetEncapsulatingReferencedModule();

            var workspace = Bam.Core.Graph.Instance.MetaData as XcodeBuilder.WorkspaceMeta;
            var target = workspace.EnsureTargetExists(encapsulating);
            var configuration = target.GetConfiguration(encapsulating);

            var command = new System.Text.StringBuilder();
            // recode the executable path for Xcode
            var xcodePath = encapsulating.CreateTokenizedString("$(packagebuilddir)/$(config)").Parse();
            xcodePath += "/" + System.IO.Path.GetFileName(compiler.Executable.Parse());
            command.AppendFormat(xcodePath);
            // TODO: change this to a configuration directory really
            command.AppendFormat(" {0}", Bam.Core.TokenizedString.Create("$(buildroot)", null).Parse());
            command.AppendFormat(" {0}", "Generated");

            var commands = new Bam.Core.StringArray();
            commands.Add(command.ToString());
            target.AddPreBuildCommands(commands, configuration);

            var compilerTarget = workspace.EnsureTargetExists(compiler as Bam.Core.Module);
            target.Requires(compilerTarget);
        }
 /// <summary>
 /// 查询条数
 /// </summary>
 /// <param name="wheres">查询条件</param>
 /// <returns>条数</returns>
 public int QueryCount(object wheres)
 {
     var parameters = new List<SqlParameter>();
     var whereBuilder = new System.Text.StringBuilder();
     if (wheres != null)
     {
         var props = wheres.GetType().GetProperties();
         foreach (var prop in props)
         {
             if (prop.Name.Equals("__o", StringComparison.InvariantCultureIgnoreCase))
             {
                 // 操作符
                 whereBuilder.AppendFormat(" {0} ", prop.GetValue(wheres, null).ToString());
             }
             else
             {
                 var val = prop.GetValue(wheres, null).ToString();
                 whereBuilder.AppendFormat(" [{0}] = @{0} ", prop.Name);
                 parameters.Add(new SqlParameter("@" + prop.Name, val));
             }
         }
     }
     var sql = SqlHelper.GenerateQuerySql("PictureCollect", new[] { "COUNT(1)" }, whereBuilder.ToString(), string.Empty);
     var res = SqlHelper.ExecuteScalar(sql, parameters.ToArray());
     return res == null ? 0 : Convert.ToInt32(res);
 }
예제 #19
0
        public SelectModel GetSelectModel(int pageIndex, int pageSize, string orderStr, int masterId, bool isHas = false, string clauseText = "")
        {
            NFMT.Common.SelectModel select = new NFMT.Common.SelectModel();
            int status = (int)NFMT.Common.StatusEnum.已生效;

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

            select.ColumnName = " cc.ClauseText,cc.ClauseEnText,ccr.RefId,cc.ClauseId,ccr.Sort,ccr.IsChose ";
            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            if (isHas)
            {
                select.TableName = " dbo.ClauseContract_Ref ccr left join dbo.ContractClause cc on cc.ClauseId = ccr.ClauseId left join dbo.ContractMaster cm on cm.MasterId = ccr.MasterId ";
                sb.AppendFormat(" ccr.RefStatus ={0} and cc.ClauseStatus = {0} ", status);
                sb.AppendFormat(" and ccr.MasterId = {0} ", masterId);
            }
            else
            {
                select.TableName = string.Format(" dbo.ContractClause cc left join dbo.ClauseContract_Ref ccr on ccr.ClauseId = cc.ClauseId and MasterId = {0} and RefStatus = {1}  left join dbo.ContractMaster cm on cm.MasterId = ccr.MasterId ", masterId, status);
                sb.AppendFormat(" ccr.ClauseId is null and cc.ClauseStatus = {0}", status);
                if (!string.IsNullOrEmpty(clauseText))
                    sb.AppendFormat(" and cc.ClauseText like '%{0}%' ", clauseText);
            }

            select.WhereStr = sb.ToString();

            return select;
        }
		protected void Page_Load( object sender, EventArgs e )
		{
			if ( PageContext.IsAdmin || PageContext.IsForumModerator )
			{
				int userID = ( int ) Security.StringToLongOrRedirect( Request.QueryString ["u"] );

				using ( DataTable dt2 = YAF.Classes.Data.DB.user_accessmasks( PageContext.PageBoardID, userID ) )
				{
					System.Text.StringBuilder html = new System.Text.StringBuilder();
					int nLastForumID = 0;
					foreach ( DataRow row in dt2.Rows )
					{
						if ( nLastForumID != Convert.ToInt32( row ["ForumID"] ) )
						{
							if ( nLastForumID != 0 )
								html.AppendFormat( "</td></tr>" );
							html.AppendFormat( "<tr><td width='50%' class='postheader'>{0}</td><td width='50%' class='post'>", row ["ForumName"] );
							nLastForumID = Convert.ToInt32( row ["ForumID"] );
						}
						else
						{
							html.AppendFormat( ", " );
						}
						html.AppendFormat( "{0}", row ["AccessMaskName"] );
					}
					if ( nLastForumID != 0 )
						html.AppendFormat( "</td></tr>" );
					AccessMaskRow.Text = html.ToString();
				}
			}
		}
예제 #21
0
        protected void DeleteAllSVN(string dirName)
        {
            var list = new List<string>();
            list.AddRange(Directory.GetDirectories(dirName, ".svn", SearchOption.AllDirectories));

            var stringResult = new System.Text.StringBuilder();
            Boolean summRes = false;

            // Process

            try
            {

                foreach (var fileName in list)
                {

                    if (chboxDeleteFiles.Checked)
                    {
                        stringResult.AppendFormat("Deleted: '{0}'<br/>", fileName);
                        Directory.Delete(fileName, true);
                    }
                    else
                    {
                        stringResult.AppendFormat("Found: '{0}'<br/>", fileName);
                    }

                }

                summRes = true;

            }
            catch (Exception ex)
            {
                stringResult.AppendFormat("<b>Error: '{0}'</b><br/>", ex.Message);
            }

            // Summary result

            lCompleted.Visible = true;

            if (summRes)
            {
                if (chboxDeleteFiles.Checked)
                {
                    lCompleted.Text = "Cleanup successfuly completed";
                }
                else
                {
                    lCompleted.Text = "Analysis successfully completed";
                }

            }
            else
            {
                lCompleted.Text = "Cleanup completed with errors";
            }

            lResultHeader.Visible = true;
            lResult.Text = stringResult.ToString();
        }
예제 #22
0
		private static string Format(object o)
		{
			if (o == null) {
				return "null";
			} else if (o is string) {
				return '"' + ((string)o) + '"';
			} else if (o is Amf3Object) {
				var sb = new System.Text.StringBuilder();
				var ao = (Amf3Object)o; 
				sb.AppendFormat("[{0} ", ao.ClassDef.Name);
				foreach (var prop in ao.Properties) {
					sb.AppendFormat("{0}:{1} ", prop.Key, Format(prop.Value));
				}
				sb.AppendFormat("]");
				return sb.ToString();
			} else if (o is _root.Vector<int>){
				var a = o as _root.Vector<int>;
				return "(int)[" + o.ToString() + "]";
			} else if (o is _root.Vector<uint>){
				var a = o as _root.Vector<uint>;
				return "(uint)[" + o.ToString() + "]";
			} else if (o is _root.Vector<double>){
				var a = o as _root.Vector<double>;
				return "(number)[" + o.ToString() + "]";
			} else if (o is double){
				return "(number)" + o.ToString();
			} else {
				return o.ToString();
			}
		}
예제 #23
0
 public void StringBuilderCanUseFormatAsWell()
 {
 var strBuilder = new System.Text.StringBuilder();
 strBuilder.AppendFormat("{0} {1} {2}", "The", "quick", "brown");
 strBuilder.AppendFormat("{0} {1} {2}", "jumped", "over", "the");
 strBuilder.AppendFormat("{0} {1}.", "lazy", "dog");
 var str = strBuilder.ToString();
 Assert.Equal("The quick brownjumped over thelazy dog.", str);
 }
예제 #24
0
 public override string ToString()
 {
     System.Text.StringBuilder sb = new System.Text.StringBuilder();
     sb.AppendFormat("{0},", Id);
     foreach (int nbr in Neighbors)
         sb.AppendFormat("{0},", nbr);
     sb.AppendFormat("{0}", Name);
     return sb.ToString();
 }
예제 #25
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());
        }
예제 #26
0
 /// <summary>
 /// Sobrescrição do método ToString para retornar as informações de um registro log.
 /// </summary>
 /// <returns>Retorna uma string com a descrição do evento.</returns>
 public override String ToString()
 {
     var descricao = new System.Text.StringBuilder();
     descricao.AppendFormat("Tipo de Log: {0}{1}", Registro.LogTipo.ToString("G"), Environment.NewLine);
     descricao.AppendFormat("Descrição: {0}{1}", Descricao, Environment.NewLine);
     descricao.AppendFormat("Ocorrido em: {0}{1}", DataHora, Environment.NewLine);
     descricao.AppendLine(Exception.ToString());
     return descricao.ToString();
 }
예제 #27
0
        public override string ToString()
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            sb.Append("TrimAnglesSettings \n");
            sb.AppendFormat("    Roll: {0} degrees\n", Roll);
            sb.AppendFormat("    Pitch: {0} degrees\n", Pitch);

            return sb.ToString();
        }
예제 #28
0
        public override string ToString()
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            sb.Append("GeoFenceSettings \n");
            sb.AppendFormat("    WarningRadius: {0} m\n", WarningRadius);
            sb.AppendFormat("    ErrorRadius: {0} m\n", ErrorRadius);

            return sb.ToString();
        }
예제 #29
0
 public string DisplayText()
 {
     System.Text.StringBuilder builder = new System.Text.StringBuilder ();
     if (IsValidText (Name))
     {
         builder.AppendFormat ("{0}-", Name);
     }
     builder.AppendFormat ("{0}", Interface);
     return builder.ToString ().Trim ();
 }
예제 #30
0
        public override string ToString()
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();

            sb.Append("PathPlannerSettings \n");
            sb.AppendFormat("    PreprogrammedPath: {0} \n", PreprogrammedPath);
            sb.AppendFormat("    FlashOperation: {0} \n", FlashOperation);

            return sb.ToString();
        }
예제 #31
0
        ILinkingPolicy.Link(
            ConsoleApplication sender,
            Bam.Core.ExecutionContext context,
            Bam.Core.TokenizedString executablePath,
            System.Collections.ObjectModel.ReadOnlyCollection <Bam.Core.Module> objectFiles,
            System.Collections.ObjectModel.ReadOnlyCollection <Bam.Core.Module> headers,
            System.Collections.ObjectModel.ReadOnlyCollection <Bam.Core.Module> libraries)
        {
            // any libraries added prior to here, need to be moved to the end
            // they are external dependencies, and thus all built modules (to be added now) may have
            // a dependency on them (and not vice versa)
            var linker       = sender.Settings as C.ICommonLinkerSettings;
            var externalLibs = linker.Libraries;

            linker.Libraries = new Bam.Core.StringArray();
            foreach (var library in libraries)
            {
                (sender.Tool as C.LinkerTool).ProcessLibraryDependency(sender as CModule, library as CModule);
            }
            linker.Libraries.AddRange(externalLibs);

            var commandLineArgs = new Bam.Core.StringArray();

            (sender.Settings as CommandLineProcessor.IConvertToCommandLine).Convert(commandLineArgs);

            var meta = new MakeFileBuilder.MakeFileMeta(sender);
            var rule = meta.AddRule();

            rule.AddTarget(executablePath);
            string objExt = null; // try to get the object file extension from a compiled source file

            foreach (var module in objectFiles)
            {
                if (null == objExt)
                {
                    objExt = module.Tool.Macros["objext"].Parse();
                }
                if (!(module as C.ObjectFileBase).PerformCompilation)
                {
                    continue;
                }
                rule.AddPrerequisite(module, C.ObjectFile.Key);
            }
            foreach (var module in libraries)
            {
                if (module is StaticLibrary)
                {
                    rule.AddPrerequisite(module, C.StaticLibrary.Key);
                }
                else if (module is IDynamicLibrary)
                {
                    if (module.BuildEnvironment.Platform.Includes(Bam.Core.EPlatform.Windows))
                    {
                        rule.AddPrerequisite(module, C.DynamicLibrary.ImportLibraryKey);
                    }
                    else
                    {
                        rule.AddPrerequisite(module, C.DynamicLibrary.Key);
                    }
                }
                else if (module is CSDKModule)
                {
                    continue;
                }
                else if (module is OSXFramework)
                {
                    continue;
                }
                else if (module is HeaderLibrary)
                {
                    continue;
                }
                else
                {
                    throw new Bam.Core.Exception("Unknown module library type: {0}", module.GetType());
                }
            }

            var tool     = sender.Tool as Bam.Core.ICommandLineTool;
            var commands = new System.Text.StringBuilder();
            // if there were no object files, you probably intended to use all prerequisites anyway
            var filter = (null != objExt) ? System.String.Format("$(filter %{0},$^)", objExt) : "$^";

            commands.AppendFormat("{0} {1} {2} {3}",
                                  CommandLineProcessor.Processor.StringifyTool(tool),
                                  filter,
                                  commandLineArgs.ToString(' '),
                                  CommandLineProcessor.Processor.TerminatingArgs(tool));
            rule.AddShellCommand(commands.ToString());

            var executableDir = System.IO.Path.GetDirectoryName(executablePath.ToString());

            meta.CommonMetaData.AddDirectory(executableDir);
            meta.CommonMetaData.ExtendEnvironmentVariables(tool.EnvironmentVariables);
        }
예제 #32
0
        void backgroundWorker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            progressBar.Visible = false;
            bStart.Text         = "Поехали";

            #region Вывод результата
            string   message;
            string[] prc_errors = new string[]
            {
                "Не удалось проанализировать исходный файл.",
                "Не удалось проанализировать файл обновления.",
                "Не удалось обработать файл.",
                "Не удалось записать целевой файл.",
                "Обработка файла отменена."
            };

            switch (FilesError)
            {
            case EG_SrcEmpty: message = "Не указан исходный файл!"; break;

            case EG_SrcBad: message = "Неверно указан исходный файл!"; break;

            case EG_SrcNotExist: message = "Исходные файлы не найдены!"; break;

            case EG_UpdBad: message = "Неверно указан файл обновления!"; break;

            case EG_TrgEmpty: message = "Не указан целевой файл!"; break;

            case EG_TrgBad: message = "Неверно указан целевой файл!"; break;

            default:
                bool updated = false;
                if (FilesUpdated)
                {
                    foreach (CheckBox c in gUpdate.Controls)
                    {
                        if (c.Checked)
                        {
                            updated = true;
                        }
                    }
                }
                if (Files.Count == 1)
                {
                    message = (Files[0].Error == 0)
                                                        ? String.Format("Файл благополучно {0}.", (updated ? "обновлен" : "отформатирован"))
                                                        : prc_errors[Files[0].Error - 10];
                }
                else
                {
                    var sb = new System.Text.StringBuilder();
                    foreach (GTFile file in Files)
                    {
                        if (file.Error > 0)
                        {
                            sb.AppendFormat("{0} - {1}\r\n", SplitPath(file.Source)[1], prc_errors[file.Error - 10]);
                        }
                    }
                    message = (sb.Length == 0)
                                                        ? String.Format("Файлы благополучно {0}.", (updated ? "обновлены" : "отформатированы"))
                                                        : String.Format("Не все файлы удалось {0}:\r\n\r\n{1}", (updated ? "обновить" : "отформатировать"), sb.ToString());
                }
                TextToItem(cbSourceFile);
                TextToItem(cbUpdateFile);
                TextToItem(cbDestFile);
                break;
            }

            MessageBox.Show(message, FilesError == 0 ? "Готово" : "Ошибка", MessageBoxButtons.OK, FilesError == 0 ? MessageBoxIcon.Asterisk : MessageBoxIcon.Error);
            #endregion
        }
예제 #33
0
        protected void Page_Load(object sender, System.EventArgs e)
        {
            if (!long.TryParse(this.Page.Request.QueryString["VoteId"], out this.voteId))
            {
                base.GotoResourceNotFound();
                return;
            }
            this.LocalUrl = base.Server.UrlEncode(base.Request.Url.ToString());

            if (!this.Page.IsPostBack)
            {
                //投票活动表信息
                VoteInfo voteById = StoreHelper.GetVoteById(this.voteId);

                string selectSql = string.Format(@"select vm.*,hm.*,model.ModelName from Yihui_Votes_Model as vm 
                    left join YiHui_HomePage_Model as hm on vm.VMID = hm.PageID 
                    left join YiHui_Model as model on vm.ModelCode = model.ModelCode 
                    where vm.VoteId = {0} order by vm.ModelSN;", this.voteId);
                selectSql += string.Format(@"select mr.UserId,mb.UserName,mb.RealName from YiHui_Votes_Model_Result as mr 
                    left join dbo.aspnet_Members as mb on mr.UserId = mb.UserId where mr.VoteId = {0} 
                    group by mr.UserId,UserName,RealName;", this.voteId);
                selectSql += string.Format("select * from dbo.YiHui_Votes_Model_Result where VoteId = {0};", this.voteId);
                selectSql += string.Format("select * from dbo.YIHui_Votes_Model_Detail");
                DataSet dsData = DataBaseHelper.GetDataSet(selectSql);

                DataTable dtHomePageModel = dsData.Tables[0];
                DataTable dtVoteUser      = dsData.Tables[1];
                DataTable dtResult        = dsData.Tables[2];
                DataTable dtDetail        = dsData.Tables[3];

                System.Text.StringBuilder builder = new System.Text.StringBuilder();
                //先构建结果表显示列
                if (dtHomePageModel.Rows.Count > 0)
                {
                    //设置标题行
                    builder.Append("<table><tr>");
                    builder.Append("<td>用户名/昵称</td>");
                    foreach (DataRow drTitle in dtHomePageModel.Rows)
                    {
                        //图片、文本除外
                        if (drTitle["ModelCode"].ToString() != "TuPian" && drTitle["ModelCode"].ToString() != "WenBen")
                        {
                            string[] strContens = drTitle["PMContents"].ToString().Split('♦');
                            if (strContens.Length > 0)
                            {
                                builder.AppendFormat("<td>{0}</td>", strContens[0]);
                            }
                        }
                    }
                    builder.Append("</tr>");

                    if (dtVoteUser.Rows.Count > 0 && dtResult.Rows.Count > 0)
                    {
                        foreach (DataRow drUser in dtVoteUser.Rows)
                        {
                            builder.Append("<tr>");
                            builder.AppendFormat("<td>{0}/{1}</td>", drUser["UserName"].ToString(), drUser["RealName"].ToString());
                            foreach (DataRow drTitle in dtHomePageModel.Rows)
                            {
                                //图片、文本除外
                                if (drTitle["ModelCode"].ToString() != "TuPian" && drTitle["ModelCode"].ToString() != "WenBen")
                                {
                                    DataRow[] drsResult = dtResult.Select(string.Format("PMID = '{0}' and UserId = '{1}'", drTitle["PMID"].ToString(), drUser["UserId"].ToString()), "", DataViewRowState.CurrentRows);
                                    if (drsResult.Length > 0)
                                    {
                                        if (drTitle["ModelCode"].ToString() == "XuanXiang")
                                        {
                                            builder.AppendFormat("<td>{0}</td>", drsResult[0]["Result"].ToString());
                                            //DataRow[] drXuanXiang = dtDetail.Select(string.Format("VMID = '{0}' and Value = '{1}'", drTitle["PageID"].ToString(), drsResult[0]["Result"].ToString()), "", DataViewRowState.CurrentRows);
                                            //if (drXuanXiang.Length > 0)
                                            //    builder.AppendFormat("<td>{0}</td>", drXuanXiang[0]["Name"].ToString());
                                            //else
                                            //    builder.Append("<td></td>");
                                        }
                                        else
                                        {
                                            builder.AppendFormat("<td>{0}</td>", drsResult[0]["Result"].ToString().Length > 20 ? drsResult[0]["Result"].ToString().Substring(0, 20) : drsResult[0]["Result"].ToString());
                                        }
                                    }
                                    else
                                    {
                                        builder.Append("<td></td>");
                                    }
                                }
                            }
                            builder.Append("</tr>");
                        }
                    }
                    builder.Append("</table>");
                }
                //设置前端显示
                litResultInfoTable.Text = builder.ToString();
            }
        }
        public void ShowDetail(int contentItemId, int?contentChannelId)
        {
            bool canEdit = IsUserAuthorized(Authorization.EDIT);

            hfId.Value        = contentItemId.ToString();
            hfChannelId.Value = contentChannelId.HasValue ? contentChannelId.Value.ToString() : string.Empty;

            ContentChannelItem contentItem = GetContentItem();

            if (contentItem != null &&
                contentItem.ContentChannelType != null &&
                contentItem.ContentChannel != null &&
                (canEdit || contentItem.IsAuthorized(Authorization.EDIT, CurrentPerson)))
            {
                ShowApproval(contentItem);

                pnlEditDetails.Visible = true;

                hfId.Value        = contentItem.Id.ToString();
                hfChannelId.Value = contentItem.ContentChannelId.ToString();

                string cssIcon = contentItem.ContentChannel.IconCssClass;
                if (string.IsNullOrWhiteSpace(cssIcon))
                {
                    cssIcon = "fa fa-certificate";
                }
                lIcon.Text = string.Format("<i class='{0}'></i>", cssIcon);

                string title = contentItem.Id > 0 ?
                               ActionTitle.Edit(ContentChannelItem.FriendlyTypeName) :
                               ActionTitle.Add(ContentChannelItem.FriendlyTypeName);
                lTitle.Text = title.FormatAsHtmlTitle();

                hlContentChannel.Text = contentItem.ContentChannel.Name;
                hlStatus.Text         = contentItem.Status.ConvertToString();

                hlStatus.LabelType = LabelType.Default;
                if (contentItem.Status == ContentChannelItemStatus.Approved)
                {
                    hlStatus.LabelType = LabelType.Success;
                }
                else if (contentItem.Status == ContentChannelItemStatus.Denied)
                {
                    hlStatus.LabelType = LabelType.Danger;
                }
                if (contentItem.Status != ContentChannelItemStatus.PendingApproval)
                {
                    var statusDetail = new System.Text.StringBuilder();
                    if (contentItem.ApprovedByPersonAlias != null && contentItem.ApprovedByPersonAlias.Person != null)
                    {
                        statusDetail.AppendFormat("by {0} ", contentItem.ApprovedByPersonAlias.Person.FullName);
                    }
                    if (contentItem.ApprovedDateTime.HasValue)
                    {
                        statusDetail.AppendFormat("on {0} at {1}", contentItem.ApprovedDateTime.Value.ToShortDateString(),
                                                  contentItem.ApprovedDateTime.Value.ToShortTimeString());
                    }
                    hlStatus.ToolTip = statusDetail.ToString();
                }

                tbTitle.Text = contentItem.Title;

                if (contentItem.ContentChannel.ContentControlType == ContentControlType.HtmlEditor)
                {
                    ceContent.Visible   = false;
                    htmlContent.Visible = true;
                    htmlContent.Text    = contentItem.Content;
                    htmlContent.MergeFields.Clear();
                    htmlContent.MergeFields.Add("GlobalAttribute");
                    htmlContent.MergeFields.Add("Rock.Model.ContentChannelItem|Current Item");
                    htmlContent.MergeFields.Add("Rock.Model.Person|Current Person");
                    htmlContent.MergeFields.Add("Campuses");
                    htmlContent.MergeFields.Add("RockVersion");

                    if (!string.IsNullOrWhiteSpace(contentItem.ContentChannel.RootImageDirectory))
                    {
                        htmlContent.DocumentFolderRoot = contentItem.ContentChannel.RootImageDirectory;
                        htmlContent.ImageFolderRoot    = contentItem.ContentChannel.RootImageDirectory;
                    }
                }
                else
                {
                    htmlContent.Visible = false;
                    ceContent.Visible   = true;
                    ceContent.Text      = contentItem.Content;
                    ceContent.MergeFields.Clear();
                    ceContent.MergeFields.Add("GlobalAttribute");
                    ceContent.MergeFields.Add("Rock.Model.ContentChannelItem|Current Item");
                    ceContent.MergeFields.Add("Rock.Model.Person|Current Person");
                    ceContent.MergeFields.Add("Campuses");
                    ceContent.MergeFields.Add("RockVersion");
                }

                dtpStart.SelectedDateTime  = contentItem.StartDateTime;
                dtpStart.Label             = contentItem.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange ? "Start" : "Active";
                dtpExpire.SelectedDateTime = contentItem.ExpireDateTime;
                dtpExpire.Visible          = contentItem.ContentChannelType.DateRangeType == ContentChannelDateType.DateRange;
                nbPriority.Text            = contentItem.Priority.ToString();
                nbPriority.Visible         = !contentItem.ContentChannelType.DisablePriority;

                contentItem.LoadAttributes();
                phAttributes.Controls.Clear();
                Rock.Attribute.Helper.AddEditControls(contentItem, phAttributes, true, BlockValidationGroup);
            }
            else
            {
                nbEditModeMessage.Text = EditModeMessage.NotAuthorizedToEdit(ContentChannelItem.FriendlyTypeName);
                pnlEditDetails.Visible = false;
            }
        }
예제 #35
0
        internal static Tuple <Type, string> Generate <TKey, TLeft, TRight, TResult>(
            BinaryStreamable <TKey, TLeft, TRight, TResult> stream,
            Expression <Func <TLeft, TRight, TResult> > selector)
        {
            Contract.Requires(stream != null);
            Contract.Ensures(Contract.Result <Tuple <Type, string> >() == null || typeof(BinaryPipe <TKey, TLeft, TRight, TResult>).GetTypeInfo().IsAssignableFrom(Contract.Result <Tuple <Type, string> >().Item1));

            string errorMessages = null;

            try
            {
                var template = new StartEdgeEquiJoinTemplate($"GeneratedStartEdgeEquiJoin_{StartEdgeEquiJoinSequenceNumber++}", typeof(TKey), typeof(TLeft), typeof(TRight), typeof(TResult));

                var gps = template.tm.GenericTypeVariables(template.keyType, template.leftType, template.rightType, template.resultType);
                template.genericParameters = gps.BracketedCommaSeparatedString();

                template.leftMessageRepresentation = new ColumnarRepresentation(template.leftType);
                template.leftFields = template.leftMessageRepresentation.AllFields;
                template.rightMessageRepresentation = new ColumnarRepresentation(template.rightType);
                template.rightFields = template.rightMessageRepresentation.AllFields;
                var resultRepresentation = new ColumnarRepresentation(template.resultType);

                #region Key Comparer
                var keyComparer = stream.Properties.KeyEqualityComparer.GetEqualsExpr();
                template.keyComparer =
                    (left, right) =>
                    keyComparer.Inline(left, right);
                #endregion

                template.BatchGeneratedFrom_TKey_TLeft = Transformer.GetBatchClassName(template.keyType, template.leftType);
                template.TKeyTLeftGenericParameters    = template.tm.GenericTypeVariables(template.keyType, template.leftType).BracketedCommaSeparatedString();

                template.BatchGeneratedFrom_TKey_TRight = Transformer.GetBatchClassName(template.keyType, template.rightType);
                template.TKeyTRightGenericParameters    = template.tm.GenericTypeVariables(template.keyType, template.rightType).BracketedCommaSeparatedString();

                template.BatchGeneratedFrom_TKey_TResult = Transformer.GetBatchClassName(template.keyType, template.resultType);
                template.TKeyTResultGenericParameters    = template.tm.GenericTypeVariables(template.keyType, template.resultType).BracketedCommaSeparatedString();

                template.outputFields = resultRepresentation.AllFields;

                var leftMessageType  = StreamMessageManager.GetStreamMessageType <TKey, TLeft>();
                var rightMessageType = StreamMessageManager.GetStreamMessageType <TKey, TRight>();
                #region LeftBatchSelector
                {
                    var parameterSubsitutions = new List <Tuple <ParameterExpression, SelectParameterInformation> >()
                    {
                        Tuple.Create(selector.Parameters[0], new SelectParameterInformation()
                        {
                            BatchName = "leftBatch", BatchType = leftMessageType, IndexVariableName = "i", parameterRepresentation = template.leftMessageRepresentation,
                        }),
                    };
                    var projectionResult = SelectTransformer.Transform(selector, parameterSubsitutions, resultRepresentation, true);
                    if (projectionResult.Error)
                    {
                        errorMessages = "error while transforming the result selector";
                        throw new InvalidOperationException();
                    }
                    template.leftBatchSelector = (leftBatch, leftIndex, rightEvent) =>
                    {
                        var d = new Dictionary <ParameterExpression, string>
                        {
                            { Expression.Variable(leftMessageType, "leftBatch"), leftBatch },
                            { Expression.Variable(typeof(int), "i"), leftIndex },
                            { selector.Parameters[1], rightEvent }
                        };
                        var sb = new System.Text.StringBuilder();
                        sb.AppendLine("{");
                        foreach (var kv in projectionResult.ComputedFields)
                        {
                            var f = kv.Key;
                            var e = kv.Value;
                            if (f.OptimizeString())
                            {
                                sb.AppendFormat(
                                    "output.{0}.AddString({1});\n",
                                    f.Name,
                                    e.ExpressionToCSharpStringWithParameterSubstitution(d));
                            }
                            else
                            {
                                sb.AppendFormat(
                                    "output.{0}.col[index] = {1};\n",
                                    f.Name,
                                    e.ExpressionToCSharpStringWithParameterSubstitution(d));
                            }
                        }
                        sb.AppendLine("}");
                        return(sb.ToString());
                    };
                }
                #endregion
                #region RightBatchSelector
                {
                    var parameterSubsitutions = new List <Tuple <ParameterExpression, SelectParameterInformation> >()
                    {
                        Tuple.Create(selector.Parameters[1], new SelectParameterInformation()
                        {
                            BatchName = "rightBatch", BatchType = rightMessageType, IndexVariableName = "j", parameterRepresentation = template.rightMessageRepresentation,
                        }),
                    };
                    var projectionResult = SelectTransformer.Transform(selector, parameterSubsitutions, resultRepresentation, true);
                    if (projectionResult.Error)
                    {
                        errorMessages = "error while transforming the result selector";
                        throw new InvalidOperationException();
                    }
                    template.rightBatchSelector = (leftEvent, rightBatch, rightIndex) =>
                    {
                        var d = new Dictionary <ParameterExpression, string>
                        {
                            { selector.Parameters[0], leftEvent },
                            { Expression.Variable(rightMessageType, "rightBatch"), rightBatch },
                            { Expression.Variable(typeof(int), "j"), rightIndex }
                        };
                        var sb = new System.Text.StringBuilder();
                        sb.AppendLine("{");
                        foreach (var kv in projectionResult.ComputedFields)
                        {
                            var f = kv.Key;
                            var e = kv.Value;
                            if (f.OptimizeString())
                            {
                                sb.AppendFormat(
                                    "output.{0}.AddString({1});\n",
                                    f.Name,
                                    e.ExpressionToCSharpStringWithParameterSubstitution(d));
                            }
                            else
                            {
                                sb.AppendFormat(
                                    "output.{0}.col[index] = {1};\n",
                                    f.Name,
                                    e.ExpressionToCSharpStringWithParameterSubstitution(d));
                            }
                        }
                        sb.AppendLine("}");
                        return(sb.ToString());
                    };
                }
                #endregion

                return(template.Generate <TKey, TLeft, TRight, TResult>(selector));
            }
            catch
            {
                if (Config.CodegenOptions.DontFallBackToRowBasedExecution)
                {
                    throw new InvalidOperationException("Code Generation failed when it wasn't supposed to!");
                }
                return(Tuple.Create((Type)null, errorMessages));
            }
        }
예제 #36
0
        /// <summary>
        /// Attempts to provide a category based upon some input string.
        /// This method looks for store and sequennce numbers.
        /// </summary>
        /// <param name="guess">the string to attempt to parse</param>
        /// <param name="category">Contains the category string if function returns true.
        /// <para>If function returns false this value will be String.Empty</para>
        /// </param>
        /// <returns>boolean true or false</returns>
        public Enum.QuestionTypes TryCategorizationFromString(string guess, out string category, out Entity.Store store)
        {
            var guessStore = this.parser.GetStoreNumberAndSequenceFromHaystack(guess);

            System.Collections.Generic.List <Entity.Store> storeList;

            if (guessStore["sequence"].HasValue)
            {
                storeList = this.connector.GetStore(guessStore["number"].Value, guessStore["sequence"].Value);
            }
            else
            {
                storeList = this.connector.GetStore(guessStore["number"].Value);
            }


            store = storeList[0];

            if (typeof(Entity.Store) != store.GetType())
            {
                throw new ArgumentNullException("No store found");
            }

            if (storeList.Count > 1)
            {
                category = string.Empty;

                return(Enum.QuestionTypes.None);
            }

            var rfiNumber = this.parser.GetRfiNumberWithPadding(guess);

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

            builder.AppendFormat("{0} {1}-{2} ",
                                 store.City,
                                 store.Number.ToString(),
                                 store.Sequence.ToString());

            if (rfiNumber != string.Empty)
            {
                builder.AppendFormat("RFI: {0}", rfiNumber);
            }
            else if (this.parser.IsBidQuestion(guess))
            {
                builder.Append("Bid Question");
            }
            else if (this.parser.IsRfiQuestion(guess))
            {
                builder.AppendFormat("RFI");

                category = builder.ToString();

                return(Enum.QuestionTypes.RequestForInformation);
            }
            else
            {
                category = string.Empty;

                return(Enum.QuestionTypes.None);
            }

            category = builder.ToString();

            return(Enum.QuestionTypes.Success);
        }
예제 #37
0
        /// <summary></summary>
        /// <param name="nesting"></param>
        /// <returns></returns>
        public string ToString(int nesting)
        {
            string start = "";

            for (int i = 0; i < nesting; i++)
            {
                start += "\t";
            }

            switch (type)
            {
            case DirectiveType.Charset: return(ToCharSetString(start));

            case DirectiveType.Page: return(ToPageString(start));

            case DirectiveType.Media: return(ToMediaString(nesting));

            case DirectiveType.Import: return(ToImportString());

            case DirectiveType.FontFace: return(ToFontFaceString(start));
            }

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

            txt.AppendFormat("{0} ", name);

            if (expression != null)
            {
                txt.AppendFormat("{0} ", expression);
            }

            bool first = true;

            foreach (Medium m in mediums)
            {
                if (first)
                {
                    first = false;
                    txt.Append(" ");
                }
                else
                {
                    txt.Append(", ");
                }
                txt.Append(m.ToString());
            }

            bool HasBlock = (this.declarations.Count > 0 || this.directives.Count > 0 || this.rulesets.Count > 0);

            if (!HasBlock)
            {
                txt.Append(";");
                return(txt.ToString());
            }

            txt.Append(" {\r\n" + start);

            foreach (Directive dir in directives)
            {
                txt.AppendFormat("{0}\r\n", dir.ToCharSetString(start + "\t"));
            }

            foreach (RuleSet rules in rulesets)
            {
                txt.AppendFormat("{0}\r\n", rules.ToString(nesting + 1));
            }

            first = true;
            foreach (Declaration dec in declarations)
            {
                if (first)
                {
                    first = false;
                }
                else
                {
                    txt.Append(";");
                }
                txt.Append("\r\n\t" + start);
                txt.Append(dec.ToString());
            }

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

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

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

                    sqlBuilder.Append(";");

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

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

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

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

                    sqlBuilder.Append(";");

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

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

                    using (var reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            yield return(this.MapToDto(reader));
                        }
                    }
                }
            }
        }
예제 #39
0
파일: R029.aspx.cs 프로젝트: radtek/Gradual
        private void ResponderArquivoCSV()
        {
            System.Text.StringBuilder lBuilder = new System.Text.StringBuilder();

            var lRequest = new ConsultarEntidadeCadastroRequest <LancamentoTEDInfo>()
            {
                IdUsuarioLogado = base.UsuarioLogado.Id, DescricaoUsuarioLogado = base.UsuarioLogado.Nome
            };
            var lResponse = new ConsultarEntidadeCadastroResponse <LancamentoTEDInfo>();

            string lPrefixo = this.PrefixoDaRaiz;

            try
            {
                var lInfo = GerarRequest();

                lRequest.EntidadeCadastro = lInfo;

                lResponse = this.ServicoPersistenciaCadastro.ConsultarEntidadeCadastro <LancamentoTEDInfo>(lRequest);

                if (lResponse.StatusResposta == MensagemResponseStatusEnum.OK)
                {
                    if (lResponse.Resultado.Count > 0)
                    {
                        IEnumerable <TransporteRelatorio_029> lLista = from LancamentoTEDInfo i in lResponse.Resultado select new TransporteRelatorio_029(i);

                        if (lLista.Count() > 0)
                        {
                            lBuilder.AppendLine("DataMovimento\tCodigoCliente\tNomeCliente\tNumeroLancamento\tDescricao\tValor\t");

                            foreach (TransporteRelatorio_029 lOcorrencia in lLista)
                            {
                                lBuilder.AppendFormat("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\r\n"
                                                      , lOcorrencia.DataMovimento
                                                      , lOcorrencia.CodigoCliente
                                                      , lOcorrencia.NomeCliente
                                                      , lOcorrencia.NumeroLancamento
                                                      , lOcorrencia.Descricao
                                                      , lOcorrencia.Valor);
                            }

                            Response.Clear();

                            Response.ContentType = "text/xls";

                            Response.ContentEncoding = System.Text.Encoding.GetEncoding("iso-8859-1");

                            Response.Charset = "iso-8859-1";

                            Response.AddHeader("content-disposition", "attachment;filename=MonitoramentoDeTeds.xls");

                            Response.Write(lBuilder.ToString());

                            Response.End();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
예제 #40
0
        private static string GenerateRequestURL(string page, string pageTitle, string category, string action, string label, int?value)
        {
            if (!page.StartsWith("/"))
            {
                page = "/" + page;
            }

            int visitCount = PlayerPrefs.GetInt(visitCountPrefKey, 0) + 1;

            PlayerPrefs.SetInt(visitCountPrefKey, visitCount);

            var userHash = PlayerPrefs.GetString(userHashPrefKey);

            if (userHash.Length == 0)
            {
                userHash = $"{domainHash}.{randomInt}.{timestamp}.{timestamp}.{timestamp}.";
                PlayerPrefs.SetString(userHashPrefKey, userHash);
            }

            var _utma  = userHash + visitCount.ToString();
            var _utmz  = $"{domainHash}.{timestamp}.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)";
            var _utmcc = UnityWebRequest.EscapeURL($"__utma={_utma};+__utmz={_utmz};").Replace("|", "%7C");

            var parameters = new Dictionary <string, string>()
            {
                { "utmwv", "4.8.8" },                                                               // Analytics version
                { "utmn", randomInt.ToString() },                                                   // Random number
                { "utmhn", UnityWebRequest.EscapeURL(domain) },                                     // Host name
                { "utmcs", "UTF-8" },                                                               // Charset
                { "utmsr", $"{Screen.currentResolution.width}x{Screen.currentResolution.height}" }, // Screen resolution
                { "utmsc", "24-bit" },                                                              // Color depth
                { "utmul", "en-us" },                                                               // Language
                { "utmje", "0" },                                                                   // Java enabled or not
                { "utmfl", "-" },                                                                   // User Flash version
                { "utmdt", UnityWebRequest.EscapeURL(pageTitle) },                                  // Page title
                { "utmhid", randomInt.ToString() },                                                 // Random number (unique for all session requests)
                { "utmr", "-" },                                                                    // Referrer
                { "utmp", UnityWebRequest.EscapeURL(page) },                                        // Page URL
                { "utmac", trackingCode },                                                          // Google Analytics account
                { "utmcc", _utmcc } // Cookie string (encoded)
            };


            if (Valid(category) && Valid(action))
            {
                var eventString =
                    $"5({category}*{action}{(Valid(label) ? $"*{label}" : "")}){(value.HasValue ? $"({value.ToString()})" : "")}";

                parameters.Add("utme", UnityWebRequest.EscapeURL(eventString));
                parameters.Add("utmt", "event");
            }

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

            foreach (var pair in parameters)
            {
                sb.AppendFormat("{0}={1}&", pair.Key, pair.Value);
            }
            sb.Remove(sb.Length - 1, 1);
            return(baseRequestURL + sb);
        }
예제 #41
0
        public static string GetHtml(ContentItem model)
        {
            if (model == null)
            {
                return("{model = null}");  // nothing to do
            }
            if (!(model is ContentList))
            {
                return("{adapter failure - Model is not a NewsList}");  // nothing to do
            }
            var currentItem = model as ContentList;
            var chH         = currentItem.HtmlHeader ?? string.Empty;
            var chF         = currentItem.HtmlFooter ?? string.Empty;
            var sb          = new System.Text.StringBuilder(50 * 1024 + chH.Length + chF.Length);
            var allNews     = new List <ContentItem>();

            if (currentItem.ContainerLinks == null)
            {
                return(@"<div class=""alert alert-error"">Content List: ContainerLinks is null.</div>");
            }

            var  containerLinks = currentItem.ContainerLinks.Where(c => c != null).ToList();
            bool any            = false;

            foreach (var containerLink in containerLinks)
            {
                if (containerLink.LinkedPage == null)
                {
                    continue;
                }
                any = true;

                var aChildren = containerLink.LinkedPage.GetChildPagesUnfiltered()             // get one level of child pages
                                .Where(Content.Is.AccessiblePage())
                                .ToList();

                if (containerLink.Recursive)             // additional levels of child pages -- recurse
                {
                    allNews.AddRange(
                        aChildren.Concat(aChildren.SelectMany(c => c.GetChildPagesUnfiltered().Where(Content.Is.AccessiblePage())))
                        .Distinct() /* but only keep unique child pages */);
                }
                else
                {
                    allNews.AddRange(aChildren);
                }
            }
            if (!any)
            {
                sb.Append(
                    @"<div class=""alert alert-warning"">Content List: ContainerLinks is empty. Edit the content list and add at least one content container.</div>");
            }

            var errorList = currentItem.Exceptions.Select(x => x.ToString(CultureInfo.InvariantCulture)).ToList();

            if (!String.IsNullOrEmpty(currentItem.Title))
            {
                sb.AppendFormat("<h{0}>{1}</h{0}>", currentItem.TitleLevel, currentItem.Title);
            }

            var newsEnumerable = allNews.Where(Content.Is.AccessiblePage());

            {
                // apply sort order ***
                var sortAscending = currentItem.SortDirection == SortDirection.Ascending;
                switch (currentItem.SortColumn)
                {
                case ContentSortMode.Expiration:
                    Func <ContentItem, DateTime> expirySortSelector = a => a.Expires != null ? a.Expires.Value : new DateTime();
                    newsEnumerable = sortAscending ? allNews.OrderBy(expirySortSelector) : allNews.OrderByDescending(expirySortSelector);
                    break;

                case ContentSortMode.Title:
                    Func <ContentItem, String> titleSortSelector = a => a.Title;
                    newsEnumerable = sortAscending ? allNews.OrderBy(titleSortSelector) : allNews.OrderByDescending(titleSortSelector);
                    break;

                case ContentSortMode.PublishDate:
                    Func <ContentItem, DateTime> dateSortSelector = a => a.Published != null ? a.Published.Value : new DateTime();
                    newsEnumerable = sortAscending ? allNews.OrderBy(dateSortSelector) : allNews.OrderByDescending(dateSortSelector);
                    break;
                }

                // apply filter ***

                if (!currentItem.ShowFutureEvents)
                {
                    newsEnumerable = newsEnumerable.Where(a => a.Published != null && a.Published.Value <= N2.Utility.CurrentTime());
                }

                if (!currentItem.ShowPastEvents)
                {
                    newsEnumerable = newsEnumerable.Where(a => a.Published != null && a.Published.Value >= N2.Utility.CurrentTime());
                }

                if (currentItem.MaxNews > 0)
                {
                    newsEnumerable = newsEnumerable.Take(currentItem.MaxNews);
                }
            }

            if (currentItem.DisplayMode == NewsDisplayMode.HtmlItemTemplate)
            {
                sb.Append(chH);
            }

            DateTime?lastDate = null;

            // why no ForEach here? it turns out that the C# compiler changes the behavior RE: how it deals with foreach
            // variables accessed from within lambda expressions.
            using (var itemEnumerator = newsEnumerable.GetEnumerator())
                while (itemEnumerator.MoveNext())
                {
                    ContentItem item          = itemEnumerator.Current;
                    var         itemPublished = item.Published == null ? new DateTime() : item.Published.Value;
                    if (currentItem.SortColumn == ContentSortMode.PublishDate && currentItem.GroupByMonth && (lastDate == null || lastDate.Value.Month != itemPublished.Month))
                    {
                        // new month ***
                        sb.AppendFormat("<h2>{0:MMMM yyyy}</h2>\n", itemPublished);
                        lastDate = item.Published.Value;
                    }

                    var showTitle = !String.IsNullOrEmpty(item.Title);// && item.ShowTitle
                    var text      = (item.GetDetail("Text") ?? "").ToString();
                    var summary   = (item.GetDetail("Summary") ?? "").ToString();

                    // display either full article or abstract + link ***
                    switch (currentItem.DisplayMode)
                    {
                    case NewsDisplayMode.TitleAndText:
                        if (showTitle)
                        {
                            sb.AppendFormat("<h{1}>{0}</h{1}>\n", item.Title ?? "Untitled", currentItem.TitleLevel + 1);
                        }
                        Debug.Assert(item.Published != null, "item.Published != null");
                        sb.AppendFormat("<div class=\"date\">{0:MMMM d, yyyy}</div>\n", item.Published.Value);
                        sb.AppendFormat("<div class=\"article\">\n{0}\n</div>\n", text);
                        break;

                    case NewsDisplayMode.TitleAndAbstract:
                        if (!String.IsNullOrEmpty(text))
                        {
                            if (showTitle)
                            {
                                sb.AppendFormat("<h{2}><a href=\"{1}\">{0}</a></h{2}>\n", item.Title ?? "Untitled", item.Url, currentItem.TitleLevel + 1);
                            }
                            Debug.Assert(item.Published != null, "item.Published != null");
                            sb.AppendFormat("<div class=\"date\">{0:MMMM d, yyyy}</div>\n", item.Published.Value);
                            sb.AppendFormat("<div class=\"abstract\">\n{0}\n</div>\n", summary);
                            sb.AppendFormat("<a href=\"{0}\">Read more...</a>\n", item.Url);
                        }
                        else
                        {
                            if (showTitle)
                            {
                                sb.AppendFormat("<h{1}>{0}</h{1}>\n", item.Title ?? "Untitled", currentItem.TitleLevel + 1);
                            }
                            Debug.Assert(item.Published != null, "item.Published != null");
                            sb.AppendFormat("<div class=\"date\">{0:MMMM d, yyyy}</div>\n", item.Published.Value);
                            sb.AppendFormat("<div class=\"abstract\">\n{0}\n</div>\n", summary);
                        }
                        break;

                    case NewsDisplayMode.TitleLinkOnly:
                        sb.AppendFormat("<h{2}><a href=\"{1}\">{0}</a></h{2}>\n", item.Title ?? "Untitled", item.Url, currentItem.TitleLevel + 1);
                        Debug.Assert(item.Published != null, "item.Published != null");
                        sb.AppendFormat("<div class=\"date\">{0:MMMM d, yyyy}</div>\n", item.Published.Value);
                        break;

                    case NewsDisplayMode.HtmlItemTemplate:
                        try
                        {
                            if (String.IsNullOrWhiteSpace(currentItem.HtmlItemTemplate))
                            {
                                break;
                            }
                            if (!currentItem.HtmlItemTemplate.Contains("$$") && !currentItem.HtmlItemTemplate.Contains("{{"))
                            {
                                sb.Append(currentItem.HtmlItemTemplate);
                                break;
                            }

                            sb.Append(VariableSubstituter.Substitute(currentItem.HtmlItemTemplate, item));
                        }
                        catch (Exception x)
                        {
                            errorList.Add(x.ToString());
                        }
                        break;

                    default:
                        errorList.Add("Can't render web part: invalid NewsDisplayMode.");
                        break;
                    }
                }

            if (currentItem.DisplayMode == NewsDisplayMode.HtmlItemTemplate)
            {
                sb.Append(chF);
            }

            errorList.ForEach(x => sb.AppendFormat(@"<div class=""alert alert-error""><pre>{0}</pre></div>", x));

            return(sb.ToString());
        }
        public void RunHandler()
        {
            HTTPManager.Logger.Information("HTTP1Handler", string.Format("[{0}] started processing request '{1}'", this, this.conn.CurrentRequest.CurrentUri.ToString()));

            HTTPConnectionStates proposedConnectionState = HTTPConnectionStates.Processing;

            bool resendRequest = false;

            try
            {
                if (this.conn.CurrentRequest.IsCancellationRequested)
                {
                    return;
                }

#if !BESTHTTP_DISABLE_CACHING
                // Setup cache control headers before we send out the request
                if (!this.conn.CurrentRequest.DisableCache)
                {
                    HTTPCacheService.SetHeaders(this.conn.CurrentRequest);
                }
#endif

                // Write the request to the stream
                this.conn.CurrentRequest.SendOutTo(this.conn.connector.Stream);

                if (this.conn.CurrentRequest.IsCancellationRequested)
                {
                    return;
                }

                // Receive response from the server
                bool received = Receive(this.conn.CurrentRequest);

                if (this.conn.CurrentRequest.IsCancellationRequested)
                {
                    return;
                }

                if (!received && this.conn.CurrentRequest.Retries < this.conn.CurrentRequest.MaxRetries)
                {
                    proposedConnectionState = HTTPConnectionStates.Closed;
                    this.conn.CurrentRequest.Retries++;
                    resendRequest = true;
                    return;
                }

                ConnectionHelper.HandleResponse(this.conn.ToString(), this.conn.CurrentRequest, out resendRequest, out proposedConnectionState, ref this._keepAlive);
            }
            catch (TimeoutException e)
            {
                this.conn.CurrentRequest.Response = null;

                // We will try again only once
                if (this.conn.CurrentRequest.Retries < this.conn.CurrentRequest.MaxRetries)
                {
                    this.conn.CurrentRequest.Retries++;
                    resendRequest = true;
                }
                else
                {
                    this.conn.CurrentRequest.Exception = e;
                    this.conn.CurrentRequest.State     = HTTPRequestStates.ConnectionTimedOut;
                }

                proposedConnectionState = HTTPConnectionStates.Closed;
            }
            catch (Exception e)
            {
                if (this.ShutdownType == ShutdownTypes.Immediate)
                {
                    return;
                }

                string exceptionMessage = string.Empty;
                if (e == null)
                {
                    exceptionMessage = "null";
                }
                else
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();

                    Exception exception = e;
                    int       counter   = 1;
                    while (exception != null)
                    {
                        sb.AppendFormat("{0}: {1} {2}", counter++.ToString(), exception.Message, exception.StackTrace);

                        exception = exception.InnerException;

                        if (exception != null)
                        {
                            sb.AppendLine();
                        }
                    }

                    exceptionMessage = sb.ToString();
                }
                HTTPManager.Logger.Verbose("HTTP1Handler", exceptionMessage);

#if !BESTHTTP_DISABLE_CACHING
                if (this.conn.CurrentRequest.UseStreaming)
                {
                    HTTPCacheService.DeleteEntity(this.conn.CurrentRequest.CurrentUri);
                }
#endif

                // Something gone bad, Response must be null!
                this.conn.CurrentRequest.Response = null;

                if (!this.conn.CurrentRequest.IsCancellationRequested)
                {
                    this.conn.CurrentRequest.Exception = e;
                    this.conn.CurrentRequest.State     = HTTPRequestStates.Error;
                }

                proposedConnectionState = HTTPConnectionStates.Closed;
            }
            finally
            {
                // Exit ASAP
                if (this.ShutdownType != ShutdownTypes.Immediate)
                {
                    if (this.conn.CurrentRequest.IsCancellationRequested)
                    {
                        // we don't know what stage the request is cancelled, we can't safely reuse the tcp channel.
                        proposedConnectionState = HTTPConnectionStates.Closed;

                        this.conn.CurrentRequest.Response = null;

                        this.conn.CurrentRequest.State = this.conn.CurrentRequest.IsTimedOut ? HTTPRequestStates.TimedOut : HTTPRequestStates.Aborted;
                    }
                    else if (resendRequest)
                    {
                        RequestEventHelper.EnqueueRequestEvent(new RequestEventInfo(this.conn.CurrentRequest, RequestEvents.Resend));
                    }
                    else if (this.conn.CurrentRequest.Response != null && this.conn.CurrentRequest.Response.IsUpgraded)
                    {
                        proposedConnectionState = HTTPConnectionStates.WaitForProtocolShutdown;
                    }
                    else if (this.conn.CurrentRequest.State == HTTPRequestStates.Processing)
                    {
                        if (this.conn.CurrentRequest.Response != null)
                        {
                            this.conn.CurrentRequest.State = HTTPRequestStates.Finished;
                        }
                        else
                        {
                            this.conn.CurrentRequest.Exception = new Exception(string.Format("[{0}] Remote server closed the connection before sending response header! Previous request state: {1}. Connection state: {2}",
                                                                                             this.ToString(),
                                                                                             this.conn.CurrentRequest.State.ToString(),
                                                                                             this.conn.State.ToString()));
                            this.conn.CurrentRequest.State = HTTPRequestStates.Error;

                            proposedConnectionState = HTTPConnectionStates.Closed;
                        }
                    }

                    this.conn.CurrentRequest = null;

                    if (proposedConnectionState == HTTPConnectionStates.Processing)
                    {
                        proposedConnectionState = HTTPConnectionStates.Recycle;
                    }

                    ConnectionEventHelper.EnqueueConnectionEvent(new ConnectionEventInfo(this.conn, proposedConnectionState));
                }
            }
        }
예제 #43
0
        public bool OnCast(Character caster, string args)
        {
            try
            {
                string[] sArgs = args.Split(" ".ToCharArray());

                Item iditem = caster.FindHeldItem(args);

                if (iditem == null)
                {
                    if (caster.RightHand != null)
                    {
                        iditem = caster.RightHand;
                    }
                    else if (caster.LeftHand != null)
                    {
                        iditem = caster.LeftHand;
                    }
                    else
                    {
                        caster.WriteToDisplay("You must hold the item to identify in your hands.");
                        return(false);
                    }
                }

                var itmeffect  = "";
                var itmspell   = "";
                var itmspecial = "";
                var itmalign   = "";
                var itmattuned = "";

                ReferenceSpell.SendGenericCastMessage(caster, caster, true);

                #region Spell and Charges
                if (iditem.spell > 0)
                {
                    var spell = GameSpell.GetSpell(iditem.spell);

                    itmspell = " It contains the spell of " + spell.Name;

                    if (iditem.charges == 0)
                    {
                        if (iditem.baseType == Globals.eItemBaseType.Scroll)
                        {
                            if (caster.IsSpellWarmingProfession && spell.IsClassSpell(caster.BaseProfession))
                            {
                                itmspell += " that you may scribe into your spellbook.";
                            }
                            else
                            {
                                itmspell += " that can be scribed into a spellbook.";
                            }
                        }
                        else
                        {
                            itmspell += ", but there are no charges remaining.";
                        }
                    }
                    else if (iditem.charges > 100)
                    {
                        itmspell += " with unlimited charges.";
                    }
                    else if (iditem.charges > 1)
                    {
                        itmspell += " with " + iditem.charges + " charges remaining.";
                    }
                    else if (iditem.charges == 1)
                    {
                        itmspell += " with 1 charge remaining.";
                    }
                    else // -1 or less
                    {
                        itmspell += " with unlimited charges.";
                    }
                }
                #endregion

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

                // Figurine info.
                if (iditem.baseType == Globals.eItemBaseType.Figurine || iditem.figExp > 0)
                {
                    sb.AppendFormat(" The {0}'s avatar has " + iditem.figExp + " experience.", iditem.name);
                }

                // Combat adds.
                if (iditem.combatAdds > 0)
                {
                    sb.AppendFormat(" The combat adds are {0}.", iditem.combatAdds);
                }

                // Silver or mithril silver.
                if (iditem.silver)
                {
                    string silver = "silver";

                    if (iditem.longDesc.ToLower().Contains("mithril") || iditem.armorType == Globals.eArmorType.Mithril)
                    {
                        silver = "mithril silver";
                    }

                    sb.AppendFormat(" The {0} is " + silver + ".", iditem.name);
                }

                // Blue glow.
                if (iditem.blueglow)
                {
                    sb.AppendFormat(" The {0} is emitting a faint blue glow.", iditem.name);
                }

                itmspecial = sb.ToString();

                //item effects
                #region Enchantments
                if (iditem.effectType.Length > 0)
                {
                    string[] itmEffectType   = iditem.effectType.Split(" ".ToCharArray());
                    string[] itmEffectAmount = iditem.effectAmount.Split(" ".ToCharArray()); // GameSpell IDs for procs

                    #region Enchantment Effects
                    if (itmEffectType.Length == 1 && Effect.GetEffectName((Effect.EffectTypes)Convert.ToInt32(itmEffectType[0])) != "")
                    {
                        if (iditem.baseType == Globals.eItemBaseType.Bottle)
                        {
                            itmeffect = " Inside the bottle is a potion of " + Effect.GetEffectName((Effect.EffectTypes)Convert.ToInt32(itmEffectType[0])) + ".";
                        }
                        else
                        {
                            string effectName = Effect.GetEffectName((Effect.EffectTypes)Convert.ToInt32(itmEffectType[0]));

                            if (effectName.ToLower() != Effect.GetEffectName(Effect.EffectTypes.None).ToLower() && effectName.ToLower() != Effect.GetEffectName(Effect.EffectTypes.Weapon_Proc))
                            {
                                itmeffect = " The " + iditem.name + " contains the enchantment of " + Effect.GetEffectName((Effect.EffectTypes)Convert.ToInt32(itmEffectType[0])) + ".";
                            }
                        }
                    }
                    else
                    {
                        var itemEffectList = new ArrayList();

                        for (int a = 0; a < itmEffectType.Length; a++)
                        {
                            Effect.EffectTypes effectType = (Effect.EffectTypes)Convert.ToInt32(itmEffectType[a]);

                            if (effectType != Effect.EffectTypes.None &&
                                effectType != Effect.EffectTypes.Weapon_Proc)
                            {
                                itemEffectList.Add(Effect.GetEffectName(effectType));
                            }
                        }

                        if (itemEffectList.Count > 0)
                        {
                            if (itemEffectList.Count > 1)
                            {
                                itmeffect = " The " + iditem.name + " contains the enchantments of";
                                for (int a = 0; a < itemEffectList.Count; a++)
                                {
                                    if (a != itemEffectList.Count - 1)
                                    {
                                        itmeffect += " " + (string)itemEffectList[a] + ",";
                                    }
                                    else
                                    {
                                        itmeffect += " and " + (string)itemEffectList[a] + ".";
                                    }
                                }
                            }
                            else if (itemEffectList.Count == 1)
                            {
                                string effectName = Effect.GetEffectName((Effect.EffectTypes)Convert.ToInt32(itmEffectType[0]));

                                if (effectName.ToLower() != "none")
                                {
                                    if (iditem.baseType == Globals.eItemBaseType.Bottle)
                                    {
                                        itmeffect = " Inside the bottle is a potion of " + Effect.GetEffectName((Effect.EffectTypes)Convert.ToInt32(itmEffectType[0])) + ".";
                                    }
                                    else
                                    {
                                        itmeffect = " The " + iditem.name + " contains the enchantment of " + Effect.GetEffectName((Effect.EffectTypes)Convert.ToInt32(itmEffectType[0])) + ".";
                                    }
                                }
                            }
                        }
                    }
                    #endregion
                }
                #endregion

                // Identify spell currently doesn't display weapon procs. 2/10/2017 Eb

                #region Alignment
                //item alignment
                if (iditem.alignment != Globals.eAlignment.None)
                {
                    string aligncolor = "";
                    switch (iditem.alignment)
                    {
                    case Globals.eAlignment.Lawful:
                        aligncolor = "white";
                        break;

                    case Globals.eAlignment.Neutral:
                        aligncolor = "green";
                        break;

                    case Globals.eAlignment.Chaotic:
                        aligncolor = "purple";
                        break;

                    case Globals.eAlignment.ChaoticEvil:
                    case Globals.eAlignment.Evil:
                        aligncolor = "red";
                        break;

                    case Globals.eAlignment.Amoral:
                        aligncolor = "yellow";
                        break;

                    default:
                        break;
                    }
                    itmalign = " The " + iditem.name + " briefly pulses with a " + aligncolor + " glow.";
                }
                #endregion

                #region Attuned
                //item attuned
                if (iditem.attunedID != 0)
                {
                    if (iditem.attunedID > 0)
                    {
                        if (iditem.attunedID == caster.UniqueID)
                        {
                            itmattuned = " The " + iditem.name + " is soulbound to you.";
                        }
                        else
                        {
                            itmattuned = " The " + iditem.name + " is soulbound to " + PC.GetName(iditem.attunedID) + ".";
                        }
                    }
                    else
                    {
                        itmattuned = " The " + iditem.name + " is soulbound to another being.";
                    }
                }
                #endregion

                //iditem.identified[iditem.identified.Length - 1] = caster.playerID;

                caster.WriteToDisplay("You are looking at " + iditem.longDesc + "." + itmeffect + itmspell + itmspecial + itmalign + itmattuned);

                #region Venom
                if (iditem.venom > 0)
                {
                    var desc = iditem.name;
                    if (iditem.baseType == Globals.eItemBaseType.Bow)
                    {
                        if (iditem.name.Contains("crossbow") || iditem.longDesc.Contains("crossbow"))
                        {
                            desc = "nocked bolt";
                        }
                        else
                        {
                            desc = "nocked arrow";
                        }
                    }

                    caster.WriteToDisplay("The " + desc + " drips with a caustic venom.");
                }
                #endregion

                return(true);
            }
            catch (Exception e)
            {
                Utils.LogException(e);
                return(false);
            }
        }
예제 #44
0
        static void OnBottomBarGUI(SceneView sceneView, Rect barSize)
        {
            //if (Event.current.type == EventType.Layout)
            //	return;

            var  snapMode          = RealtimeCSG.CSGSettings.SnapMode;
            var  uniformGrid       = RealtimeCSG.CSGSettings.UniformGrid;
            var  moveSnapVector    = RealtimeCSG.CSGSettings.SnapVector;
            var  rotationSnap      = RealtimeCSG.CSGSettings.SnapRotation;
            var  scaleSnap         = RealtimeCSG.CSGSettings.SnapScale;
            var  showGrid          = RealtimeCSG.CSGSettings.GridVisible;
            var  lockAxisX         = RealtimeCSG.CSGSettings.LockAxisX;
            var  lockAxisY         = RealtimeCSG.CSGSettings.LockAxisY;
            var  lockAxisZ         = RealtimeCSG.CSGSettings.LockAxisZ;
            var  distanceUnit      = RealtimeCSG.CSGSettings.DistanceUnit;
            var  helperSurfaces    = RealtimeCSG.CSGSettings.VisibleHelperSurfaces;
            var  showWireframe     = RealtimeCSG.CSGSettings.IsWireframeShown(sceneView);
            var  skin              = CSG_GUIStyleUtility.Skin;
            var  updateSurfaces    = false;
            bool wireframeModified = false;

            var viewWidth = sceneView.position.width;

            float layoutHeight = barSize.height;
            float layoutX      = 6.0f;

            bool modified = false;

            GUI.changed = false;
            {
                currentRect.width  = 27;
                currentRect.y      = 0;
                currentRect.height = layoutHeight - currentRect.y;
                currentRect.y     += barSize.y;
                currentRect.x      = layoutX;
                layoutX           += currentRect.width;

                #region "Grid" button
                if (showGrid)
                {
                    showGrid = GUI.Toggle(currentRect, showGrid, skin.gridIconOn, EditorStyles.toolbarButton);
                }
                else
                {
                    showGrid = GUI.Toggle(currentRect, showGrid, skin.gridIcon, EditorStyles.toolbarButton);
                }
                //(x:6.00, y:0.00, width:27.00, height:18.00)
                TooltipUtility.SetToolTip(showGridTooltip, currentRect);
                #endregion

                if (viewWidth >= 800)
                {
                    layoutX += 6;                     //(x:33.00, y:0.00, width:6.00, height:6.00)
                }
                var prevBackgroundColor   = GUI.backgroundColor;
                var lockedBackgroundColor = skin.lockedBackgroundColor;
                if (lockAxisX)
                {
                    GUI.backgroundColor = lockedBackgroundColor;
                }

                #region "X" lock button
                currentRect.width  = 17;
                currentRect.y      = 0;
                currentRect.height = layoutHeight - currentRect.y;
                currentRect.y     += barSize.y;
                currentRect.x      = layoutX;
                layoutX           += currentRect.width;

                lockAxisX = !GUI.Toggle(currentRect, !lockAxisX, xLabel, skin.xToolbarButton);
                //(x:39.00, y:0.00, width:17.00, height:18.00)
                if (lockAxisX)
                {
                    TooltipUtility.SetToolTip(xTooltipOn, currentRect);
                }
                else
                {
                    TooltipUtility.SetToolTip(xTooltipOff, currentRect);
                }
                GUI.backgroundColor = prevBackgroundColor;
                #endregion

                #region "Y" lock button
                currentRect.x = layoutX;
                layoutX      += currentRect.width;

                if (lockAxisY)
                {
                    GUI.backgroundColor = lockedBackgroundColor;
                }
                lockAxisY = !GUI.Toggle(currentRect, !lockAxisY, yLabel, skin.yToolbarButton);
                //(x:56.00, y:0.00, width:17.00, height:18.00)
                if (lockAxisY)
                {
                    TooltipUtility.SetToolTip(yTooltipOn, currentRect);
                }
                else
                {
                    TooltipUtility.SetToolTip(yTooltipOff, currentRect);
                }
                GUI.backgroundColor = prevBackgroundColor;
                #endregion

                #region "Z" lock button
                currentRect.x = layoutX;
                layoutX      += currentRect.width;

                if (lockAxisZ)
                {
                    GUI.backgroundColor = lockedBackgroundColor;
                }
                lockAxisZ = !GUI.Toggle(currentRect, !lockAxisZ, zLabel, skin.zToolbarButton);
                //(x:56.00, y:0.00, width:17.00, height:18.00)
                if (lockAxisZ)
                {
                    TooltipUtility.SetToolTip(zTooltipOn, currentRect);
                }
                else
                {
                    TooltipUtility.SetToolTip(zTooltipOff, currentRect);
                }
                GUI.backgroundColor = prevBackgroundColor;
                #endregion
            }
            modified = GUI.changed || modified;

            if (viewWidth >= 800)
            {
                layoutX += 6;                 // (x:91.00, y:0.00, width:6.00, height:6.00)
            }
            #region "SnapMode" button
            GUI.changed = false;
            {
                currentRect.width  = 27;
                currentRect.y      = 0;
                currentRect.height = layoutHeight - currentRect.y;
                currentRect.y     += barSize.y;
                currentRect.x      = layoutX;
                layoutX           += currentRect.width;


                switch (snapMode)
                {
                case SnapMode.GridSnapping:
                {
                    var newValue = GUI.Toggle(currentRect, snapMode == SnapMode.GridSnapping, CSG_GUIStyleUtility.Skin.gridSnapIconOn, EditorStyles.toolbarButton);
                    if (GUI.changed)
                    {
                        snapMode = newValue ? SnapMode.GridSnapping : SnapMode.RelativeSnapping;
                        //Debug.Log($"SnapMode.GridSnapping {snapMode}");
                    }
                    //(x:97.00, y:0.00, width:27.00, height:18.00)
                    TooltipUtility.SetToolTip(gridSnapModeTooltip, currentRect);
                    break;
                }

                case SnapMode.RelativeSnapping:
                {
                    var newValue = GUI.Toggle(currentRect, snapMode == SnapMode.RelativeSnapping, CSG_GUIStyleUtility.Skin.relSnapIconOn, EditorStyles.toolbarButton);
                    if (GUI.changed)
                    {
                        snapMode = newValue ? SnapMode.RelativeSnapping : SnapMode.None;
                        //Debug.Log($"SnapMode.RelativeSnapping {snapMode}");
                    }
                    //(x:97.00, y:0.00, width:27.00, height:18.00)
                    TooltipUtility.SetToolTip(relativeSnapModeTooltip, currentRect);
                    break;
                }

                default:
                case SnapMode.None:
                {
                    var newValue = GUI.Toggle(currentRect, snapMode != SnapMode.None, CSG_GUIStyleUtility.Skin.noSnapIconOn, EditorStyles.toolbarButton);
                    if (GUI.changed)
                    {
                        snapMode = newValue ? SnapMode.GridSnapping : SnapMode.None;
                        //Debug.Log($"SnapMode.None {snapMode}");
                    }
                    //(x:97.00, y:0.00, width:27.00, height:18.00)
                    TooltipUtility.SetToolTip(noSnappingModeTooltip, currentRect);
                    break;
                }
                }
            }
            modified = GUI.changed || modified;
            #endregion

            if (viewWidth >= 460)
            {
                if (snapMode != SnapMode.None)
                {
                    #region "Position" label
                    if (viewWidth >= 500)
                    {
                        if (viewWidth >= 865)
                        {
                            currentRect.width  = 44;
                            currentRect.y      = 1;
                            currentRect.height = layoutHeight - currentRect.y;
                            currentRect.y     += barSize.y;
                            currentRect.x      = layoutX;
                            layoutX           += currentRect.width;

                            uniformGrid = GUI.Toggle(currentRect, uniformGrid, positionLargeLabel, miniTextStyle);
                            //(x:128.00, y:2.00, width:44.00, height:16.00)

                            TooltipUtility.SetToolTip(positionTooltip, currentRect);
                        }
                        else
                        {
                            currentRect.width  = 22;
                            currentRect.y      = 1;
                            currentRect.height = layoutHeight - currentRect.y;
                            currentRect.y     += barSize.y;
                            currentRect.x      = layoutX;
                            layoutX           += currentRect.width;

                            uniformGrid = GUI.Toggle(currentRect, uniformGrid, positionSmallLabel, miniTextStyle);
                            //(x:127.00, y:2.00, width:22.00, height:16.00)

                            TooltipUtility.SetToolTip(positionTooltip, currentRect);
                        }
                    }
                    #endregion

                    layoutX += 2;

                    #region "Position" field
                    if (uniformGrid || viewWidth < 515)
                    {
                        EditorGUI.showMixedValue = !(moveSnapVector.x == moveSnapVector.y && moveSnapVector.x == moveSnapVector.z);
                        GUI.changed = false;
                        {
                            currentRect.width  = 70;
                            currentRect.y      = 3;
                            currentRect.height = layoutHeight - (currentRect.y - 1);
                            currentRect.y     += barSize.y;
                            currentRect.x      = layoutX;
                            layoutX           += currentRect.width;

                            moveSnapVector.x = Units.DistanceUnitToUnity(distanceUnit, EditorGUI.DoubleField(currentRect, Units.UnityToDistanceUnit(distanceUnit, moveSnapVector.x), textInputStyle));                            //, MinSnapWidth, MaxSnapWidth));
                            //(x:176.00, y:3.00, width:70.00, height:16.00)
                        }
                        if (GUI.changed)
                        {
                            modified         = true;
                            moveSnapVector.y = moveSnapVector.x;
                            moveSnapVector.z = moveSnapVector.x;
                        }
                        EditorGUI.showMixedValue = false;
                    }
                    else
                    {
                        GUI.changed = false;
                        {
                            currentRect.width  = 70;
                            currentRect.y      = 3;
                            currentRect.height = layoutHeight - (currentRect.y - 1);
                            currentRect.y     += barSize.y;
                            currentRect.x      = layoutX;
                            layoutX           += currentRect.width;
                            layoutX++;

                            moveSnapVector.x = Units.DistanceUnitToUnity(distanceUnit, EditorGUI.DoubleField(currentRect, Units.UnityToDistanceUnit(distanceUnit, moveSnapVector.x), textInputStyle));                            //, MinSnapWidth, MaxSnapWidth));
                            //(x:175.00, y:3.00, width:70.00, height:16.00)


                            currentRect.x = layoutX;
                            layoutX      += currentRect.width;
                            layoutX++;

                            moveSnapVector.y = Units.DistanceUnitToUnity(distanceUnit, EditorGUI.DoubleField(currentRect, Units.UnityToDistanceUnit(distanceUnit, moveSnapVector.y), textInputStyle));                            //, MinSnapWidth, MaxSnapWidth));
                            //(x:247.00, y:3.00, width:70.00, height:16.00)


                            currentRect.x = layoutX;
                            layoutX      += currentRect.width;

                            moveSnapVector.z = Units.DistanceUnitToUnity(distanceUnit, EditorGUI.DoubleField(currentRect, Units.UnityToDistanceUnit(distanceUnit, moveSnapVector.z), textInputStyle));                            //, MinSnapWidth, MaxSnapWidth));
                            //(x:319.00, y:3.00, width:70.00, height:16.00)
                        }
                        modified = GUI.changed || modified;
                    }
                    #endregion

                    layoutX++;

                    #region "Position" Unit
                    DistanceUnit nextUnit = Units.CycleToNextUnit(distanceUnit);
                    GUIContent   unitText = Units.GetUnitGUIContent(distanceUnit);

                    currentRect.width  = 22;
                    currentRect.y      = 2;
                    currentRect.height = layoutHeight - currentRect.y;
                    currentRect.y     += barSize.y;
                    currentRect.x      = layoutX;
                    layoutX           += currentRect.width;

                    if (GUI.Button(currentRect, unitText, miniTextStyle))                    //(x:393.00, y:2.00, width:13.00, height:16.00)
                    {
                        distanceUnit = nextUnit;
                        modified     = true;
                    }
                    #endregion

                    layoutX += 2;

                    #region "Position" +/-
                    if (viewWidth >= 700)
                    {
                        currentRect.width  = 19;
                        currentRect.y      = 2;
                        currentRect.height = layoutHeight - (currentRect.y + 1);
                        currentRect.y     += barSize.y;
                        currentRect.x      = layoutX;
                        layoutX           += currentRect.width;

                        if (GUI.Button(currentRect, positionPlusLabel, EditorStyles.miniButtonLeft))
                        {
                            GridUtility.DoubleGridSize(); moveSnapVector = RealtimeCSG.CSGSettings.SnapVector;
                        }
                        //(x:410.00, y:2.00, width:19.00, height:15.00)
                        TooltipUtility.SetToolTip(positionPlusTooltip, currentRect);

                        currentRect.width  = 17;
                        currentRect.y      = 2;
                        currentRect.height = layoutHeight - (currentRect.y + 1);
                        currentRect.y     += barSize.y;
                        currentRect.x      = layoutX;
                        layoutX           += currentRect.width;

                        if (GUI.Button(currentRect, positionMinusLabel, EditorStyles.miniButtonRight))
                        {
                            GridUtility.HalfGridSize(); moveSnapVector = RealtimeCSG.CSGSettings.SnapVector;
                        }
                        //(x:429.00, y:2.00, width:17.00, height:15.00)
                        TooltipUtility.SetToolTip(positionMinnusTooltip, currentRect);
                    }
                    #endregion

                    layoutX += 2;

                    #region "Angle" label
                    if (viewWidth >= 750)
                    {
                        if (viewWidth >= 865)
                        {
                            currentRect.width  = 31;
                            currentRect.y      = 1;
                            currentRect.height = layoutHeight - currentRect.y;
                            currentRect.y     += barSize.y;
                            currentRect.x      = layoutX;
                            layoutX           += currentRect.width;

                            GUI.Label(currentRect, angleLargeLabel, miniTextStyle);
                            //(x:450.00, y:2.00, width:31.00, height:16.00)
                        }
                        else
                        {
                            currentRect.width  = 22;
                            currentRect.y      = 1;
                            currentRect.height = layoutHeight - currentRect.y;
                            currentRect.y     += barSize.y;
                            currentRect.x      = layoutX;
                            layoutX           += currentRect.width;

                            GUI.Label(currentRect, angleSmallLabel, miniTextStyle);
                            //(x:355.00, y:2.00, width:22.00, height:16.00)
                        }
                        TooltipUtility.SetToolTip(angleTooltip, currentRect);
                    }
                    #endregion

                    layoutX += 2;

                    #region "Angle" field
                    GUI.changed = false;
                    {
                        currentRect.width  = 70;
                        currentRect.y      = 3;
                        currentRect.height = layoutHeight - (currentRect.y - 1);
                        currentRect.y     += barSize.y;
                        currentRect.x      = layoutX;
                        layoutX           += currentRect.width;

                        rotationSnap = EditorGUI.FloatField(currentRect, rotationSnap, textInputStyle);                        //, MinSnapWidth, MaxSnapWidth);
                        //(x:486.00, y:3.00, width:70.00, height:16.00)
                        if (viewWidth <= 750)
                        {
                            TooltipUtility.SetToolTip(angleTooltip, currentRect);
                        }
                    }
                    modified = GUI.changed || modified;
                    #endregion

                    layoutX++;

                    #region "Angle" Unit
                    if (viewWidth >= 370)
                    {
                        currentRect.width  = 14;
                        currentRect.y      = 1;
                        currentRect.height = layoutHeight - currentRect.y;
                        currentRect.y     += barSize.y;
                        currentRect.x      = layoutX;
                        layoutX           += currentRect.width;

                        GUI.Label(currentRect, angleUnitLabel, miniTextStyle);
                    }
                    #endregion

                    layoutX += 2;

                    #region "Angle" +/-
                    if (viewWidth >= 700)
                    {
                        currentRect.width  = 19;
                        currentRect.y      = 1;
                        currentRect.height = layoutHeight - (currentRect.y + 1);
                        currentRect.y     += barSize.y;
                        currentRect.x      = layoutX;
                        layoutX           += currentRect.width;

                        if (GUI.Button(currentRect, anglePlusLabel, EditorStyles.miniButtonLeft))
                        {
                            rotationSnap *= 2.0f; modified = true;
                        }
                        //(x:573.00, y:2.00, width:19.00, height:15.00)
                        TooltipUtility.SetToolTip(anglePlusTooltip, currentRect);


                        currentRect.width  = 17;
                        currentRect.y      = 1;
                        currentRect.height = layoutHeight - (currentRect.y + 1);
                        currentRect.y     += barSize.y;
                        currentRect.x      = layoutX;
                        layoutX           += currentRect.width;

                        if (GUI.Button(currentRect, angleMinusLabel, EditorStyles.miniButtonRight))
                        {
                            rotationSnap /= 2.0f; modified = true;
                        }
                        //(x:592.00, y:2.00, width:17.00, height:15.00)
                        TooltipUtility.SetToolTip(angleMinnusTooltip, currentRect);
                    }
                    #endregion

                    layoutX += 2;

                    #region "Scale" label
                    if (viewWidth >= 750)
                    {
                        if (viewWidth >= 865)
                        {
                            currentRect.width  = 31;
                            currentRect.y      = 1;
                            currentRect.height = layoutHeight - currentRect.y;
                            currentRect.y     += barSize.y;
                            currentRect.x      = layoutX;
                            layoutX           += currentRect.width;

                            GUI.Label(currentRect, scaleLargeLabel, miniTextStyle);
                            //(x:613.00, y:2.00, width:31.00, height:16.00)
                        }
                        else
                        {
                            currentRect.width  = 19;
                            currentRect.y      = 1;
                            currentRect.height = layoutHeight - currentRect.y;
                            currentRect.y     += barSize.y;
                            currentRect.x      = layoutX;
                            layoutX           += currentRect.width;

                            GUI.Label(currentRect, scaleSmallLabel, miniTextStyle);
                            //(x:495.00, y:2.00, width:19.00, height:16.00)
                        }
                        TooltipUtility.SetToolTip(scaleTooltip, currentRect);
                    }
                    #endregion

                    layoutX += 2;

                    #region "Scale" field
                    GUI.changed = false;
                    {
                        currentRect.width  = 70;
                        currentRect.y      = 3;
                        currentRect.height = layoutHeight - (currentRect.y - 1);
                        currentRect.y     += barSize.y;
                        currentRect.x      = layoutX;
                        layoutX           += currentRect.width;

                        scaleSnap = EditorGUI.FloatField(currentRect, scaleSnap, textInputStyle);                        //, MinSnapWidth, MaxSnapWidth);
                        //(x:648.00, y:3.00, width:70.00, height:16.00)
                        if (viewWidth <= 750)
                        {
                            TooltipUtility.SetToolTip(scaleTooltip, currentRect);
                        }
                    }
                    modified = GUI.changed || modified;
                    #endregion

                    layoutX++;

                    #region "Scale" Unit
                    if (viewWidth >= 370)
                    {
                        currentRect.width  = 15;
                        currentRect.y      = 1;
                        currentRect.height = layoutHeight - currentRect.y;
                        currentRect.y     += barSize.y;
                        currentRect.x      = layoutX;
                        layoutX           += currentRect.width;

                        GUI.Label(currentRect, scaleUnitLabel, miniTextStyle);
                        //(x:722.00, y:2.00, width:15.00, height:16.00)
                    }
                    #endregion

                    layoutX += 2;

                    #region "Scale" +/-
                    if (viewWidth >= 700)
                    {
                        currentRect.width  = 19;
                        currentRect.y      = 2;
                        currentRect.height = layoutHeight - (currentRect.y + 1);
                        currentRect.y     += barSize.y;
                        currentRect.x      = layoutX;
                        layoutX           += currentRect.width;

                        if (GUI.Button(currentRect, scalePlusLabel, EditorStyles.miniButtonLeft))
                        {
                            scaleSnap *= 10.0f; modified = true;
                        }
                        //(x:741.00, y:2.00, width:19.00, height:15.00)
                        TooltipUtility.SetToolTip(scalePlusTooltip, currentRect);


                        currentRect.width  = 17;
                        currentRect.y      = 2;
                        currentRect.height = layoutHeight - (currentRect.y + 1);
                        currentRect.y     += barSize.y;
                        currentRect.x      = layoutX;
                        layoutX           += currentRect.width;

                        if (GUI.Button(currentRect, scaleMinusLabel, EditorStyles.miniButtonRight))
                        {
                            scaleSnap /= 10.0f; modified = true;
                        }
                        //(x:760.00, y:2.00, width:17.00, height:15.00)
                        TooltipUtility.SetToolTip(scaleMinnusTooltip, currentRect);
                    }
                    #endregion
                }
            }


            var prevLayoutX = layoutX;

            layoutX = viewWidth;


            #region "Rebuild"
            currentRect.width  = 27;
            currentRect.y      = 0;
            currentRect.height = layoutHeight - currentRect.y;
            currentRect.y     += barSize.y;
            layoutX           -= currentRect.width;
            currentRect.x      = layoutX;

            if (GUI.Button(currentRect, CSG_GUIStyleUtility.Skin.rebuildIcon, EditorStyles.toolbarButton))
            {
                Debug.Log("Starting complete rebuild");

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

                MaterialUtility.ResetMaterialTypeLookup();

                InternalCSGModelManager.skipCheckForChanges = true;
                RealtimeCSG.CSGSettings.Reload();
                UnityCompilerDefineManager.UpdateUnityDefines();

                InternalCSGModelManager.registerTime          = 0.0;
                InternalCSGModelManager.validateTime          = 0.0;
                InternalCSGModelManager.hierarchyValidateTime = 0.0;
                InternalCSGModelManager.updateHierarchyTime   = 0.0;

                var startTime = EditorApplication.timeSinceStartup;
                InternalCSGModelManager.ForceRebuildAll();
                InternalCSGModelManager.OnHierarchyModified();
                var hierarchy_update_endTime = EditorApplication.timeSinceStartup;
                text.AppendFormat(CultureInfo.InvariantCulture, "Full hierarchy rebuild in {0:F} ms. ", (hierarchy_update_endTime - startTime) * 1000);


                NativeMethodBindings.RebuildAll();
                var csg_endTime = EditorApplication.timeSinceStartup;
                text.AppendFormat(CultureInfo.InvariantCulture, "Full CSG rebuild done in {0:F} ms. ", (csg_endTime - hierarchy_update_endTime) * 1000);

                InternalCSGModelManager.RemoveForcedUpdates();                 // we already did this in rebuild all
                InternalCSGModelManager.UpdateMeshes(text, forceUpdate: true);

                updateSurfaces = true;
                UpdateLoop.ResetUpdateRoutine();
                RealtimeCSG.CSGSettings.Save();
                InternalCSGModelManager.skipCheckForChanges = false;

                var scenes = new HashSet <UnityEngine.SceneManagement.Scene>();
                foreach (var model in InternalCSGModelManager.Models)
                {
                    scenes.Add(model.gameObject.scene);
                }

                foreach (var scene in scenes)
                {
                    UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(scene);
                }

                text.AppendFormat(CultureInfo.InvariantCulture, "{0} brushes. ", Foundation.CSGManager.TreeBrushCount);

                Debug.Log(text.ToString());
            }
            //(x:1442.00, y:0.00, width:27.00, height:18.00)
            TooltipUtility.SetToolTip(rebuildTooltip, currentRect);
            #endregion

            if (viewWidth >= 800)
            {
                layoutX -= 6;                 //(x:1436.00, y:0.00, width:6.00, height:6.00)
            }
            #region "Helper Surface Flags" Mask
            if (viewWidth >= 250)
            {
                GUI.changed = false;
                {
                    prevLayoutX += 8;                      // extra space
                    prevLayoutX += 26;                     // width of "Show wireframe" button

                    currentRect.width = Mathf.Max(20, Mathf.Min(165, (viewWidth - prevLayoutX - currentRect.width)));

                    currentRect.y      = 0;
                    currentRect.height = layoutHeight - currentRect.y;
                    currentRect.y     += barSize.y;
                    layoutX           -= currentRect.width;
                    currentRect.x      = layoutX;

                    SurfaceVisibilityPopup.Button(currentRect);

                    //(x:1267.00, y:2.00, width:165.00, height:16.00)
                    TooltipUtility.SetToolTip(helperSurfacesTooltip, currentRect);
                }
                if (GUI.changed)
                {
                    updateSurfaces = true;
                    modified       = true;
                }
            }
            #endregion

            #region "Show wireframe" button
            GUI.changed        = false;
            currentRect.width  = 26;
            currentRect.y      = 0;
            currentRect.height = layoutHeight - currentRect.y;
            currentRect.y     += barSize.y;
            layoutX           -= currentRect.width;
            currentRect.x      = layoutX;

            if (showWireframe)
            {
                showWireframe = GUI.Toggle(currentRect, showWireframe, CSG_GUIStyleUtility.Skin.wireframe, EditorStyles.toolbarButton);
                //(x:1237.00, y:0.00, width:26.00, height:18.00)
            }
            else
            {
                showWireframe = GUI.Toggle(currentRect, showWireframe, CSG_GUIStyleUtility.Skin.wireframeOn, EditorStyles.toolbarButton);
                //(x:1237.00, y:0.00, width:26.00, height:18.00)
            }
            TooltipUtility.SetToolTip(showWireframeTooltip, currentRect);
            if (GUI.changed)
            {
                wireframeModified = true;
                modified          = true;
            }
            #endregion



            #region Capture mouse clicks in empty space
            var mousePoint = Event.current.mousePosition;
            int controlID  = GUIUtility.GetControlID(BottomBarEditorOverlayHash, FocusType.Passive, barSize);
            switch (Event.current.GetTypeForControl(controlID))
            {
            case EventType.MouseDown:       { if (barSize.Contains(mousePoint))
                                              {
                                                  GUIUtility.hotControl = controlID; GUIUtility.keyboardControl = controlID; Event.current.Use();
                                              }
                                              break; }

            case EventType.MouseMove:       { if (barSize.Contains(mousePoint))
                                              {
                                                  Event.current.Use();
                                              }
                                              break; }

            case EventType.MouseUp:         { if (GUIUtility.hotControl == controlID)
                                              {
                                                  GUIUtility.hotControl = 0; GUIUtility.keyboardControl = 0; Event.current.Use();
                                              }
                                              break; }

            case EventType.MouseDrag:       { if (GUIUtility.hotControl == controlID)
                                              {
                                                  Event.current.Use();
                                              }
                                              break; }

            case EventType.ScrollWheel: { if (barSize.Contains(mousePoint))
                                          {
                                              Event.current.Use();
                                          }
                                          break; }
            }
            #endregion



            #region Store modified values
            rotationSnap     = Mathf.Max(1.0f, Mathf.Abs((360 + (rotationSnap % 360))) % 360);
            moveSnapVector.x = Mathf.Max(1.0f / 1024.0f, moveSnapVector.x);
            moveSnapVector.y = Mathf.Max(1.0f / 1024.0f, moveSnapVector.y);
            moveSnapVector.z = Mathf.Max(1.0f / 1024.0f, moveSnapVector.z);

            scaleSnap = Mathf.Max(MathConstants.MinimumScale, scaleSnap);

            RealtimeCSG.CSGSettings.SnapMode     = snapMode;
            RealtimeCSG.CSGSettings.SnapVector   = moveSnapVector;
            RealtimeCSG.CSGSettings.SnapRotation = rotationSnap;
            RealtimeCSG.CSGSettings.SnapScale    = scaleSnap;
            RealtimeCSG.CSGSettings.UniformGrid  = uniformGrid;
//			RealtimeCSG.Settings.SnapVertex					= vertexSnap;
            RealtimeCSG.CSGSettings.GridVisible           = showGrid;
            RealtimeCSG.CSGSettings.LockAxisX             = lockAxisX;
            RealtimeCSG.CSGSettings.LockAxisY             = lockAxisY;
            RealtimeCSG.CSGSettings.LockAxisZ             = lockAxisZ;
            RealtimeCSG.CSGSettings.DistanceUnit          = distanceUnit;
            RealtimeCSG.CSGSettings.VisibleHelperSurfaces = helperSurfaces;

            if (wireframeModified)
            {
                RealtimeCSG.CSGSettings.SetWireframeShown(sceneView, showWireframe);
            }

            if (updateSurfaces)
            {
                MeshInstanceManager.UpdateHelperSurfaceVisibility(force: true);
            }

            if (modified)
            {
                GUI.changed = true;
                RealtimeCSG.CSGSettings.UpdateSnapSettings();
                RealtimeCSG.CSGSettings.Save();
                CSG_EditorGUIUtility.UpdateSceneViews();
            }
            #endregion
        }
예제 #45
0
        } // End Function EscapeString

        // https://github.com/mono/mono/blob/master/mcs/class/System.Json/System.Json/JsonValue.cs
        // https://github.com/mono/mono/blob/master/mcs/class/System.Web/System.Web/HttpUtility.cs
        public static string JavaScriptStringEncode(string value, bool addDoubleQuotes)
        {
            if (string.IsNullOrEmpty(value))
            {
                return(addDoubleQuotes ? "\"\"" : string.Empty);
            }

            int  len        = value.Length;
            bool needEncode = false;
            char c;

            for (int i = 0; i < len; i++)
            {
                c = value[i];

                if (c >= 0 && c <= 31 || c == 34 || c == 39 || c == 60 || c == 62 || c == 92)
                {
                    needEncode = true;
                    break;
                } // End if (c >= 0 && c <= 31 || c == 34 || c == 39 || c == 60 || c == 62 || c == 92)
            }     // Next i

            if (!needEncode)
            {
                return(addDoubleQuotes ? "\"" + value + "\"" : value);
            }

            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            if (addDoubleQuotes)
            {
                sb.Append('"');
            }

            for (int i = 0; i < len; i++)
            {
                c = value[i];
                if (c >= 0 && c <= 7 || c == 11 || c >= 14 && c <= 31 || c == 39 || c == 60 || c == 62)
                {
                    sb.AppendFormat("\\u{0:x4}", (int)c);
                }
                else
                {
                    switch ((int)c)
                    {
                    case 8:
                        sb.Append("\\b");
                        break;

                    case 9:
                        sb.Append("\\t");
                        break;

                    case 10:
                        sb.Append("\\n");
                        break;

                    case 12:
                        sb.Append("\\f");
                        break;

                    case 13:
                        sb.Append("\\r");
                        break;

                    case 34:
                        sb.Append("\\\"");
                        break;

                    case 92:
                        sb.Append("\\\\");
                        break;

                    default:
                        sb.Append(c);
                        break;
                    } // End switch ((int)c)
                }
            }         // Next i

            if (addDoubleQuotes)
            {
                sb.Append('"');
            }

            return(sb.ToString());
        } // End Function JavaScriptStringEncode
예제 #46
0
        Serialize(
            System.Text.StringBuilder text,
            int indentLevel)
        {
            var indent  = new string('\t', indentLevel);
            var indent2 = new string('\t', indentLevel + 1);
            var indent3 = new string('\t', indentLevel + 2);

            text.AppendFormat("{0}{1} /* {2} */ = {{", indent, this.GUID, this.Name);
            text.AppendLine();
            text.AppendFormat("{0}isa = {1};", indent2, this.IsA);
            text.AppendLine();
            text.AppendFormat("{0}buildConfigurationList = {1} /* Build configuration list for {2} \"{3}\" */;", indent2, this.ConfigurationList.GUID, this.ConfigurationList.Parent.IsA, this.ConfigurationList.Parent.Name);
            text.AppendLine();
            if (((null != this.BuildPhases) && (this.BuildPhases.Count > 0)) ||
                (null != this.PreBuildBuildPhase) ||
                (null != this.PostBuildBuildPhase))
            {
                // make sure that pre-build phases appear first
                // then any regular build phases
                // and then post-build phases.
                // any of these can be missing

                text.AppendFormat("{0}buildPhases = (", indent2);
                text.AppendLine();
                System.Action <BuildPhase> dumpPhase = (phase) =>
                {
                    text.AppendFormat("{0}{1} /* {2} */,", indent3, phase.GUID, phase.Name);
                    text.AppendLine();
                };
                if (null != this.PreBuildBuildPhase)
                {
                    dumpPhase(this.PreBuildBuildPhase);
                }
                if (null != this.BuildPhases)
                {
                    foreach (var phase in this.BuildPhases)
                    {
                        dumpPhase(phase);
                    }
                }
                if (null != this.PostBuildBuildPhase)
                {
                    dumpPhase(this.PostBuildBuildPhase);
                }
                text.AppendFormat("{0});", indent2);
                text.AppendLine();
            }
            text.AppendFormat("{0}buildRules = (", indent2);
            text.AppendLine();
            text.AppendFormat("{0});", indent2);
            text.AppendLine();
            text.AppendFormat("{0}dependencies = (", indent2);
            text.AppendLine();
            foreach (var dependency in this.TargetDependencies)
            {
                text.AppendFormat("{0}{1} /* {2} */,", indent3, dependency.GUID, dependency.Name);
                text.AppendLine();
            }
            text.AppendFormat("{0});", indent2);
            text.AppendLine();
            text.AppendFormat("{0}name = {1};", indent2, this.Name);
            text.AppendLine();
            text.AppendFormat("{0}productName = {1};", indent2, this.Name);
            text.AppendLine();
            if (null != this.FileReference)
            {
                text.AppendFormat("{0}productReference = {1} /* {2} */;", indent2, this.FileReference.GUID, this.FileReference.Name);
                text.AppendLine();
            }
            text.AppendFormat("{0}productType = \"{1}\";", indent2, this.ProductTypeToString());
            text.AppendLine();
            text.AppendFormat("{0}}};", indent);
            text.AppendLine();
        }
예제 #47
0
        /// <summary>
        /// Procedure to execute a Find query. Although the full query results are retrieved from the DB and stored
        /// internally in an object, data will be returned in 'pages' of data, each page holding a defined number
        /// of records.
        /// </summary>
        /// <param name="ACriteriaData">HashTable containing non-empty Find parameters.</param>
        public void PerformSearch(DataTable ACriteriaData)
        {
            String    CustomWhereCriteria;
            Hashtable ColumnNameMapping;

            OdbcParameter[] ParametersArray;
            String          FieldList;
            String          FromClause;
            String          WhereClause;

            System.Text.StringBuilder sb;
            TLogging.LogAtLevel(7, "TGiftDetailFind.PerformSearch called.");

            FPagedDataSetObject = new TPagedDataSet(new GiftBatchTDSAGiftDetailTable());

            // Build WHERE criteria string based on AFindCriteria
            CustomWhereCriteria = BuildCustomWhereCriteria(ACriteriaData, out ParametersArray);

            //
            // Set up find parameters
            //
            ColumnNameMapping = new Hashtable();

            // Create Field List
            sb = new System.Text.StringBuilder();
            sb.AppendFormat("{0},{1}", "PUB.a_gift_detail.a_batch_number_i", Environment.NewLine);
            sb.AppendFormat("{0},{1}", "PUB.a_gift_detail.a_gift_transaction_number_i", Environment.NewLine);
            sb.AppendFormat("{0},{1}", "PUB.a_gift_detail.a_detail_number_i", Environment.NewLine);
            sb.AppendFormat("{0},{1}", "PUB.a_gift_detail.a_confidential_gift_flag_l", Environment.NewLine);
            sb.AppendFormat("{0},{1}", "PUB.a_gift_detail.a_gift_amount_n", Environment.NewLine);
            sb.AppendFormat("{0},{1}", "PUB.a_gift.a_receipt_number_i", Environment.NewLine);
            sb.AppendFormat("{0},{1}", "DonorPartner.p_partner_short_name_c DonorPartnerShortName", Environment.NewLine);
            sb.AppendFormat("{0},{1}", "RecipientPartner.p_partner_short_name_c RecipientPartnerShortName", Environment.NewLine);
            sb.AppendFormat("{0},{1}", "PUB.a_gift_detail.a_motivation_group_code_c", Environment.NewLine);
            sb.AppendFormat("{0},{1}", "PUB.a_gift_detail.a_motivation_detail_code_c", Environment.NewLine);
            sb.AppendFormat("{0},{1}", "PUB.a_gift.a_date_entered_d", Environment.NewLine);
            sb.AppendFormat("{0},{1}", "PUB.a_gift_detail.a_cost_centre_code_c", Environment.NewLine);
            sb.AppendFormat("{0},{1}", "PUB.a_gift_detail.a_gift_comment_one_c", Environment.NewLine);
            sb.AppendFormat("{0},{1}", "PUB.a_gift_detail.a_gift_comment_two_c", Environment.NewLine);
            sb.AppendFormat("{0},{1}", "PUB.a_gift_detail.a_gift_comment_three_c", Environment.NewLine);
            sb.AppendFormat("{0},{1}", "PUB.a_gift_batch.a_batch_status_c", Environment.NewLine);
            sb.AppendFormat("{0},{1}", "PUB.a_gift_batch.a_batch_period_i", Environment.NewLine);
            sb.AppendFormat("{0}{1}", "PUB.a_gift_batch.a_batch_year_i", Environment.NewLine);

            // short
            FieldList = sb.ToString();

            // Create FROM From Clause
            sb = new System.Text.StringBuilder();
            System.Text.StringBuilder sbWhereClause = new System.Text.StringBuilder();

            sb.AppendFormat("{0},{1}", "PUB.a_gift_detail", Environment.NewLine);
            sb.AppendFormat("{0},{1}", "PUB.a_gift", Environment.NewLine);
            sb.AppendFormat("{0},{1}", "PUB.a_gift_batch", Environment.NewLine);
            sb.AppendFormat("{0},{1}", "PUB.p_partner DonorPartner", Environment.NewLine);
            sb.AppendFormat("{0}{1}", "PUB.p_partner RecipientPartner", Environment.NewLine);
            sbWhereClause.AppendFormat("{0}{1}",
                                       "DonorPartner.p_partner_key_n = PUB.a_gift.p_donor_key_n " +
                                       "AND RecipientPartner.p_partner_key_n = PUB.a_gift_detail.p_recipient_key_n " +
                                       "AND PUB.a_gift.a_ledger_number_i = PUB.a_gift_detail.a_ledger_number_i " +
                                       "AND PUB.a_gift.a_batch_number_i = PUB.a_gift_detail.a_batch_number_i " +
                                       "AND PUB.a_gift.a_gift_transaction_number_i = PUB.a_gift_detail.a_gift_transaction_number_i " +
                                       "AND PUB.a_gift_batch.a_ledger_number_i = PUB.a_gift_detail.a_ledger_number_i " +
                                       "AND PUB.a_gift_batch.a_batch_number_i = PUB.a_gift_detail.a_batch_number_i", Environment.NewLine);

            FromClause  = sb.ToString();
            WhereClause = CustomWhereCriteria;

            if (WhereClause.StartsWith(" AND") == true)
            {
                WhereClause = WhereClause.Substring(4);
            }

            if (sbWhereClause.ToString().Length > 0)
            {
                WhereClause += " AND " + sbWhereClause.ToString();
            }

            FPagedDataSetObject.FindParameters = new TPagedDataSet.TAsyncFindParameters(FieldList,
                                                                                        FromClause,
                                                                                        WhereClause,
                                                                                        "PUB.a_gift_detail.a_batch_number_i, PUB.a_gift_detail.a_gift_transaction_number_i, PUB.a_gift_detail.a_detail_number_i",
                                                                                        ColumnNameMapping,
                                                                                        ParametersArray);

            string session = TSession.GetSessionID();

            //
            // Start the Find Thread
            //
            try
            {
                ThreadStart myThreadStart = delegate {
                    FPagedDataSetObject.ExecuteQuery(session);
                };
                FFindThread      = new Thread(myThreadStart);
                FFindThread.Name = "GiftDetailFind" + Guid.NewGuid().ToString();
                FFindThread.Start();
            }
            catch (Exception)
            {
                throw;
            }
        }
예제 #48
0
        /// <summary>
        /// Retrieves the specified metrics and displays them in textual form.
        /// </summary>
        /// <param name="effect">The AnimationEffect whose metrics are to be displayed.</param>
        /// <param name="target">The AnimationEffecTarget whose metrics are to be displayed.</param>
        private void DisplayMetrics(AnimationEffect effect, AnimationEffectTarget target)
        {
            var s = new System.Text.StringBuilder();
            AnimationDescription animationDescription = new AnimationDescription(effect, target);

            s.AppendFormat("Stagger delay = {0}ms", animationDescription.StaggerDelay.TotalMilliseconds);
            s.AppendLine();
            s.AppendFormat("Stagger delay factor = {0}", animationDescription.StaggerDelayFactor);
            s.AppendLine();
            s.AppendFormat("Delay limit = {0}ms", animationDescription.DelayLimit.TotalMilliseconds);
            s.AppendLine();
            s.AppendFormat("ZOrder = {0}", animationDescription.ZOrder);
            s.AppendLine();
            s.AppendLine();

            int animationIndex = 0;

            foreach (var animation in animationDescription.Animations)
            {
                s.AppendFormat("Animation #{0}:", ++animationIndex);
                s.AppendLine();

                switch (animation.Type)
                {
                case PropertyAnimationType.Scale:
                {
                    ScaleAnimation scale = animation as ScaleAnimation;
                    s.AppendLine("Type = Scale");
                    if (scale.InitialScaleX.HasValue)
                    {
                        s.AppendFormat("InitialScaleX = {0}", scale.InitialScaleX.Value);
                        s.AppendLine();
                    }
                    if (scale.InitialScaleY.HasValue)
                    {
                        s.AppendFormat("InitialScaleY = {0}", scale.InitialScaleY.Value);
                        s.AppendLine();
                    }
                    s.AppendFormat("FinalScaleX = {0}", scale.FinalScaleX);
                    s.AppendLine();
                    s.AppendFormat("FinalScaleY = {0}", scale.FinalScaleY);
                    s.AppendLine();
                    s.AppendFormat("Origin = {0}, {1}", scale.NormalizedOrigin.X, scale.NormalizedOrigin.Y);
                    s.AppendLine();
                }
                break;

                case PropertyAnimationType.Translation:
                    s.AppendLine("Type = Translation");
                    break;

                case PropertyAnimationType.Opacity:
                {
                    OpacityAnimation opacity = animation as OpacityAnimation;
                    s.AppendLine("Type = Opacity");
                    if (opacity.InitialOpacity.HasValue)
                    {
                        s.AppendFormat("InitialOpacity = {0}", opacity.InitialOpacity.Value);
                        s.AppendLine();
                    }
                    s.AppendFormat("FinalOpacity = {0}", opacity.FinalOpacity);
                    s.AppendLine();
                }
                break;
                }

                s.AppendFormat("Delay = {0}ms", animation.Delay.TotalMilliseconds);
                s.AppendLine();
                s.AppendFormat("Duration = {0}ms", animation.Duration.TotalMilliseconds);
                s.AppendLine();
                s.AppendFormat("Cubic Bezier control points");
                s.AppendLine();
                s.AppendFormat("    X1 = {0}, Y1 = {1}", animation.Control1.X, animation.Control1.Y);
                s.AppendLine();
                s.AppendFormat("    X2 = {0}, Y2 = {1}", animation.Control2.X, animation.Control2.Y);
                s.AppendLine();
                s.AppendLine();
            }

            Metrics.Text = s.ToString();
        }
        List <GameObject> FilterList(List <GameObject> mrss,
                                     HashSet <GameObject> objectsAlreadyIncludedInBakers,
                                     GameObject dontAddMe,
                                     bool addingObjects)
        {
            int numInSelection             = 0;
            int numStaticExcluded          = 0;
            int numEnabledExcluded         = 0;
            int numLightmapExcluded        = 0;
            int numLodLevelExcluded        = 0;
            int numOBuvExcluded            = 0;
            int numMatExcluded             = 0;
            int numShaderExcluded          = 0;
            int numRegExExcluded           = 0;
            int numAlreadyIncludedExcluded = 0;

            System.Text.RegularExpressions.Regex regex = null;
            if (searchRegEx != null && searchRegEx.Length > 0)
            {
                try
                {
                    regex           = new System.Text.RegularExpressions.Regex(searchRegEx);
                    regExParseError = "";
                }
                catch (Exception ex)
                {
                    regExParseError = ex.Message;
                }
            }

            Dictionary <int, MB_Utility.MeshAnalysisResult> meshAnalysisResultsCache = new Dictionary <int, MB_Utility.MeshAnalysisResult>(); //cache results
            List <GameObject> newMomObjs = new List <GameObject>();

            for (int j = 0; j < mrss.Count; j++)
            {
                if (mrss[j] == null)
                {
                    continue;
                }
                Renderer mrs = mrss[j].GetComponent <Renderer>();
                if (mrs is MeshRenderer || mrs is SkinnedMeshRenderer)
                {
                    if (mrs.GetComponent <TextMesh>() != null)
                    {
                        continue; //don't add TextMeshes
                    }

                    numInSelection++;
                    if (!newMomObjs.Contains(mrs.gameObject))
                    {
                        bool addMe = true;
                        if (!mrs.gameObject.isStatic && onlyStaticObjects)
                        {
                            numStaticExcluded++;
                            addMe = false;
                            continue;
                        }

                        if ((!mrs.enabled || !mrs.gameObject.activeInHierarchy) && onlyEnabledObjects)
                        {
                            numEnabledExcluded++;
                            addMe = false;
                            continue;
                        }

                        if (lightmapIndex != -2)
                        {
                            if (mrs.lightmapIndex != lightmapIndex)
                            {
                                numLightmapExcluded++;
                                addMe = false;
                                continue;
                            }
                        }

                        if (lodLevelToInclude == -1)
                        {
                            // not filtering on LODLevel
                        }
                        else
                        {
                            if (GetLODLevelForRenderer(mrs) != lodLevelToInclude)
                            {
                                numLodLevelExcluded++;
                                addMe = false;
                                continue;
                            }
                        }

                        // only do this check when adding objects. If removing objects shouldn't do it
                        if (addingObjects &&
                            excludeMeshesAlreadyAddedToBakers &&
                            objectsAlreadyIncludedInBakers.Contains(mrs.gameObject))
                        {
                            numAlreadyIncludedExcluded++;
                            addMe = false;
                            continue;
                        }

                        Mesh mm = MB_Utility.GetMesh(mrs.gameObject);
                        if (mm != null)
                        {
                            MB_Utility.MeshAnalysisResult mar;
                            if (!meshAnalysisResultsCache.TryGetValue(mm.GetInstanceID(), out mar))
                            {
                                MB_Utility.hasOutOfBoundsUVs(mm, ref mar);
                                meshAnalysisResultsCache.Add(mm.GetInstanceID(), mar);
                            }
                            if (mar.hasOutOfBoundsUVs && excludeMeshesWithOBuvs)
                            {
                                numOBuvExcluded++;
                                addMe = false;
                                continue;
                            }
                        }

                        if (shaderMat != null)
                        {
                            Material[] nMats      = mrs.sharedMaterials;
                            bool       usesShader = false;
                            foreach (Material nMat in nMats)
                            {
                                if (nMat != null && nMat.shader == shaderMat.shader)
                                {
                                    usesShader = true;
                                }
                            }
                            if (!usesShader)
                            {
                                numShaderExcluded++;
                                addMe = false;
                                continue;
                            }
                        }

                        if (mat != null)
                        {
                            Material[] nMats   = mrs.sharedMaterials;
                            bool       usesMat = false;
                            foreach (Material nMat in nMats)
                            {
                                if (nMat == mat)
                                {
                                    usesMat = true;
                                }
                            }
                            if (!usesMat)
                            {
                                numMatExcluded++;
                                addMe = false;
                                continue;
                            }
                        }

                        if (regex != null)
                        {
                            if (!regex.IsMatch(mrs.gameObject.name))
                            {
                                numRegExExcluded++;
                                addMe = false;
                                continue;
                            }
                        }

                        if (addMe && mrs.gameObject != dontAddMe)
                        {
                            if (!newMomObjs.Contains(mrs.gameObject))
                            {
                                newMomObjs.Add(mrs.gameObject);
                            }
                        }
                    }
                }
            }

            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            //sb.AppendFormat("Total objects in selection {0}\n", numInSelection);
            //Debug.Log( "Total objects in selection " + numInSelection);
            if (numStaticExcluded > 0)
            {
                sb.AppendFormat("   {0} objects were excluded because they were not static\n", numStaticExcluded);
                Debug.Log(numStaticExcluded + " objects were excluded because they were not static\n");
            }
            if (numEnabledExcluded > 0)
            {
                sb.AppendFormat("   {0} objects were excluded because they were disabled\n", numEnabledExcluded);
                Debug.Log(numEnabledExcluded + " objects were excluded because they were disabled\n");
            }
            if (numOBuvExcluded > 0)
            {
                sb.AppendFormat("   {0} objects were excluded because they had out of bounds uvs\n", numOBuvExcluded);
                Debug.Log(numOBuvExcluded + " objects were excluded because they had out of bounds uvs\n");
            }
            if (numLightmapExcluded > 0)
            {
                sb.AppendFormat("   {0} objects were excluded because they did not match lightmap filter.\n", numLightmapExcluded);
                Debug.Log(numLightmapExcluded + " objects did not match lightmap filter.\n");
            }
            if (numLodLevelExcluded > 0)
            {
                sb.AppendFormat("   {0} objects were excluded because they did not match the selected LOD level filter.\n", numLodLevelExcluded);
                Debug.Log(numLodLevelExcluded + " objects did not match LOD level filter.\n");
            }
            if (numShaderExcluded > 0)
            {
                sb.AppendFormat("   {0} objects were excluded because they did not use the selected shader.\n", numShaderExcluded);
                Debug.Log(numShaderExcluded + " objects were excluded because they did not use the selected shader.\n");
            }
            if (numMatExcluded > 0)
            {
                sb.AppendFormat("   {0} objects were excluded because they did not use the selected material.\n", numMatExcluded);
                Debug.Log(numMatExcluded + " objects were excluded because they did not use the selected material.\n");
            }
            if (numRegExExcluded > 0)
            {
                sb.AppendFormat("   {0} objects were excluded because they did not match the regular expression.\n", numRegExExcluded);
                Debug.Log(numRegExExcluded + " objects were excluded because they did not match the regular expression.\n");
            }
            if (numAlreadyIncludedExcluded > 0)
            {
                sb.AppendFormat("   {0} objects were excluded because they did were already included in other bakers.\n", numAlreadyIncludedExcluded);
                Debug.Log(numAlreadyIncludedExcluded + " objects were excluded because they did were already included in other bakers.\n");
            }

            helpBoxString = sb.ToString();
            return(newMomObjs);
        }
        /// <summary> Dumps the active view sheet settings for review. </summary>
        ///
        /// <param name="settings"> The data for the sheet. </param>
        /// <param name="label">    (Optional) A label to prefix to the report. </param>
        /// <param name="display">  (Optional) true to display the data on screen. </param>
        ///
        /// <returns> A string containing all of the data. </returns>
        public string DumpViewSheetSettings(Mastercam.Support.ViewSheets.ViewSheetSettings settings, string label = "", bool display = true)
        {
            var sb = new System.Text.StringBuilder();

            if (!string.IsNullOrEmpty(label))
            {
                sb.AppendLine(label);
            }

            sb.AppendFormat("\nConstructionMode (3D) = {0}", settings.ConstructionMode);
            sb.AppendFormat("\nGraphicsView = {0}", settings.GraphicsView);
            sb.AppendFormat("\nPlanes = {0}", settings.Planes);
            sb.AppendFormat("\nToolplanes = {0}", settings.ToolPlanes);
            sb.AppendFormat("\nConstructionPlanes= {0}", settings.ConstructionPlanes);
            sb.AppendFormat("\nZdepth = {0}", settings.Zdepth);
            sb.AppendFormat("\nWcs = {0}", settings.WcsPlane);
            sb.AppendFormat("\nColor = {0}", settings.Color);
            sb.AppendFormat("\nActivelevel = {0}", settings.ActiveLevel);
            sb.AppendFormat("\nLinestyle= {0}", settings.LineStyle);
            sb.AppendFormat("\nPointstyle = {0}", settings.PointStyle);
            sb.AppendFormat("\nLineWidth = {0}", settings.LineWidth);
            sb.AppendFormat("\nSurfaceDensity = {0}", settings.SurfaceDensity);
            sb.AppendFormat("\nAutoRestore = {0}", settings.AutoRestore);

            var settingsDump = sb.ToString();

            if (display)
            {
                this.ShowData(settingsDump);
            }

            return(settingsDump);
        }
예제 #51
0
 Serialize(
     System.Text.StringBuilder text,
     int indentLevel)
 {
     if (this.BuildFiles.Count > 0)
     {
         text.AppendLine();
         text.AppendFormat("/* Begin PBXBuildFile section */");
         text.AppendLine();
         foreach (var buildFile in this.BuildFiles.OrderBy(key => key.GUID))
         {
             buildFile.Serialize(text, indentLevel);
         }
         text.AppendFormat("/* End PBXBuildFile section */");
         text.AppendLine();
     }
     if (this.ContainerItemProxies.Count > 0)
     {
         text.AppendLine();
         text.AppendFormat("/* Begin PBXContainerItemProxy section */");
         text.AppendLine();
         foreach (var proxy in this.ContainerItemProxies.OrderBy(key => key.GUID))
         {
             proxy.Serialize(text, indentLevel);
         }
         text.AppendFormat("/* End PBXContainerItemProxy section */");
         text.AppendLine();
     }
     if (this.CopyFilesBuildPhases.Count > 0)
     {
         text.AppendLine();
         text.AppendFormat("/* Begin PBXCopyFilesBuildPhase section */");
         text.AppendLine();
         foreach (var phase in this.CopyFilesBuildPhases.OrderBy(key => key.GUID))
         {
             phase.Serialize(text, indentLevel);
         }
         text.AppendFormat("/* End PBXCopyFilesBuildPhase section */");
         text.AppendLine();
     }
     if (this.FileReferences.Count > 0)
     {
         text.AppendLine();
         text.AppendFormat("/* Begin PBXFileReference section */");
         text.AppendLine();
         foreach (var fileRef in this.FileReferences.OrderBy(key => key.GUID))
         {
             fileRef.Serialize(text, indentLevel);
         }
         text.AppendFormat("/* End PBXFileReference section */");
         text.AppendLine();
     }
     if (this.FrameworksBuildPhases.Count > 0)
     {
         text.AppendLine();
         text.AppendFormat("/* Begin PBXFrameworksBuildPhase section */");
         text.AppendLine();
         foreach (var phase in this.FrameworksBuildPhases.OrderBy(key => key.GUID))
         {
             phase.Serialize(text, indentLevel);
         }
         text.AppendFormat("/* End PBXFrameworksBuildPhase section */");
         text.AppendLine();
     }
     if (this.Groups.Count > 0)
     {
         text.AppendLine();
         text.AppendFormat("/* Begin PBXGroup section */");
         text.AppendLine();
         foreach (var group in this.Groups.OrderBy(key => key.GUID))
         {
             group.Serialize(text, indentLevel);
         }
         text.AppendFormat("/* End PBXGroup section */");
         text.AppendLine();
     }
     if (this.ReferenceProxies.Count > 0)
     {
         text.AppendLine();
         text.AppendFormat("/* Begin PBXReferenceProxy section */");
         text.AppendLine();
         foreach (var proxy in this.ReferenceProxies.OrderBy(key => key.GUID))
         {
             proxy.Serialize(text, indentLevel);
         }
         text.AppendFormat("/* End PBXReferenceProxy section */");
         text.AppendLine();
     }
     if (this.Targets.Count > 0)
     {
         text.AppendLine();
         text.AppendFormat("/* Begin PBXNativeTarget section */");
         text.AppendLine();
         foreach (var target in this.Targets.Values.OrderBy(key => key.GUID))
         {
             target.Serialize(text, indentLevel);
         }
         text.AppendFormat("/* End PBXNativeTarget section */");
         text.AppendLine();
     }
     this.InternalSerialize(text, indentLevel); //this is the PBXProject :)
     if (this.ShellScriptsBuildPhases.Count > 0)
     {
         text.AppendLine();
         text.AppendFormat("/* Begin PBXShellScriptBuildPhase section */");
         text.AppendLine();
         foreach (var phase in this.ShellScriptsBuildPhases.OrderBy(key => key.GUID))
         {
             phase.Serialize(text, indentLevel);
         }
         text.AppendFormat("/* End PBXShellScriptBuildPhase section */");
         text.AppendLine();
     }
     if (this.SourcesBuildPhases.Count > 0)
     {
         text.AppendLine();
         text.AppendFormat("/* Begin PBXSourcesBuildPhase section */");
         text.AppendLine();
         foreach (var phase in this.SourcesBuildPhases.OrderBy(key => key.GUID))
         {
             phase.Serialize(text, indentLevel);
         }
         text.AppendFormat("/* End PBXSourcesBuildPhase section */");
         text.AppendLine();
     }
     if (this.TargetDependencies.Count > 0)
     {
         text.AppendLine();
         text.AppendFormat("/* Begin PBXTargetDependency section */");
         text.AppendLine();
         foreach (var dependency in this.TargetDependencies.OrderBy(key => key.GUID))
         {
             dependency.Serialize(text, indentLevel);
         }
         text.AppendFormat("/* End PBXTargetDependency section */");
         text.AppendLine();
     }
     if (this.AllConfigurations.Count > 0)
     {
         text.AppendLine();
         text.AppendFormat("/* Begin XCBuildConfiguration section */");
         text.AppendLine();
         foreach (var config in this.AllConfigurations.OrderBy(key => key.GUID))
         {
             config.Serialize(text, indentLevel);
         }
         text.AppendFormat("/* End XCBuildConfiguration section */");
         text.AppendLine();
     }
     if (this.ConfigurationLists.Count > 0)
     {
         text.AppendLine();
         text.AppendFormat("/* Begin XCConfigurationList section */");
         text.AppendLine();
         foreach (var configList in this.ConfigurationLists.OrderBy(key => key.GUID))
         {
             configList.Serialize(text, indentLevel);
         }
         text.AppendFormat("/* End XCConfigurationList section */");
         text.AppendLine();
     }
 }
        /// <summary> Dumps the view sheet data package for review. </summary>
        ///
        /// <param name="data">    The data for the sheet. </param>
        /// <param name="label">   (Optional) A label to prefix to the report. </param>
        /// <param name="display"> (Optional) true to display the data on screen. </param>
        ///
        /// <returns> A string containing all of the data. </returns>
        public string DumpViewSheetDataPackage(Mastercam.Support.ViewSheets.ViewSheetData data, string label = "", bool display = true)
        {
            var sb = new System.Text.StringBuilder();

            if (!string.IsNullOrEmpty(label))
            {
                sb.AppendLine(label);
            }

            sb.AppendFormat("\nConstructionMode3D = {0}", data.ConstructionMode3D);
            sb.AppendFormat("\nWireframeColor = {0}", data.WireframeColor);
            sb.AppendFormat("\nSurfaceColor = {0}", data.SurfaceColor);
            sb.AppendFormat("\nSolidColor = {0}", data.SolidColor);

            sb.AppendFormat("\nConstructionPlaneMatrix => {0}", this.FormatMatrix(data.ConstructionPlaneMatrix));
            sb.AppendFormat("\nToolPlaneMatrix => {0}", this.FormatMatrix(data.ToolPlaneMatrix));
            sb.AppendFormat("\nGraphicsPlaneMatrix => {0}", this.FormatMatrix(data.GraphicsPlaneMatrix));
            sb.AppendFormat("\nWcsPlaneMatrix => {0}", this.FormatMatrix(data.WcsPlaneMatrix));

            sb.AppendFormat("\nViewportCenter = {0}", data.ViewportCenter);
            sb.AppendFormat("\nConstructionDepthZ = {0}", data.ConstructionDepthZ);
            sb.AppendFormat("\nLineWidth = {0}", data.LineWidth);

            sb.AppendFormat("\nSurfaceDensity = {0}", data.SurfaceDensity);
            sb.AppendFormat("\nActiveLevel = {0}", data.ActiveLevel);
            sb.AppendFormat("\nConstructionPlaneID = {0}", data.ConstructionPlaneID);
            sb.AppendFormat("\nTooltPlaneID = {0}", data.ToolPlaneID);
            sb.AppendFormat("\nGraphicsPlaneID = {0}", data.GraphicsPlaneID);
            sb.AppendFormat("\nWcsPlakneID = {0}", data.ToolPlaneID);

            var count = data.VisibleLevels.Count;

            sb.AppendFormat("\nVisibleLevels has [{0}] {1}  ->", count, (count == 1) ? "entry" : "entries");
            for (var i = 0; i < data.VisibleLevels.Count; i++)
            {
                sb.AppendFormat("\n{0}> {1}", i + 1, data.VisibleLevels[i]);
            }

            var dataDump = sb.ToString();

            if (display)
            {
                this.ShowData(dataDump);
            }

            return(dataDump);
        }
예제 #53
0
        InternalSerialize(
            System.Text.StringBuilder text,
            int indentLevel)
        {
            var indent  = new string('\t', indentLevel);
            var indent2 = new string('\t', indentLevel + 1);
            var indent3 = new string('\t', indentLevel + 2);
            var indent4 = new string('\t', indentLevel + 3);

            text.AppendLine();
            text.AppendFormat("/* Begin PBXProject section */");
            text.AppendLine();

            text.AppendFormat("{0}{1} /* Project object */ = {{", indent, this.GUID);
            text.AppendLine();
            text.AppendFormat("{0}isa = {1};", indent2, this.IsA);
            text.AppendLine();
            text.AppendFormat("{0}attributes = {{", indent2);
            text.AppendLine();

            var clangMeta = Bam.Core.Graph.Instance.PackageMetaData <Clang.MetaData>("Clang");

            text.AppendFormat("{0}LastUpgradeCheck = {1};", indent3, clangMeta.LastUpgradeCheck);
            text.AppendLine();
            text.AppendFormat("{0}}};", indent2);
            text.AppendLine();
            // project configuration list is always the first
            var projectConfigurationList = this.ConfigurationLists[0];

            text.AppendFormat("{0}buildConfigurationList = {1} /* Build configuration list for {2} \"{3}\" */;", indent2, projectConfigurationList.GUID, projectConfigurationList.Parent.IsA, projectConfigurationList.Parent.Name);
            text.AppendLine();
            text.AppendFormat("{0}compatibilityVersion = \"{1}\";", indent2, "Xcode 3.2"); // TODO
            text.AppendLine();
            text.AppendFormat("{0}mainGroup = {1};", indent2, this.MainGroup.GUID);
            text.AppendLine();
            text.AppendFormat("{0}productRefGroup = {1} /* {2} */;", indent2, this.ProductRefGroup.GUID, this.ProductRefGroup.Name);
            text.AppendLine();
            text.AppendFormat("{0}projectDirPath = \"\";", indent2);
            text.AppendLine();
            if (this.ProjectReferences.Count > 0)
            {
                text.AppendFormat("{0}projectReferences = (", indent2);
                text.AppendLine();
                foreach (var projectRef in this.ProjectReferences)
                {
                    text.AppendFormat("{0}{", indent3);
                    text.AppendLine();
                    text.AppendFormat("{0}ProductGroup = {1} /* {2} */;", indent4, projectRef.Key.GUID, projectRef.Key.Name);
                    text.AppendLine();
                    text.AppendFormat("{0}ProjectRef = {1} /* {2} */;", indent4, projectRef.Value.GUID, projectRef.Value.Name);
                    text.AppendLine();
                    text.AppendFormat("{0}},", indent3);
                    text.AppendLine();
                }
                text.AppendFormat("{0});", indent2);
                text.AppendLine();
            }
            text.AppendFormat("{0}targets = (", indent2);
            text.AppendLine();
            foreach (var target in this.Targets.Values)
            {
                text.AppendFormat("{0}{1} /* {2} */,", indent3, target.GUID, target.Name);
                text.AppendLine();
            }
            text.AppendFormat("{0});", indent2);
            text.AppendLine();
            text.AppendFormat("{0}}};", indent);
            text.AppendLine();

            text.AppendFormat("/* End PBXProject section */");
            text.AppendLine();
        }
예제 #54
0
        private string GetStateLabel(State state)
        {
            if (state == null)
            {
                return("null");
            }

            string   stateLabel = state.stateNumber.ToString();
            DFAState dfaState   = state as DFAState;
            NFAState nfaState   = state as NFAState;

            if (dfaState != null)
            {
                StringBuilder builder = new StringBuilder(250);
                builder.Append('s');
                builder.Append(state.stateNumber);
                if (AntlrTool.internalOption_ShowNFAConfigsInDFA)
                {
                    if (dfaState.abortedDueToRecursionOverflow)
                    {
                        builder.AppendLine();
                        builder.AppendLine("AbortedDueToRecursionOverflow");
                    }

                    var alts = dfaState.AltSet;
                    if (alts != null)
                    {
                        builder.AppendLine();
                        List <int> altList = alts.OrderBy(i => i).ToList();
                        ICollection <NFAConfiguration> configurations = dfaState.nfaConfigurations;
                        for (int i = 0; i < altList.Count; i++)
                        {
                            int alt = altList[i];
                            if (i > 0)
                            {
                                builder.AppendLine();
                            }
                            builder.AppendFormat("alt{0}:", alt);
                            // get a list of configs for just this alt
                            // it will help us print better later
                            List <NFAConfiguration> configsInAlt = new List <NFAConfiguration>();
                            foreach (NFAConfiguration c in configurations)
                            {
                                if (c.alt != alt)
                                {
                                    continue;
                                }

                                configsInAlt.Add(c);
                            }

                            int n = 0;
                            for (int cIndex = 0; cIndex < configsInAlt.Count; cIndex++)
                            {
                                NFAConfiguration c = configsInAlt[cIndex];
                                n++;
                                builder.Append(c.ToString(false));
                                if ((cIndex + 1) < configsInAlt.Count)
                                {
                                    builder.Append(", ");
                                }
                                if (n % 5 == 0 && (configsInAlt.Count - cIndex) > 3)
                                {
                                    builder.Append("\\n");
                                }
                            }
                        }
                    }
                }

                if (dfaState.IsAcceptState)
                {
                    builder.Append("⇒" + dfaState.GetUniquelyPredictedAlt());
                }

                stateLabel = builder.ToString();
            }
            else if (nfaState != null)
            {
                if (nfaState.IsDecisionState)
                {
                    stateLabel += ",d=" + nfaState.DecisionNumber;
                }

                if (nfaState.endOfBlockStateNumber != State.INVALID_STATE_NUMBER)
                {
                    stateLabel += ",eob=" + nfaState.endOfBlockStateNumber;
                }
            }

            return(stateLabel);
        }
예제 #55
0
        public override string ToString()
        {
            string strUserID = "XX";

            if (UserIDLogedIn.HasValue && UserIDLogedIn.Value != Constants.ANONYMOUS_USERID.ToGuid())
            {
                strUserID = string.Concat("X", UserIDLogedIn);
            }

            System.Text.StringBuilder sb = new System.Text.StringBuilder(string.Format("OT{0}-{1}-{2}-{3}-{4}-{5}-{6}", (int)ObjectType, strUserID, (int)SortBy, CommunityID, UserID, TagID, (int)Direction));

            if (Featured != null)
            {
                sb.AppendFormat("-B{0}", Featured.Value);
            }

            if (WithCopy != null)
            {
                sb.AppendFormat("-C{0}", WithCopy.Value ? "1" : "0");
            }

            if (ShowState != null)
            {
                sb.AppendFormat("-D{0}", (int)ShowState.Value);
            }

            if (FromInserted != null)
            {
                sb.AppendFormat("-E{0}", FromInserted.Value.Date.Ticks);
            }

            if (ToInserted != null)
            {
                sb.AppendFormat("-F{0}", ToInserted.Value.Date.Ticks);
            }

            if (FromStartDate != null)
            {
                sb.AppendFormat("-G1{0}", FromStartDate.Value.Date.Ticks);
            }

            if (ToStartDate != null)
            {
                sb.AppendFormat("-G2{0}", ToStartDate.Value.Date.Ticks);
            }

            if (FromEndDate != null)
            {
                sb.AppendFormat("-H1{0}", FromEndDate.Value.Date.Ticks);
            }

            if (ToEndDate != null)
            {
                sb.AppendFormat("-H2{0}", ToEndDate.Value.Date.Ticks);
            }

            if (DateQueryMethode != null)
            {
                sb.AppendFormat("-I{0}", (int)DateQueryMethode.Value);
            }

            if (!string.IsNullOrEmpty(Country))
            {
                sb.AppendFormat("-J{0}", Country.ToLower());
            }

            if (!string.IsNullOrEmpty(Zip))
            {
                sb.AppendFormat("-K{0}", Zip.ToLower());
            }

            if (!string.IsNullOrEmpty(City))
            {
                sb.AppendFormat("-L{0}", City.ToLower());
            }

            if (DistanceKm != null && GeoLat != null && GeoLong != null)
            {
                sb.AppendFormat("-M{0}({1}{2})", DistanceKm.Value, GeoLat.Value, GeoLong.Value);
            }

            if (!string.IsNullOrEmpty(ParentObjectID))
            {
                sb.AppendFormat("-N{0}", ParentObjectID);
            }

            if (CheckUserRoleRight)
            {
                sb.AppendFormat("-O{0}", UserRole.ToLower());
            }

            if (PageSize > 0 || Amount > 0)
            {
                sb.AppendFormat("-P{0}", string.Format("{0}.{1}.{2}", PageNumber, PageSize, Amount));
            }

            if (!string.IsNullOrEmpty(Communities))
            {
                sb.AppendFormat("-R{0}", Communities.ToLower());
            }

            if (!string.IsNullOrEmpty(Tags1))
            {
                sb.AppendFormat("-S1{0}", Tags1.ToLower());
            }
            if (!string.IsNullOrEmpty(RawTags1))
            {
                sb.AppendFormat("-SR1{0}", RawTags1.ToLower());
            }

            if (!string.IsNullOrEmpty(Tags2))
            {
                sb.AppendFormat("-S2{0}", Tags2.ToLower());
            }
            if (!string.IsNullOrEmpty(RawTags2))
            {
                sb.AppendFormat("-SR2{0}", RawTags2.ToLower());
            }

            if (!string.IsNullOrEmpty(Tags3))
            {
                sb.AppendFormat("-S3{0}", Tags3.ToLower());
            }
            if (!string.IsNullOrEmpty(RawTags3))
            {
                sb.AppendFormat("-SR3{0}", RawTags3.ToLower());
            }

            if (!string.IsNullOrEmpty(ObjectTypes))
            {
                sb.AppendFormat("-T{0}", ObjectTypes.ToLower());
            }

            if (GroupID.HasValue)
            {
                sb.AppendFormat("-X1{0}", GroupID.Value);
            }

            if (CatalogSearchType != DBCatalogSearchType.None)
            {
                sb.AppendFormat("-X2{0}", (int)CatalogSearchType);
            }

            if (DisablePaging.HasValue)
            {
                sb.AppendFormat("-X3{0}", DisablePaging.Value ? "1" : "0");
            }

            if (CurrentObjectID.HasValue)
            {
                sb.AppendFormat("-XC4{0}", CurrentObjectID.Value);
            }

            if (ObjectID.HasValue)
            {
                sb.AppendFormat("-XO4{0}", ObjectID.Value);
            }

            if (OnlyConverted.HasValue)
            {
                sb.AppendFormat("-X5{0}", OnlyConverted.Value ? "1" : "0");
            }

            if (OnlyWithImage.HasValue)
            {
                sb.AppendFormat("-X6{0}", OnlyWithImage.Value ? "1" : "0");
            }

            if (IncludeGroups.HasValue)
            {
                sb.AppendFormat("-X7{0}", IncludeGroups.Value ? "1" : "0");
            }

            if (OnlyGeoTagged.HasValue)
            {
                sb.AppendFormat("-X8{0}", OnlyGeoTagged.Value ? "1" : "0");
            }

            if (!string.IsNullOrEmpty(nickname))
            {
                sb.AppendFormat("-X9{0}", nickname.ToLower());
            }

            if (!string.IsNullOrEmpty(title))
            {
                sb.AppendFormat("-X10{0}", title.ToLower());
            }

            if (!string.IsNullOrEmpty(description))
            {
                sb.AppendFormat("-X11{0}", description.ToLower());
            }

            if (!string.IsNullOrEmpty(userSearch))
            {
                sb.AppendFormat("-X12{0}", userSearch.ToLower());
            }

            if (!string.IsNullOrEmpty(generalSearch))
            {
                sb.AppendFormat("-X13{0}", generalSearch.ToLower());
            }

            if (!string.IsNullOrEmpty(oTypes))
            {
                sb.AppendFormat("-X14{0}", oTypes.ToLower());
            }

            if (!string.IsNullOrEmpty(cties))
            {
                sb.AppendFormat("-X15{0}", cties.ToLower());
            }

            if (!string.IsNullOrEmpty(titleLeftChar))
            {
                sb.AppendFormat("-X16{0}", titleLeftChar.ToLower());
            }

            if (RelationParams != null)
            {
                sb.AppendFormat("-RP{0}", RelationParams.ToString());
            }

            if (MembershipParams != null)
            {
                sb.AppendFormat("-MP{0}", MembershipParams.ToString());
            }

            if (ViewLogParams != null)
            {
                sb.AppendFormat("-LP{0}", ViewLogParams.ToString());
            }



            //public ViewLogParams ViewLogParams { get; set; }


            return(sb.ToString());
        }
        public IVisio.Document DrawInteropEnumDocumentation()
        {
            var cmdtarget = this._client.GetCommandTarget(CommandTargetFlags.RequireApplication);

            var formdoc = new VADOC.Forms.FormDocument();

            var helpstr   = new System.Text.StringBuilder();
            int chunksize = 70;

            var interop_enums = VisioScripting.Helpers.InteropHelper.GetEnums();

            foreach (var enum_ in interop_enums)
            {
                int chunkcount = 0;

                var values = enum_.Values.OrderBy(i => i.Name).ToList();
                foreach (var chunk in DeveloperCommands._chunk(values, chunksize))
                {
                    helpstr.Length = 0;
                    foreach (var val in chunk)
                    {
                        helpstr.AppendFormat("0x{0}\t{1}\n", val.Value.ToString("x"), val.Name);
                    }

                    var formpage = new VADOC.Forms.FormPage();
                    formpage.Size       = new VisioAutomation.Geometry.Size(8.5, 11);
                    formpage.PageMargin = new VADOC.Forms.PageMargin(0.5, 0.5, 0.5, 0.5);
                    formpage.Title      = enum_.Name;
                    formpage.Body       = helpstr.ToString();
                    if (chunkcount == 0)
                    {
                        formpage.Name = string.Format("{0}", enum_.Name);
                    }
                    else
                    {
                        formpage.Name = string.Format("{0} ({1})", enum_.Name, chunkcount + 1);
                    }

                    //docbuilder.BodyParaSpacingAfter = 2.0;

                    formpage.BodyTextSize = 8.0;
                    formdoc.Pages.Add(formpage);

                    var tabstops = new[]
                    {
                        new VisioAutomation.Text.TabStop(1.5, VisioAutomation.Text.TabStopAlignment.Left)
                    };

                    //VA.Text.TextFormat.SetTabStops(docpage.VisioBodyShape, tabstops);

                    chunkcount++;
                }
            }

            formdoc.Subject = "Visio Interop Enum Documenation";
            formdoc.Title   = "Visio Interop Enum Documenation";
            formdoc.Creator = "";
            formdoc.Company = "";

            //hide_ui_stuff(docbuilder.VisioDocument);


            var application = cmdtarget.Application;
            var doc         = formdoc.Render(application);

            return(doc);
        }
예제 #57
0
        public ActionResult Edit(FormCollection collection)
        {
            string editid = Request.QueryString["id"];

            BizProcess.Platform.DBExtract   bdbConn = new BizProcess.Platform.DBExtract();
            BizProcess.Data.Model.DBExtract dbe     = null;
            if (editid.IsGuid())
            {
                dbe = bdbConn.Get(editid.ToGuid());
            }
            bool   isAdd  = !editid.IsGuid();
            string oldXML = string.Empty;

            if (dbe == null)
            {
                dbe    = new BizProcess.Data.Model.DBExtract();
                dbe.ID = Guid.NewGuid();
            }
            else
            {
                oldXML = dbe.Serialize();
            }

            if (collection != null)
            {
                string Name           = Request.Form["Name"];
                string Comment        = Request.Form["Comment"];
                string DBConnID       = Request.Form["DBConnID"];
                string ExtractType    = Request.Form["ExtractType"];
                string RunTime        = Request.Form["RunTime"];
                string OnlyIncrement  = Request.Form["OnlyIncrement"];
                string DesignJSON     = "";
                string db_table       = Request.Form["db_table"];
                string db_primarykey  = Request.Form["db_primarykey"];
                bool   bSchemaChanged = false;

                if (dbe.DBConnID != DBConnID.ToGuid())
                {
                    bSchemaChanged = true;
                }

                dbe.Name     = Name.Trim();
                dbe.Comment  = Comment;
                dbe.DBConnID = DBConnID.ToGuid();

                System.Text.StringBuilder json = new System.Text.StringBuilder();
                json.Append("{");
                json.AppendFormat("\"table\":\"{0}\",", db_table.Trim());
                json.AppendFormat("\"primarykey\":\"{0}\",", db_primarykey.Trim());
                json.Append("\"fields\":[");

                String[] fields = Request.Form.GetValues("link_field[]");
                foreach (String field in fields)
                {
                    json.Append("{");
                    json.AppendFormat("\"field\":\"{0}\"", field.Trim());
                    if (fields.Last() != field)
                    {
                        json.Append("},");
                    }
                    else
                    {
                        json.Append("}");
                    }
                }
                json.AppendFormat("]");
                json.Append("}");
                DesignJSON = json.ToString();

                if (bSchemaChanged && (dbe.DesignJSON == null || !dbe.DesignJSON.Equals(DesignJSON)))
                {
                    bSchemaChanged = true;
                }

                dbe.DesignJSON    = DesignJSON;
                dbe.ExtractType   = ExtractType == "Auto" ? true : false;
                dbe.RunTime       = RunTime;
                dbe.OnlyIncrement = OnlyIncrement == "OnlyIncrement" ? true : false;

                if (isAdd)
                {
                    bdbConn.Add(dbe);
                    BizProcess.Platform.Log.Add("添加了数据抽取", dbe.Serialize(), BizProcess.Platform.Log.Types.流程相关);
                    ViewBag.Script = "alert('添加成功!');new BPUI.Window().reloadOpener();new BPUI.Window().close();";
                }
                else
                {
                    bdbConn.Update(dbe, bSchemaChanged);
                    BizProcess.Platform.Log.Add("修改了数据抽取", "", BizProcess.Platform.Log.Types.流程相关, oldXML, dbe.Serialize());
                    ViewBag.Script = "alert('修改成功!');new BPUI.Window().reloadOpener();new BPUI.Window().close();";
                }
                bdbConn.ClearCache();
            }

            return(View(dbe));
        }
예제 #58
0
        private string Body()
        {
            var builder = new System.Text.StringBuilder();

            builder.AppendLine("<h2>Overall</h2>");
            builder.AppendFormat("Server last started {0}<br/>", Logger.ServerStarted.Last());
            builder.AppendFormat("Total connections received: {0}<br />", Logger.TotalConnectionsReceived);

            builder.AppendLine("<h2>Request Times</h2>");
            builder.AppendLine("<table id=\"request_times\"><tr><th>Path</th><th>Method</th><th>Number of requests</th><th></th></tr>");
            int i = 0;

            foreach (var time in Logger.GetAllRequestTimes())
            {
                string row_class = (i % 2 == 0) ? "even_row" : "odd_row";
                builder.AppendFormat("<tr class=\"{0}\"><td>{1}</td><td>{2}</td><td>{3}</td><td class=\"see_details\">details</td></tr>\n", row_class, WebUtility.HtmlEncode(time.RelativePath), WebUtility.HtmlEncode(time.HttpMethod), time.NumRequests);

                // Now the line with more data
                builder.AppendFormat("<tr class=\"row_data\"><td colspan=\"4\"><div style=\"padding-left: 10px;\">Minimum time: {0}ms<br />Maximum time: {1}ms<br/>Average time: {2}ms</div></td></tr>\n", time.MinimumTime.TotalMilliseconds, time.MaximumTime.TotalMilliseconds, time.AverageTime.TotalMilliseconds);

                i++;
            }
            builder.Append("</table>\n");

            var applicationErrors = Logger.GetAllApplicationErrors();

            builder.Append("<h2>Application Errors</h2>");
            if (!applicationErrors.Any())
            {
                builder.AppendLine("<p>No application errors<p>");
            }
            else
            {
                builder.AppendLine("<table id=\"application_errors\"><tr><th>Path</th><th>Method</th><th>Error</th><th></th></tr>");
                i = 0;
                foreach (var error in applicationErrors)
                {
                    string row_class = (i % 2 == 0) ? "even_row" : "odd_row";
                    builder.AppendFormat("<tr class=\"{0}\"><td>{1}</td><td>{2}</td><td>{3}</td><td class=\"see_details\">details</td></tr>\n", row_class, WebUtility.HtmlEncode(error.RelativePath), WebUtility.HtmlEncode(error.HttpMethod), WebUtility.HtmlEncode(error.Error.Message));

                    // Now the line with more data
                    builder.AppendFormat("<tr class=\"row_data\"><td colspan=\"4\"><div style=\"padding-left: 10px;\">{0}</div></td></tr>\n", error.Error.ToString());

                    i++;
                }
                builder.Append("</table>\n");
            }

            var serverErrors = Logger.GetAllServerErrors();

            builder.Append("<h2>Server Errors</h2>");
            if (!serverErrors.Any())
            {
                builder.AppendLine("<p>No server errors</p>");
            }
            else
            {
                builder.AppendLine("<table id=\"server_errors\"><tr><th>Type</th><th></th></tr>");
                i = 0;
                foreach (var error in serverErrors)
                {
                    string row_class = (i % 2 == 0) ? "even_row" : "odd_row";
                    builder.AppendFormat("<tr class=\"{0}\"><td>{1}</td><td class=\"see_details\">details</td></tr>\n", row_class, WebUtility.HtmlEncode(error.GetType().ToString()));

                    // Now the line with more data
                    builder.AppendFormat("<tr class=\"row_data\"><td colspan=\"4\"><div style=\"padding-left: 10px;\">{0}</div></td></tr>\n", WebUtility.HtmlEncode(error.ToString()));

                    i++;
                }
                builder.Append("</table>\n");
            }

            return(builder.ToString());
        }
예제 #59
0
파일: Main.cs 프로젝트: soufflee/ClassicUO
        public static void Main(string[] args)
        {
            CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;

            Log.Start(LogTypes.All);

            CUOEnviroment.GameThread      = Thread.CurrentThread;
            CUOEnviroment.GameThread.Name = "CUO_MAIN_THREAD";

#if !DEBUG
            AppDomain.CurrentDomain.UnhandledException += (s, e) =>
            {
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                sb.AppendLine("######################## [START LOG] ########################");

#if DEV_BUILD
                sb.AppendLine($"ClassicUO [DEV_BUILD] - {CUOEnviroment.Version} - {DateTime.Now}");
#else
                sb.AppendLine($"ClassicUO [STANDARD_BUILD] - {CUOEnviroment.Version} - {DateTime.Now}");
#endif

                sb.AppendLine($"OS: {Environment.OSVersion.Platform} {(Environment.Is64BitOperatingSystem ? "x64" : "x86")}");
                sb.AppendLine($"Thread: {Thread.CurrentThread.Name}");
                sb.AppendLine();

                if (Settings.GlobalSettings != null)
                {
                    sb.AppendLine($"Shard: {Settings.GlobalSettings.IP}");
                    sb.AppendLine($"ClientVersion: {Settings.GlobalSettings.ClientVersion}");
                    sb.AppendLine();
                }

                sb.AppendFormat("Exception:\n{0}\n", e.ExceptionObject);
                sb.AppendLine("######################## [END LOG] ########################");
                sb.AppendLine();
                sb.AppendLine();

                Log.Panic(e.ExceptionObject.ToString());
                string path = Path.Combine(CUOEnviroment.ExecutablePath, "Logs");

                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }

                using (LogFile crashfile = new LogFile(path, "crash.txt"))
                {
                    crashfile.WriteAsync(sb.ToString()).RunSynchronously();
                }
            };
#endif
            ReadSettingsFromArgs(args);

#if DEV_BUILD
            if (!_skipUpdates)
            {
                Network.Updater updater = new Network.Updater();
                if (updater.Check())
                {
                    return;
                }
            }
#endif

            if (!_skipUpdates)
            {
                if (CheckUpdate(args))
                {
                    return;
                }
            }

            if (CUOEnviroment.IsHighDPI)
            {
                Log.Trace("HIGH DPI - ENABLED");
                Environment.SetEnvironmentVariable("FNA_GRAPHICS_ENABLE_HIGHDPI", "1");
            }

            Environment.SetEnvironmentVariable("FNA3D_BACKBUFFER_SCALE_NEAREST", "1");
            Environment.SetEnvironmentVariable("FNA3D_OPENGL_FORCE_COMPATIBILITY_PROFILE", "1");
            Environment.SetEnvironmentVariable(SDL.SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1");
            Environment.SetEnvironmentVariable("PATH", Environment.GetEnvironmentVariable("PATH") + ";" + Path.Combine(CUOEnviroment.ExecutablePath, "Data", "Plugins"));

            string globalSettingsPath = Settings.GetSettingsFilepath();

            if (!Directory.Exists(Path.GetDirectoryName(globalSettingsPath)) || !File.Exists(globalSettingsPath))
            {
                // settings specified in path does not exists, make new one
                {
                    // TODO:
                    Settings.GlobalSettings.Save();
                }
            }

            Settings.GlobalSettings  = ConfigurationResolver.Load <Settings>(globalSettingsPath);
            CUOEnviroment.IsOutlands = Settings.GlobalSettings.ShardType == 2;

            ReadSettingsFromArgs(args);

            // still invalid, cannot load settings
            if (Settings.GlobalSettings == null)
            {
                Settings.GlobalSettings = new Settings();
                Settings.GlobalSettings.Save();
            }

            if (!CUOEnviroment.IsUnix)
            {
                string libsPath = Path.Combine(CUOEnviroment.ExecutablePath, Environment.Is64BitProcess ? "x64" : "x86");
                SetDllDirectory(libsPath);
            }


            if (string.IsNullOrWhiteSpace(Settings.GlobalSettings.UltimaOnlineDirectory))
            {
                Settings.GlobalSettings.UltimaOnlineDirectory = CUOEnviroment.ExecutablePath;
            }

            const uint INVALID_UO_DIRECTORY = 0x100;
            const uint INVALID_UO_VERSION   = 0x200;

            uint flags = 0;

            if (!Directory.Exists(Settings.GlobalSettings.UltimaOnlineDirectory) ||
                !File.Exists(UOFileManager.GetUOFilePath("tiledata.mul")))
            {
                flags |= INVALID_UO_DIRECTORY;
            }

            string clientVersionText = Settings.GlobalSettings.ClientVersion;

            if (!ClientVersionHelper.IsClientVersionValid(Settings.GlobalSettings.ClientVersion, out ClientVersion clientVersion))
            {
                Log.Warn($"Client version [{clientVersionText}] is invalid, let's try to read the client.exe");

                // mmm something bad happened, try to load from client.exe [windows only]
                if (!ClientVersionHelper.TryParseFromFile(Path.Combine(Settings.GlobalSettings.UltimaOnlineDirectory, "client.exe"), out clientVersionText) ||
                    !ClientVersionHelper.IsClientVersionValid(clientVersionText, out clientVersion))
                {
                    Log.Error("Invalid client version: " + clientVersionText);

                    flags |= INVALID_UO_VERSION;
                }
                else
                {
                    Log.Trace($"Found a valid client.exe [{clientVersionText} - {clientVersion}]");

                    // update the wrong/missing client version in settings.json
                    Settings.GlobalSettings.ClientVersion = clientVersionText;
                }
            }

            if (flags != 0)
            {
                if ((flags & INVALID_UO_DIRECTORY) != 0)
                {
                    Client.ShowErrorMessage(ResGeneral.YourUODirectoryIsInvalid);
                }
                else if ((flags & INVALID_UO_VERSION) != 0)
                {
                    Client.ShowErrorMessage(ResGeneral.YourUOClientVersionIsInvalid);
                }

                try
                {
                    Process.Start(ResGeneral.ClassicUOLink);
                }
                catch
                {
                }
            }
            else
            {
                switch (Settings.GlobalSettings.ForceDriver)
                {
                case 1:     // OpenGL
                    Environment.SetEnvironmentVariable("FNA3D_FORCE_DRIVER", "OpenGL");

                    break;

                case 2:     // Vulkan
                    Environment.SetEnvironmentVariable("FNA3D_FORCE_DRIVER", "Vulkan");

                    break;
                }

                Client.Run();
            }

            Log.Trace("Closing...");
        }
예제 #60
0
        /**
         * @russfeld
         * This seed method reads data from a set of XML files to populate the database
         *
         * XMLReader Code from Microsoft Tutorials
         * http://support.microsoft.com/kb/307548
         *
         */
        protected override void Seed(CIS726_Assignment2.Models.CourseDBContext context)
        {
            bool seedAll = true;

            WebSecurity.InitializeDatabaseConnection(
                "CourseDBContext",
                "Users",
                "ID",
                "username", autoCreateTables: true);

            if (!Roles.RoleExists("Administrator"))
            {
                Roles.CreateRole("Administrator");
            }
            if (!Roles.RoleExists("Advisor"))
            {
                Roles.CreateRole("Advisor");
            }

            if (!WebSecurity.UserExists("admin"))
            {
                WebSecurity.CreateUserAndAccount(
                    "admin",
                    "admin",
                    new { realName = "Administrator" });
            }
            if (!Roles.GetRolesForUser("admin").Contains("Administrator"))
            {
                Roles.AddUserToRole("admin", "Administrator");
            }

            if (!WebSecurity.UserExists("advisor"))
            {
                WebSecurity.CreateUserAndAccount(
                    "advisor",
                    "advisor",
                    new { realName = "Advisor" });
            }
            if (!Roles.GetRolesForUser("advisor").Contains("Advisor"))
            {
                Roles.AddUserToRole("advisor", "Advisor");
            }

            if (!WebSecurity.UserExists("csUndergrad"))
            {
                WebSecurity.CreateUserAndAccount(
                    "csUndergrad",
                    "csUndergrad",
                    new { realName = "Computer Science Undergraduate" });
            }

            if (!WebSecurity.UserExists("seUndergrad"))
            {
                WebSecurity.CreateUserAndAccount(
                    "seUndergrad",
                    "seUndergrad",
                    new { realName = "Software Engineering Undergraduate" });
            }

            if (!WebSecurity.UserExists("isUndergrad"))
            {
                WebSecurity.CreateUserAndAccount(
                    "isUndergrad",
                    "isUndergrad",
                    new { realName = "Information Systems Undergraduate" });
            }

            if (!WebSecurity.UserExists("msGrad"))
            {
                WebSecurity.CreateUserAndAccount(
                    "msGrad",
                    "msGrad",
                    new { realName = "Computer Science Masters Student" });
            }

            if (!WebSecurity.UserExists("mseGrad"))
            {
                WebSecurity.CreateUserAndAccount(
                    "mseGrad",
                    "mseGrad",
                    new { realName = "Software Engineering Masters Student" });
            }

            if (!WebSecurity.UserExists("phdGrad"))
            {
                WebSecurity.CreateUserAndAccount(
                    "phdGrad",
                    "phdGrad",
                    new { realName = "Computer Science Doctoral Student" });
            }

            if (seedAll)
            {
                string[] semesterTitles = { "January", "Spring", "May", "Summer", "August", "Fall" };

                int semCount = 1;
                for (int i = 2013; i < 2025; i++)
                {
                    for (int k = 0; k < semesterTitles.Length; k++)
                    {
                        if (semesterTitles[k].Equals("Spring") || semesterTitles[k].Equals("Fall"))
                        {
                            context.Semesters.AddOrUpdate(c => c.ID, new Semester()
                            {
                                ID            = semCount++,
                                semesterYear  = i,
                                semesterTitle = semesterTitles[k],
                                standard      = true
                            });
                        }
                        else
                        {
                            context.Semesters.AddOrUpdate(c => c.ID, new Semester()
                            {
                                ID            = semCount++,
                                semesterYear  = i,
                                semesterTitle = semesterTitles[k],
                                standard      = false
                            });
                        }
                    }
                }

                context.SaveChanges();

                String resourceName = "CIS726_Assignment2.SeedData.";

                XmlTextReader reader   = new XmlTextReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName + "ksu_courses.xml"));
                Course        course   = null;
                String        property = null;
                int           count    = 0;
                Boolean       done     = false;
                while (reader.Read() && !done)
                {
                    switch (reader.NodeType)
                    {
                    case XmlNodeType.Element:     // The node is an element.
                        if (reader.Name.Equals("htmlparse.Course"))
                        {
                            course = new Course();
                        }
                        else
                        {
                            property = reader.Name;
                        }
                        break;

                    case XmlNodeType.Text:     //Display the text in each element.
                        if (property.Equals("id"))
                        {
                            course.ID = Int32.Parse(reader.Value);
                        }
                        else if (property.Equals("prefix"))
                        {
                            course.coursePrefix = reader.Value;
                        }
                        else if (property.Equals("number"))
                        {
                            course.courseNumber = Int32.Parse(reader.Value);
                        }
                        else if (property.Equals("title"))
                        {
                            course.courseTitle = reader.Value;
                        }
                        else if (property.Equals("description"))
                        {
                            course.courseDescription = reader.Value;
                        }
                        else if (property.Equals("minHours"))
                        {
                            course.minHours = int.Parse(reader.Value);
                        }
                        else if (property.Equals("maxHours"))
                        {
                            course.maxHours = int.Parse(reader.Value);
                        }
                        else if (property.Equals("variableHours"))
                        {
                            if (reader.Value.Equals("false"))
                            {
                                course.variable = false;
                            }
                            else
                            {
                                course.variable = true;
                            }
                        }
                        else if (property.Equals("ugrad"))
                        {
                            if (reader.Value.Equals("false"))
                            {
                                course.undergrad = false;
                            }
                            else
                            {
                                course.undergrad = true;
                            }
                        }
                        else if (property.Equals("grad"))
                        {
                            if (reader.Value.Equals("false"))
                            {
                                course.graduate = false;
                            }
                            else
                            {
                                course.graduate = true;
                            }
                        }
                        break;

                    case XmlNodeType.EndElement:     //Display the end of the element.
                        if (reader.Name.Equals("htmlparse.Course"))
                        {
                            try
                            {
                                context.Courses.AddOrUpdate(i => i.ID, course);
                                //if (count++ > 500)
                                //{
                                //    done = true;
                                //}
                            }
                            catch (System.Data.Entity.Validation.DbEntityValidationException ex)
                            {
                                var sb = new System.Text.StringBuilder();
                                foreach (var failure in ex.EntityValidationErrors)
                                {
                                    sb.AppendFormat("{0} failed validation", failure.Entry.Entity.GetType());
                                    foreach (var error in failure.ValidationErrors)
                                    {
                                        sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage);
                                        sb.AppendLine();
                                    }
                                }
                                throw new Exception(sb.ToString());
                            }
                        }
                        break;
                    }
                }
                reader.Close();
                context.SaveChanges();

                reader = new XmlTextReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName + "ksu_electivelists.xml"));
                ElectiveList elist = null;
                property = null;
                count    = 0;
                done     = false;
                while (reader.Read() && !done)
                {
                    switch (reader.NodeType)
                    {
                    case XmlNodeType.Element:     // The node is an element.
                        if (reader.Name.Equals("htmlparse.ElectiveList"))
                        {
                            elist = new ElectiveList();
                        }
                        else
                        {
                            property = reader.Name;
                        }
                        break;

                    case XmlNodeType.Text:     //Display the text in each element.
                        if (property.Equals("id"))
                        {
                            elist.ID = Int32.Parse(reader.Value);
                        }
                        else if (property.Equals("name"))
                        {
                            elist.electiveListName = reader.Value;
                        }
                        else if (property.Equals("shortname"))
                        {
                            elist.shortName = reader.Value;
                        }
                        break;

                    case XmlNodeType.EndElement:     //Display the end of the element.
                        if (reader.Name.Equals("htmlparse.ElectiveList"))
                        {
                            try
                            {
                                context.ElectiveLists.AddOrUpdate(i => i.ID, elist);
                                //if (count++ > 500)
                                //{
                                //    done = true;
                                //}
                            }
                            catch (System.Data.Entity.Validation.DbEntityValidationException ex)
                            {
                                var sb = new System.Text.StringBuilder();
                                foreach (var failure in ex.EntityValidationErrors)
                                {
                                    sb.AppendFormat("{0} failed validation", failure.Entry.Entity.GetType());
                                    foreach (var error in failure.ValidationErrors)
                                    {
                                        sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage);
                                        sb.AppendLine();
                                    }
                                }
                                throw new Exception(sb.ToString());
                            }
                        }
                        break;
                    }
                }
                reader.Close();
                context.SaveChanges();

                reader = new XmlTextReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName + "ksu_degreeprograms.xml"));
                DegreeProgram dp = null;
                property = null;
                count    = 0;
                done     = false;
                while (reader.Read() && !done)
                {
                    switch (reader.NodeType)
                    {
                    case XmlNodeType.Element:     // The node is an element.
                        if (reader.Name.Equals("htmlparse.DegreeProgram"))
                        {
                            dp = new DegreeProgram();
                        }
                        else
                        {
                            property = reader.Name;
                        }
                        break;

                    case XmlNodeType.Text:     //Display the text in each element.
                        if (property.Equals("id"))
                        {
                            dp.ID = Int32.Parse(reader.Value);
                        }
                        else if (property.Equals("name"))
                        {
                            dp.degreeProgramName = reader.Value;
                        }
                        else if (property.Equals("description"))
                        {
                            dp.degreeProgramDescription = reader.Value;
                        }
                        break;

                    case XmlNodeType.EndElement:     //Display the end of the element.
                        if (reader.Name.Equals("htmlparse.DegreeProgram"))
                        {
                            try
                            {
                                context.DegreePrograms.AddOrUpdate(i => i.ID, dp);
                                //if (count++ > 500)
                                //{
                                //    done = true;
                                //}
                            }
                            catch (System.Data.Entity.Validation.DbEntityValidationException ex)
                            {
                                var sb = new System.Text.StringBuilder();
                                foreach (var failure in ex.EntityValidationErrors)
                                {
                                    sb.AppendFormat("{0} failed validation", failure.Entry.Entity.GetType());
                                    foreach (var error in failure.ValidationErrors)
                                    {
                                        sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage);
                                        sb.AppendLine();
                                    }
                                }
                                throw new Exception(sb.ToString());
                            }
                        }
                        break;
                    }
                }
                reader.Close();
                context.SaveChanges();

                reader = new XmlTextReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName + "ksu_electivelistcourses.xml"));
                ElectiveListCourse ec = null;
                property = null;
                count    = 0;
                done     = false;
                while (reader.Read() && !done)
                {
                    switch (reader.NodeType)
                    {
                    case XmlNodeType.Element:     // The node is an element.
                        if (reader.Name.Equals("htmlparse.ElectiveListCourse"))
                        {
                            ec = new ElectiveListCourse();
                        }
                        else
                        {
                            property = reader.Name;
                        }
                        break;

                    case XmlNodeType.Text:     //Display the text in each element.
                        if (property.Equals("id"))
                        {
                            ec.ID = Int32.Parse(reader.Value);
                        }
                        else if (property.Equals("course"))
                        {
                            ec.courseID = Int32.Parse(reader.Value);
                        }
                        else if (property.Equals("electivelist"))
                        {
                            ec.electiveListID = Int32.Parse(reader.Value);
                        }
                        break;

                    case XmlNodeType.EndElement:     //Display the end of the element.
                        if (reader.Name.Equals("htmlparse.ElectiveListCourse"))
                        {
                            try
                            {
                                context.ElectiveListCourses.AddOrUpdate(i => i.ID, ec);
                                //if (count++ > 500)
                                //{
                                //    done = true;
                                //}
                            }
                            catch (System.Data.Entity.Validation.DbEntityValidationException ex)
                            {
                                var sb = new System.Text.StringBuilder();
                                foreach (var failure in ex.EntityValidationErrors)
                                {
                                    sb.AppendFormat("{0} failed validation", failure.Entry.Entity.GetType());
                                    foreach (var error in failure.ValidationErrors)
                                    {
                                        sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage);
                                        sb.AppendLine();
                                    }
                                }
                                throw new Exception(sb.ToString());
                            }
                        }
                        break;
                    }
                }
                reader.Close();
                context.SaveChanges();

                reader = new XmlTextReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName + "ksu_requiredcourses.xml"));
                RequiredCourse rq = null;
                property = null;
                count    = 0;
                done     = false;
                while (reader.Read() && !done)
                {
                    switch (reader.NodeType)
                    {
                    case XmlNodeType.Element:     // The node is an element.
                        if (reader.Name.Equals("htmlparse.RequiredCourse"))
                        {
                            rq = new RequiredCourse();
                        }
                        else
                        {
                            property = reader.Name;
                        }
                        break;

                    case XmlNodeType.Text:     //Display the text in each element.
                        if (property.Equals("id"))
                        {
                            rq.ID = Int32.Parse(reader.Value);
                        }
                        else if (property.Equals("course"))
                        {
                            rq.courseID = Int32.Parse(reader.Value);
                        }
                        else if (property.Equals("degree"))
                        {
                            rq.degreeProgramID = Int32.Parse(reader.Value);
                        }
                        else if (property.Equals("semester"))
                        {
                            rq.semester = Int32.Parse(reader.Value);
                        }
                        break;

                    case XmlNodeType.EndElement:     //Display the end of the element.
                        if (reader.Name.Equals("htmlparse.RequiredCourse"))
                        {
                            try
                            {
                                context.RequiredCourses.AddOrUpdate(i => i.ID, rq);
                                //if (count++ > 500)
                                //{
                                //    done = true;
                                //}
                            }
                            catch (System.Data.Entity.Validation.DbEntityValidationException ex)
                            {
                                var sb = new System.Text.StringBuilder();
                                foreach (var failure in ex.EntityValidationErrors)
                                {
                                    sb.AppendFormat("{0} failed validation", failure.Entry.Entity.GetType());
                                    foreach (var error in failure.ValidationErrors)
                                    {
                                        sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage);
                                        sb.AppendLine();
                                    }
                                }
                                throw new Exception(sb.ToString());
                            }
                        }
                        break;
                    }
                }
                reader.Close();
                context.SaveChanges();

                reader = new XmlTextReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName + "ksu_electivecourses.xml"));
                ElectiveCourse ecr = null;
                property = null;
                count    = 0;
                done     = false;
                while (reader.Read() && !done)
                {
                    switch (reader.NodeType)
                    {
                    case XmlNodeType.Element:     // The node is an element.
                        if (reader.Name.Equals("htmlparse.ElectiveCourse"))
                        {
                            ecr = new ElectiveCourse();
                        }
                        else
                        {
                            property = reader.Name;
                        }
                        break;

                    case XmlNodeType.Text:     //Display the text in each element.
                        if (property.Equals("id"))
                        {
                            ecr.ID = Int32.Parse(reader.Value);
                        }
                        else if (property.Equals("degree"))
                        {
                            ecr.degreeProgramID = Int32.Parse(reader.Value);
                        }
                        else if (property.Equals("electivelist"))
                        {
                            ecr.electiveListID = Int32.Parse(reader.Value);
                        }
                        else if (property.Equals("semester"))
                        {
                            ecr.semester = Int32.Parse(reader.Value);
                        }
                        else if (property.Equals("credits"))
                        {
                            ecr.credits = Int32.Parse(reader.Value);
                        }
                        break;

                    case XmlNodeType.EndElement:     //Display the end of the element.
                        if (reader.Name.Equals("htmlparse.ElectiveCourse"))
                        {
                            try
                            {
                                context.ElectiveCourses.AddOrUpdate(i => i.ID, ecr);
                                //if (count++ > 500)
                                //{
                                //    done = true;
                                //}
                            }
                            catch (System.Data.Entity.Validation.DbEntityValidationException ex)
                            {
                                var sb = new System.Text.StringBuilder();
                                foreach (var failure in ex.EntityValidationErrors)
                                {
                                    sb.AppendFormat("{0} failed validation", failure.Entry.Entity.GetType());
                                    foreach (var error in failure.ValidationErrors)
                                    {
                                        sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage);
                                        sb.AppendLine();
                                    }
                                }
                                throw new Exception(sb.ToString());
                            }
                        }
                        break;
                    }
                }
                reader.Close();
                context.SaveChanges();

                reader = new XmlTextReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName + "ksu_prerequisitecourses.xml"));
                PrerequisiteCourse pre = null;
                property = null;
                count    = 0;
                done     = false;
                while (reader.Read() && !done)
                {
                    switch (reader.NodeType)
                    {
                    case XmlNodeType.Element:     // The node is an element.
                        if (reader.Name.Equals("htmlparse.PrerequisiteCourse"))
                        {
                            pre = new PrerequisiteCourse();
                        }
                        else
                        {
                            property = reader.Name;
                        }
                        break;

                    case XmlNodeType.Text:     //Display the text in each element.
                        if (property.Equals("id"))
                        {
                            pre.ID = Int32.Parse(reader.Value);
                        }
                        else if (property.Equals("prerequisiteCourse"))
                        {
                            pre.prerequisiteCourseID = Int32.Parse(reader.Value);
                        }
                        else if (property.Equals("prerequisiteFor"))
                        {
                            pre.prerequisiteForCourseID = Int32.Parse(reader.Value);
                        }
                        break;

                    case XmlNodeType.EndElement:     //Display the end of the element.
                        if (reader.Name.Equals("htmlparse.PrerequisiteCourse"))
                        {
                            try
                            {
                                context.PrerequisiteCourses.AddOrUpdate(i => i.ID, pre);
                                //if (count++ > 500)
                                //{
                                //    done = true;
                                //}
                            }
                            catch (System.Data.Entity.Validation.DbEntityValidationException ex)
                            {
                                var sb = new System.Text.StringBuilder();
                                foreach (var failure in ex.EntityValidationErrors)
                                {
                                    sb.AppendFormat("{0} failed validation", failure.Entry.Entity.GetType());
                                    foreach (var error in failure.ValidationErrors)
                                    {
                                        sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage);
                                        sb.AppendLine();
                                    }
                                }
                                throw new Exception(sb.ToString());
                            }
                        }
                        break;
                    }
                }
                reader.Close();
                context.SaveChanges();
            }
        }