string.Concat(string, string)

Here are the examples of the csharp api string.Concat(string, string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

893 Examples 7

19 View Source File : TemplateEngin.cs
License : MIT License
Project Creator : 2881099

private static ITemplateOutput Parser(string tplcode, string[] usings, IDictionary options) {
			int view = Interlocked.Increment(ref _view);
			StringBuilder sb = new StringBuilder();
			IDictionary options_copy = new Hashtable();
			foreach (DictionaryEntry options_de in options) options_copy[options_de.Key] = options_de.Value;
			sb.AppendFormat(@"
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;{1}

//namespace TplDynamicCodeGenerate {{
	public clreplaced TplDynamicCodeGenerate_view{0} : FreeSql.Template.TemplateEngin.ITemplateOutput {{
		public FreeSql.Template.TemplateEngin.TemplateReturnInfo OuTpUt(StringBuilder tOuTpUt, IDictionary oPtIoNs, string rEfErErFiLeNaMe, FreeSql.Template.TemplateEngin tEmPlAtEsEnDeR) {{
			FreeSql.Template.TemplateEngin.TemplateReturnInfo rTn = tOuTpUt == null ? 
				new FreeSql.Template.TemplateEngin.TemplateReturnInfo {{ Sb = (tOuTpUt = new StringBuilder()), Blocks = new Dictionary<string, int[]>() }} :
				new FreeSql.Template.TemplateEngin.TemplateReturnInfo {{ Sb = tOuTpUt, Blocks = new Dictionary<string, int[]>() }};
			Dictionary<string, int[]> TPL__blocks = rTn.Blocks;
			Stack<int[]> TPL__blocks_stack = new Stack<int[]>();
			int[] TPL__blocks_stack_peek;
			List<IDictionary> TPL__forc = new List<IDictionary>();
			Func<IDictionary> pRoCeSsOpTiOnS = new Func<IDictionary>(delegate () {{
				IDictionary nEwoPtIoNs = new Hashtable();
				foreach (DictionaryEntry oPtIoNs_dE in oPtIoNs)
					nEwoPtIoNs[oPtIoNs_dE.Key] = oPtIoNs_dE.Value;
				foreach (IDictionary TPL__forc_dIc in TPL__forc)
					foreach (DictionaryEntry TPL__forc_dIc_dE in TPL__forc_dIc)
						nEwoPtIoNs[TPL__forc_dIc_dE.Key] = TPL__forc_dIc_dE.Value;
				return nEwoPtIoNs;
			}});
			FreeSql.Template.TemplateEngin.TemplateIf tPlIf = delegate(object exp) {{
				if (exp is bool) return (bool)exp;
				if (exp == null) return false;
				if (exp is int && (int)exp == 0) return false;
				if (exp is string && (string)exp == string.Empty) return false;
				if (exp is long && (long)exp == 0) return false;
				if (exp is short && (short)exp == 0) return false;
				if (exp is byte && (byte)exp == 0) return false;
				if (exp is double && (double)exp == 0) return false;
				if (exp is float && (float)exp == 0) return false;
				if (exp is decimal && (decimal)exp == 0) return false;
				return true;
			}};
			FreeSql.Template.TemplateEngin.TemplatePrint print = delegate(object[] pArMs) {{
				if (pArMs == null || pArMs.Length == 0) return;
				foreach (object pArMs_A in pArMs) if (pArMs_A != null) tOuTpUt.Append(pArMs_A);
			}};
			FreeSql.Template.TemplateEngin.TemplatePrint Print = print;", view, usings?.Any() == true ? $"\r\nusing {string.Join(";\r\nusing ", usings)};" : "");

			#region {miss}...{/miss}块内容将不被解析
			string[] tmp_content_arr = _reg_miss.Split(tplcode);
			if (tmp_content_arr.Length > 1) {
				sb.AppendFormat(@"
			string[] TPL__MISS = new string[{0}];", Math.Ceiling(1.0 * (tmp_content_arr.Length - 1) / 2));
				int miss_len = -1;
				for (int a = 1; a < tmp_content_arr.Length; a += 2) {
					sb.Append(string.Concat(@"
			TPL__MISS[", ++miss_len, @"] = """, Utils.GetConstString(tmp_content_arr[a]), @""";"));
					tmp_content_arr[a] = string.Concat("{#TPL__MISS[", miss_len, "]}");
				}
				tplcode = string.Join("", tmp_content_arr);
			}
			#endregion
			#region 扩展语法如 <div @if="表达式"></div>
			tplcode = htmlSyntax(tplcode, 3); //<div @if="c#表达式" @for="index 1,100"></div>
											  //处理 {% %} 块 c#代码
			tmp_content_arr = _reg_code.Split(tplcode);
			if (tmp_content_arr.Length == 1) {
				tplcode = Utils.GetConstString(tplcode)
					.Replace("{%", "{$TEMPLATE__CODE}")
					.Replace("%}", "{/$TEMPLATE__CODE}");
			} else {
				tmp_content_arr[0] = Utils.GetConstString(tmp_content_arr[0]);
				for (int a = 1; a < tmp_content_arr.Length; a += 4) {
					tmp_content_arr[a] = "{$TEMPLATE__CODE}";
					tmp_content_arr[a + 2] = "{/$TEMPLATE__CODE}";
					tmp_content_arr[a + 3] = Utils.GetConstString(tmp_content_arr[a + 3]);
				}
				tplcode = string.Join("", tmp_content_arr);
			}
			#endregion
			sb.Append(@"
			tOuTpUt.Append(""");

			string error = null;
			int tpl_tmpid = 0;
			int forc_i = 0;
			string extends = null;
			Stack<string> codeTree = new Stack<string>();
			Stack<string> forEndRepl = new Stack<string>();
			sb.Append(_reg.Replace(tplcode, delegate (Match m) {
				string _0 = m.Groups[0].Value;
				if (!string.IsNullOrEmpty(error)) return _0;

				string _1 = m.Groups[1].Value.Trim(' ', '\t');
				string _2 = m.Groups[2].Value
					.Replace("\\\\", "\\")
					.Replace("\\\"", "\"");
				_2 = Utils.ReplaceSingleQuote(_2);

				switch (_1) {
					#region $TEMPLATE__CODE--------------------------------------------------
					case "$TEMPLATE__CODE":
						codeTree.Push(_1);
						return @""");
";
					case "/$TEMPLATE__CODE":
						string pop = codeTree.Pop();
						if (pop != "$TEMPLATE__CODE") {
							codeTree.Push(pop);
							error = "编译出错,{% 与 %} 并没有配对";
							return _0;
						}
						return @"
			tOuTpUt.Append(""";
					#endregion
					case "include":
						return string.Format(@""");
tEmPlAtEsEnDeR.RenderFile2(tOuTpUt, pRoCeSsOpTiOnS(), ""{0}"", rEfErErFiLeNaMe);
			tOuTpUt.Append(""", _2);
					case "import":
						return _0;
					case "module":
						return _0;
					case "/module":
						return _0;
					case "extends":
						//{extends ../inc/layout.html}
						if (string.IsNullOrEmpty(extends) == false) return _0;
						extends = _2;
						return string.Empty;
					case "block":
						codeTree.Push("block");
						return string.Format(@""");
TPL__blocks_stack_peek = new int[] {{ tOuTpUt.Length, 0 }};
TPL__blocks_stack.Push(TPL__blocks_stack_peek);
TPL__blocks.Add(""{0}"", TPL__blocks_stack_peek);
tOuTpUt.Append(""", _2.Trim(' ', '\t'));
					case "/block":
						codeTreeEnd(codeTree, "block");
						return @""");
TPL__blocks_stack_peek = TPL__blocks_stack.Pop();
TPL__blocks_stack_peek[1] = tOuTpUt.Length - TPL__blocks_stack_peek[0];
tOuTpUt.Append(""";

					#region ##---------------------------------------------------------
					case "#":
						if (_2[0] == '#')
							return string.Format(@""");
			try {{ Print({0}); }} catch {{ }}
			tOuTpUt.Append(""", _2.Substring(1));
						return string.Format(@""");
			Print({0});
			tOuTpUt.Append(""", _2);
					#endregion
					#region for--------------------------------------------------------
					case "for":
						forc_i++;
						int cur_tpl_tmpid = tpl_tmpid;
						string sb_endRepl = string.Empty;
						StringBuilder sbfor = new StringBuilder();
						sbfor.Append(@""");");
						Match mfor = _reg_forin.Match(_2);
						if (mfor.Success) {
							string mfor1 = mfor.Groups[1].Value.Trim(' ', '\t');
							string mfor2 = mfor.Groups[2].Value.Trim(' ', '\t');
							sbfor.AppendFormat(@"
//new Action(delegate () {{
	IDictionary TPL__tmp{0} = new Hashtable();
	TPL__forc.Add(TPL__tmp{0});
	var TPL__tmp{1} = {3};
	var TPL__tmp{2} = {4};", ++tpl_tmpid, ++tpl_tmpid, ++tpl_tmpid, mfor.Groups[3].Value, mfor1);
							sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
	{0} = TPL__tmp{1};", mfor1, cur_tpl_tmpid + 3));
							if (options_copy.Contains(mfor1) == false) options_copy[mfor1] = null;
							if (!string.IsNullOrEmpty(mfor2)) {
								sbfor.AppendFormat(@"
	var TPL__tmp{1} = {0};
	{0} = 0;", mfor2, ++tpl_tmpid);
								sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
	{0} = TPL__tmp{1};", mfor2, tpl_tmpid));
								if (options_copy.Contains(mfor2) == false) options_copy[mfor2] = null;
							}
							sbfor.AppendFormat(@"
	if (TPL__tmp{1} != null)
	foreach (var TPL__tmp{0} in TPL__tmp{1}) {{", ++tpl_tmpid, cur_tpl_tmpid + 2);
							if (!string.IsNullOrEmpty(mfor2))
								sbfor.AppendFormat(@"
		TPL__tmp{1}[""{0}""] = ++ {0};", mfor2, cur_tpl_tmpid + 1);
							sbfor.AppendFormat(@"
		TPL__tmp{1}[""{0}""] = TPL__tmp{2};
		{0} = TPL__tmp{2};
		tOuTpUt.Append(""", mfor1, cur_tpl_tmpid + 1, tpl_tmpid);
							codeTree.Push("for");
							forEndRepl.Push(sb_endRepl);
							return sbfor.ToString();
						}
						mfor = _reg_foron.Match(_2);
						if (mfor.Success) {
							string mfor1 = mfor.Groups[1].Value.Trim(' ', '\t');
							string mfor2 = mfor.Groups[2].Value.Trim(' ', '\t');
							string mfor3 = mfor.Groups[3].Value.Trim(' ', '\t');
							sbfor.AppendFormat(@"
//new Action(delegate () {{
	IDictionary TPL__tmp{0} = new Hashtable();
	TPL__forc.Add(TPL__tmp{0});
	var TPL__tmp{1} = {3};
	var TPL__tmp{2} = {4};", ++tpl_tmpid, ++tpl_tmpid, ++tpl_tmpid, mfor.Groups[4].Value, mfor1);
							sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
	{0} = TPL__tmp{1};", mfor1, cur_tpl_tmpid + 3));
							if (options_copy.Contains(mfor1) == false) options_copy[mfor1] = null;
							if (!string.IsNullOrEmpty(mfor2)) {
								sbfor.AppendFormat(@"
	var TPL__tmp{1} = {0};", mfor2, ++tpl_tmpid);
								sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
	{0} = TPL__tmp{1};", mfor2, tpl_tmpid));
								if (options_copy.Contains(mfor2) == false) options_copy[mfor2] = null;
							}
							if (!string.IsNullOrEmpty(mfor3)) {
								sbfor.AppendFormat(@"
	var TPL__tmp{1} = {0};
	{0} = 0;", mfor3, ++tpl_tmpid);
								sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
	{0} = TPL__tmp{1};", mfor3, tpl_tmpid));
								if (options_copy.Contains(mfor3) == false) options_copy[mfor3] = null;
							}
							sbfor.AppendFormat(@"
	if (TPL__tmp{2} != null)
	foreach (DictionaryEntry TPL__tmp{1} in TPL__tmp{2}) {{
		{0} = TPL__tmp{1}.Key;
		TPL__tmp{3}[""{0}""] = {0};", mfor1, ++tpl_tmpid, cur_tpl_tmpid + 2, cur_tpl_tmpid + 1);
							if (!string.IsNullOrEmpty(mfor2))
								sbfor.AppendFormat(@"
		{0} = TPL__tmp{1}.Value;
		TPL__tmp{2}[""{0}""] = {0};", mfor2, tpl_tmpid, cur_tpl_tmpid + 1);
							if (!string.IsNullOrEmpty(mfor3))
								sbfor.AppendFormat(@"
		TPL__tmp{1}[""{0}""] = ++ {0};", mfor3, cur_tpl_tmpid + 1);
							sbfor.AppendFormat(@"
		tOuTpUt.Append(""");
							codeTree.Push("for");
							forEndRepl.Push(sb_endRepl);
							return sbfor.ToString();
						}
						mfor = _reg_forab.Match(_2);
						if (mfor.Success) {
							string mfor1 = mfor.Groups[1].Value.Trim(' ', '\t');
							sbfor.AppendFormat(@"
//new Action(delegate () {{
	IDictionary TPL__tmp{0} = new Hashtable();
	TPL__forc.Add(TPL__tmp{0});
	var TPL__tmp{1} = {5};
	{5} = {3} - 1;
	if ({5} == null) {5} = 0;
	var TPL__tmp{2} = {4} + 1;
	while (++{5} < TPL__tmp{2}) {{
		TPL__tmp{0}[""{5}""] = {5};
		tOuTpUt.Append(""", ++tpl_tmpid, ++tpl_tmpid, ++tpl_tmpid, mfor.Groups[2].Value, mfor.Groups[3].Value, mfor1);
							sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
	{0} = TPL__tmp{1};", mfor1, cur_tpl_tmpid + 1));
							if (options_copy.Contains(mfor1) == false) options_copy[mfor1] = null;
							codeTree.Push("for");
							forEndRepl.Push(sb_endRepl);
							return sbfor.ToString();
						}
						return _0;
					case "/for":
						if (--forc_i < 0) return _0;
						codeTreeEnd(codeTree, "for");
						return string.Format(@""");
	}}{0}
	TPL__forc.RemoveAt(TPL__forc.Count - 1);
//}})();
			tOuTpUt.Append(""", forEndRepl.Pop());
					#endregion
					#region if---------------------------------------------------------
					case "if":
						codeTree.Push("if");
						return string.Format(@""");
			if ({1}tPlIf({0})) {{
				tOuTpUt.Append(""", _2[0] == '!' ? _2.Substring(1) : _2, _2[0] == '!' ? '!' : ' ');
					case "elseif":
						codeTreeEnd(codeTree, "if");
						codeTree.Push("if");
						return string.Format(@""");
			}} else if ({1}tPlIf({0})) {{
				tOuTpUt.Append(""", _2[0] == '!' ? _2.Substring(1) : _2, _2[0] == '!' ? '!' : ' ');
					case "else":
						codeTreeEnd(codeTree, "if");
						codeTree.Push("if");
						return @""");
			} else {
			tOuTpUt.Append(""";
					case "/if":
						codeTreeEnd(codeTree, "if");
						return @""");
			}
			tOuTpUt.Append(""";
						#endregion
				}
				return _0;
			}));

			sb.Append(@""");");
			if (string.IsNullOrEmpty(extends) == false) {
				sb.AppendFormat(@"
FreeSql.Template.TemplateEngin.TemplateReturnInfo eXtEnDs_ReT = tEmPlAtEsEnDeR.RenderFile2(null, pRoCeSsOpTiOnS(), ""{0}"", rEfErErFiLeNaMe);
string rTn_Sb_string = rTn.Sb.ToString();
foreach(string eXtEnDs_ReT_blocks_key in eXtEnDs_ReT.Blocks.Keys) {{
	if (rTn.Blocks.ContainsKey(eXtEnDs_ReT_blocks_key)) {{
		int[] eXtEnDs_ReT_blocks_value = eXtEnDs_ReT.Blocks[eXtEnDs_ReT_blocks_key];
		eXtEnDs_ReT.Sb.Remove(eXtEnDs_ReT_blocks_value[0], eXtEnDs_ReT_blocks_value[1]);
		int[] rTn_blocks_value = rTn.Blocks[eXtEnDs_ReT_blocks_key];
		eXtEnDs_ReT.Sb.Insert(eXtEnDs_ReT_blocks_value[0], rTn_Sb_string.Substring(rTn_blocks_value[0], rTn_blocks_value[1]));
		foreach(string eXtEnDs_ReT_blocks_keyb in eXtEnDs_ReT.Blocks.Keys) {{
			if (eXtEnDs_ReT_blocks_keyb == eXtEnDs_ReT_blocks_key) continue;
			int[] eXtEnDs_ReT_blocks_valueb = eXtEnDs_ReT.Blocks[eXtEnDs_ReT_blocks_keyb];
			if (eXtEnDs_ReT_blocks_valueb[0] >= eXtEnDs_ReT_blocks_value[0])
				eXtEnDs_ReT_blocks_valueb[0] = eXtEnDs_ReT_blocks_valueb[0] - eXtEnDs_ReT_blocks_value[1] + rTn_blocks_value[1];
		}}
		eXtEnDs_ReT_blocks_value[1] = rTn_blocks_value[1];
	}}
}}
return eXtEnDs_ReT;
", extends);
			} else {
				sb.Append(@"
return rTn;");
			}
			sb.Append(@"
		}
	}
//}
");
			var str = "FreeSql.Template.TemplateEngin.TemplatePrint Print = print;";
			int dim_idx = sb.ToString().IndexOf(str) + str.Length;
			foreach (string dic_name in options_copy.Keys) {
				sb.Insert(dim_idx, string.Format(@"
			dynamic {0} = oPtIoNs[""{0}""];", dic_name));
			}
			//Console.WriteLine(sb.ToString());
			return Complie(sb.ToString(), @"TplDynamicCodeGenerate_view" + view);
		}

19 View Source File : RazorModel.cs
License : MIT License
Project Creator : 2881099

public string GetCsName(string name)
	{
		name = Regex.Replace(name.TrimStart('@', '.'), @"[^\w]", "_");
		name = char.IsLetter(name, 0) ? name : string.Concat("_", name);
		if (task.OptionsEnreplacedy01) name = UFString(name);
		if (task.OptionsEnreplacedy02) name = UFString(name.ToLower());
		if (task.OptionsEnreplacedy03) name = name.ToLower();
		if (task.OptionsEnreplacedy04) name = string.Join("", name.Split('_').Select(a => UFString(a)));
		return name;
	}

19 View Source File : TemplateEngin.cs
License : MIT License
Project Creator : 2881099

private static string htmlSyntax(string tplcode, int num) {

			while (num-- > 0) {
				string[] arr = _reg_syntax.Split(tplcode);

				if (arr.Length == 1) break;
				for (int a = 1; a < arr.Length; a += 4) {
					string tag = string.Concat('<', arr[a]);
					string end = string.Concat("</", arr[a], '>');
					int fc = 1;
					for (int b = a; fc > 0 && b < arr.Length; b += 4) {
						if (b > a && arr[a].ToLower() == arr[b].ToLower()) fc++;
						int bpos = 0;
						while (true) {
							int fa = arr[b + 3].IndexOf(tag, bpos);
							int fb = arr[b + 3].IndexOf(end, bpos);
							if (b == a) {
								var z = arr[b + 3].IndexOf("/>");
								if ((fb == -1 || z < fb) && z != -1) {
									var y = arr[b + 3].Substring(0, z + 2);
									if (_reg_htmltag.IsMatch(y) == false)
										fb = z - end.Length + 2;
								}
							}
							if (fa == -1 && fb == -1) break;
							if (fa != -1 && (fa < fb || fb == -1)) {
								fc++;
								bpos = fa + tag.Length;
								continue;
							}
							if (fb != -1) fc--;
							if (fc <= 0) {
								var a1 = arr[a + 1];
								var end3 = string.Concat("{/", a1, "}");
								if (a1.ToLower() == "else") {
									if (_reg_blank.Replace(arr[a - 4 + 3], "").EndsWith("{/if}", StringComparison.CurrentCultureIgnoreCase) == true) {
										var idx = arr[a - 4 + 3].IndexOf("{/if}");
										arr[a - 4 + 3] = string.Concat(arr[a - 4 + 3].Substring(0, idx), arr[a - 4 + 3].Substring(idx + 5));
										//如果 @else="有条件内容",则变换成 elseif 条件内容
										if (_reg_blank.Replace(arr[a + 2], "").Length > 0) a1 = "elseif";
										end3 = "{/if}";
									} else {
										arr[a] = string.Concat("指令 @", arr[a + 1], "='", arr[a + 2], "' 没紧接着 if/else 指令之后,无效. <", arr[a]);
										arr[a + 1] = arr[a + 2] = string.Empty;
									}
								}
								if (arr[a + 1].Length > 0) {
									if (_reg_blank.Replace(arr[a + 2], "").Length > 0 || a1.ToLower() == "else") {
										arr[b + 3] = string.Concat(arr[b + 3].Substring(0, fb + end.Length), end3, arr[b + 3].Substring(fb + end.Length));
										arr[a] = string.Concat("{", a1, " ", arr[a + 2], "}<", arr[a]);
										arr[a + 1] = arr[a + 2] = string.Empty;
									} else {
										arr[a] = string.Concat('<', arr[a]);
										arr[a + 1] = arr[a + 2] = string.Empty;
									}
								}
								break;
							}
							bpos = fb + end.Length;
						}
					}
					if (fc > 0) {
						arr[a] = string.Concat("不严谨的html格式,请检查 ", arr[a], " 的结束标签, @", arr[a + 1], "='", arr[a + 2], "' 指令无效. <", arr[a]);
						arr[a + 1] = arr[a + 2] = string.Empty;
					}
				}
				if (arr.Length > 0) tplcode = string.Join(string.Empty, arr);
			}
			return tplcode;
		}

19 View Source File : TemplateEngin.cs
License : MIT License
Project Creator : 2881099

public TemplateReturnInfo RenderFile2(StringBuilder sb, IDictionary options, string filename, string refererFilename) {
			if (filename[0] == '/' || string.IsNullOrEmpty(refererFilename)) refererFilename = _viewDir;
			//else refererFilename = Path.GetDirectoryName(refererFilename);
			string filename2 = Utils.TranslateUrl(filename, refererFilename);
			Console.WriteLine(filename2);
			ITemplateOutput tpl;
			if (_cache.TryGetValue(filename2, out tpl) == false) {
				string tplcode = File.Exists(filename2) == false ? string.Concat("文件不存在 ", filename) : Utils.ReadTextFile(filename2);
				tpl = Parser(tplcode, _usings, options);
				lock (_cache_lock) {
					if (_cache.ContainsKey(filename2) == false) {
						_cache.Add(filename2, tpl);
					}
				}
			}
			try {
				return tpl.OuTpUt(sb, options, filename2, this);
			} catch (Exception ex) {
				TemplateReturnInfo ret = sb == null ?
					new TemplateReturnInfo { Sb = new StringBuilder(), Blocks = new Dictionary<string, int[]>() } :
					new TemplateReturnInfo { Sb = sb, Blocks = new Dictionary<string, int[]>() };
				ret.Sb.Append(refererFilename);
				ret.Sb.Append(" -> ");
				ret.Sb.Append(filename);
				ret.Sb.Append("\r\n");
				ret.Sb.Append(ex.Message);
				ret.Sb.Append("\r\n");
				ret.Sb.Append(ex.StackTrace);
				return ret;
			}
		}

19 View Source File : RazorModel.cs
License : MIT License
Project Creator : 2881099

public string GetCsName(string name) {
		name = Regex.Replace(name.TrimStart('@', '.'), @"[^\w]", "_");
		name = char.IsLetter(name, 0) ? name : string.Concat("_", name);
		if (task.OptionsEnreplacedy01) name = UFString(name);
		if (task.OptionsEnreplacedy02) name = UFString(name.ToLower());
		if (task.OptionsEnreplacedy03) name = name.ToLower();
		if (task.OptionsEnreplacedy04) name = string.Join("", name.Split('_').Select(a => UFString(a)));
		return name;
	}

19 View Source File : LeapMotionConfigurationChecker.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

private static void AddLeapEditorAsmDefs()
        {
            if (FileUtilities.FindFilesInreplacedets("LeapMotion.Core.Editor.asmdef").Length == 0)
            {
                foreach (KeyValuePair<string, string[]> leapAsmDef in leapEditorDirectories)
                {
                    // Convert asmdef name to a path
                    string leapAsmDefPath = leapAsmDef.Key.Replace('.', '/');

                    string leapAsmDefFilename = string.Concat(leapAsmDef.Key, ".asmdef");

                    // Path for the asmdef including the filename
                    string fullLeapAsmDefFilePath = Path.Combine(Application.dataPath, pathDifference, leapAsmDefPath, leapAsmDefFilename);

                    // Path for the asmdef NOT including the filename
                    string fullLeapAsmDefDirectoryPath = Path.Combine(Application.dataPath, pathDifference, leapAsmDefPath);

                    // Make sure the directory exists within the leap core replacedets before we add the asmdef
                    // The leap core replacedets version 4.5.0 contains the LeapMotion/Core/Tests/Editor directory while 4.4.0 does not.
                    if (!File.Exists(fullLeapAsmDefFilePath) && Directory.Exists(fullLeapAsmDefDirectoryPath))
                    {
                        // Create and save the new asmdef
                        replacedemblyDefinition leapEditorAsmDef = new replacedemblyDefinition
                        {
                            Name = leapAsmDef.Key,
                            References = leapAsmDef.Value,
                            IncludePlatforms = new string[] { "Editor" }
                        };

#if !UNITY_2019_3_OR_NEWER
                        // In Unity 2018.4, directories that contain tests need to have a test replacedembly.
                        // An asmdef is added to a leap directory that contains tests for the leap core replacedets 4.5.0.
                        if (leapEditorAsmDef.Name.Contains("Tests"))
                        {
                            leapEditorAsmDef.OptionalUnityReferences = new string[] { "Testreplacedemblies" };
                        }
#endif

                        leapEditorAsmDef.Save(fullLeapAsmDefFilePath);
                    }
                }
            }
        }

19 View Source File : LeapMotionConfigurationChecker.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

[MenuItem("Mixed Reality Toolkit/Utilities/Leap Motion/Configure CSC File for Leap Motion")]
        static void UpdateCSC()
        {
            // The csc file will always be in the root of replacedets
            string cscFilePath = Path.Combine(Application.dataPath, "csc.rsp");

            // Each line of the csc file
            List<string> cscFileLines = new List<string>();

            // List of the warning numbers after "-nowarn: " in the csc file
            List<string> warningNumbers = new List<string>();

            // List of new warning numbers to add to the csc file
            List<string> warningNumbersToAdd = new List<string>()
            {
                "618",
                "649"
            };

            using (StreamReader streamReader = new StreamReader(cscFilePath))
            {
                while (streamReader.Peek() > -1)
                {
                    string cscFileLine = streamReader.ReadLine();

                    if (cscFileLine.Contains("-nowarn"))
                    {
                        string[] currentWarningNumbers = cscFileLine.Split(',', ':');
                        warningNumbers = currentWarningNumbers.ToList();

                        // Remove "nowarn" from the warningNumbers list
                        warningNumbers.Remove("-nowarn");

                        foreach (string warningNumberToAdd in warningNumbersToAdd)
                        {
                            // Add the new warning numbers if they are not already in the file
                            if (!warningNumbers.Contains(warningNumberToAdd))
                            {
                                warningNumbers.Add(warningNumberToAdd);
                            }
                        }

                        cscFileLines.Add(string.Join(",", warningNumbers));
                    }
                    else
                    {
                        cscFileLines.Add(cscFileLine);
                    }
                }
            }

            using (StreamWriter streamWriter = new StreamWriter(cscFilePath))
            {
                foreach (string cscLine in cscFileLines)
                {
                    if (cscLine.StartsWith("1701"))
                    {
                        string warningNumbersJoined = string.Join(",", warningNumbers);
                        streamWriter.WriteLine(string.Concat("-nowarn:", warningNumbersJoined));
                    }
                    else
                    {
                        streamWriter.WriteLine(cscLine);
                    } 
                }
            }

            Debug.Log($"Saving {cscFilePath}");
        }

19 View Source File : XmlSerializableDataContractExtensions.cs
License : MIT License
Project Creator : actions

private static SerializableProperties GetSerializableProperties(TypeInfo type)
        {
            if (SerializablePropertiesByType.TryGetValue(type, out var properties))
            {
                return properties;
            }

            var dataContract = type.GetCustomAttribute(typeof(XmlSerializableDataContractAttribute)) as XmlSerializableDataContractAttribute;
            var enableCamelCaseNameCompat = dataContract == null ? false : dataContract.EnableCamelCaseNameCompat;

            var declaredProperties = new List<SerializableProperty>();

            foreach (var declaredProperty in type.DeclaredProperties)
            {
                if (declaredProperty.GetCustomAttribute(typeof(XmlIgnoreAttribute)) != null)
                {
                    continue;
                }

                if (declaredProperty.SetMethod == null)
                {
                    continue;
                }

                var dataMember = declaredProperty.GetCustomAttribute(typeof(DataMemberAttribute)) as DataMemberAttribute;
                if (dataMember == null)
                {
                    continue;
                }

                var shouldSerializeMethodName = string.Concat("ShouldSerialize", declaredProperty.Name);
                var shouldSerializeMethod = type.GetDeclaredMethod(shouldSerializeMethodName);

                declaredProperties.Add(new SerializableProperty(declaredProperty, dataMember, shouldSerializeMethod, enableCamelCaseNameCompat));
            }

            var inheritedProperties = Enumerable.Empty<SerializableProperty>();
            if (type.BaseType != typeof(object))
            {
                inheritedProperties = GetSerializableProperties(type.BaseType.GetTypeInfo()).EnumeratedInOrder;
            }

            var serializableProperties = new SerializableProperties(declaredProperties, inheritedProperties);

            return SerializablePropertiesByType.GetOrAdd(type, serializableProperties);
        }

19 View Source File : TestBigDecimalCritical.cs
License : MIT License
Project Creator : AdamWhiteHat

[TestProperty("Basic", "Conversion")]
		[TestMethod]
		public void TestTruncate()
		{
			string inputTruncated = "38776413731534507341472294220970933835515664718260518542692164892369393388454765429965711304132864249950074173248631118139885711281403156400182208418498132380665348582256048635378814909035638369142648772177618951899185003568005598389270883746269077440991532220847404333505059368816860680653357748237545067181074698997348124273540082967040205337039719556204791774654186626822192852578297197622945023468587167940717672154626982847038945027431144177383552390076867181200131087852865589018597759807623800948540502708501473286123912110702619773244550322465985979980114779581215743799790210865866959716136152785422203785552850816565888483726280027736811701443283167094373785256268739306209472514414456698923382789454032363968616464876677737866600848986505927023714735496267888826964325695603484817243244809072199216323431074501911199589021095576091452848741385260278621154863084476153732935785975553768625991893151359011912157996422994871709298494233782632174324940552077998861058801035481527689611495569489001108047129667715138204276438217877458404549511313153150137527893798615996618488836664617057038126333313180040094667868763537391421370724952266262848120654117339947389714860375532634890853303061644123428823851175161042458377024247370039795707768407904842511280809838660155394320788005292339449327116941969519022963362256288633034183673183754543670394109495242494711094883817203892173617367313695468521390931623680173196403022932833410798171066411176995128779282872081932608267999112302172207922731784899893348412676098162467010668924433588685153611407005617772276741793479524433622378470125354022566116327819435029065557564148488746638319658731270457607183892425161850287824787546065413294231650473976473355046501500793677901782339691542233183741598103696583351788651177203938936918102755367072014549821942367309956671236707350861545099496206538228683951185018840006137763162355709495445928668480960580978979870379511703883251713690511544429859593313279574155504139941107166963497890833932811052504269372145803660626639428643564562691059910703703938694915154537936003382455188656514686359660013747580119285264755448830584594983111162605867224680013454700621697086948523549156403848856543212816956769085216390639154261614649538130954560421673680672884105498050605587531872704107707071402689983600332112655608194612408217782173036018661692139351433658340756975168361107372727516912020823362368253159826937134217107045868191298957690827125630453728790792408734840661702578638598543186544910552465999106381802375938701350575940262569041045146526024334627822715612658351899764042223444201035443823410277761971257862200600465373558428055133799307959576455801692979753194304758921759067399106319456847661528054181651013888120488047974670158855437555210689546049958555745098303660202886404313365902203237775035723926097742965028613593632230336269392684340085274710999024668887638930755250701806345477524832568256645103704878731032912768646402146422301881142289323523789305126831904241622042944333916620344863470012778933196413192781253025453531244850133026071231714118351386262249150472643870800725983523611903791303553632632769972142502483519860983067322477753824959399886980031912842700140970151007657989042261109130704991895244868527969247414974047405237324669264878742391500642753525622057641241164177505839173992651361990366480244195157062835803031557544691492841007028723179639729081951702197292799161437892952439082270465575308762112590993865133052593362045638622447863872110087219994330766670422412140283392118259566085972052360790645394540700438378734059789109046910356858343004387656915432928337709841252916626015752013241699464443045041876948902728601721842214670716585909801092203893128618468720651888522728597430373030188565238122801065278124235661294292641028550276301054915567825793810248724267437857461336921376742513529432313053995421425528496990787018582251366776291943999044323970133345610820834058391982655766601126736285624213085882525085728598384700565577250732861707158419417137322187913601105221450993534840307771350787020353312910993312574109077271828643659506792514058623896881407687463008239648545371730757776422468606770212802349464720937428992320859723193781752582479518699133569129895070994026410312951649922900688489934852155962598169718199217867461287501481443450777777718726084902136902441480397119384141792970385831367927360530354214563521320900336914169681532166791668676942898880184098720787172114194029069821244937592713815214434788393095503048740886117426353441330676447598548976011441527165748380891340472246800001389307364429687469295246232117792720007673578989468325170179570094184486525355114468774857635615955720968054081874458733938769018227387365842825259166694681823057556598910704367318366050815517174086712448729791746859581490981539042615521145996146036468018904747552880641671500884541141688250485043379587617571474356672696577799617797264760021142950373293666619603196041523466051054935554966409263947312788960948665394281916627352113060683470291466105925";
			string inputOverflow = "919919200639429489197056";

			BigDecimal expectedResult = BigDecimal.Parse(inputTruncated);
			BigDecimal result = BigDecimal.Parse(string.Concat(inputTruncated, inputOverflow));
			result.Truncate();
			bool success = expectedResult.Equals(result);

			replacedert.IsTrue(success);
		}

19 View Source File : CrmEntitySecurityCacheInfo.cs
License : MIT License
Project Creator : Adoxio

private string BuildKey(Enreplacedy enreplacedy, CrmEnreplacedyRight right, string securityContextKey)
		{
			var baseKey = string.Concat(securityContextKey, ":", enreplacedy.Id, ":", right);

            IIdenreplacedy idenreplacedy;

			return TryGetCurrentIdenreplacedy(out idenreplacedy)
				? string.Concat(baseKey, ":Idenreplacedy=", idenreplacedy.Name)
                : string.Concat(baseKey, ":Anonymous");
        }

19 View Source File : RedisLite.cs
License : MIT License
Project Creator : AElfProject

private byte[][] ReadMultiData()
        {
            int c = SafeReadByte();
            if (c == -1)
                throw CreateResponseError("No more data");

            var s = ReadLine();
            Log("R: {0}", s);

            switch (c)
            {
                // Some commands like BRPOPLPUSH may return Bulk Reply instead of Multi-bulk
                case '$':
                    var t = new byte[2][];
                    t[1] = ParseSingleLine(string.Concat(char.ToString((char) c), s));
                    return t;

                case '-':
                    throw CreateResponseError(s.StartsWith("ERR") ? s.Substring(4) : s);

                case '*':
                    int count;
                    if (int.TryParse(s, out count))
                    {
                        if (count == -1)
                        {
                            //redis is in an invalid state
                            return new byte[0][];
                        }

                        var result = new byte[count][];

                        for (int i = 0; i < count; i++)
                            result[i] = ReadData();

                        return result;
                    }

                    break;
            }

            throw CreateResponseError("Unknown reply on multi-request: " + c + s);
        }

19 View Source File : RedisLite.cs
License : MIT License
Project Creator : AElfProject

private object ReadDeeplyNestedMultiDataItem()
        {
            int c = SafeReadByte();
            if (c == -1)
                throw CreateResponseError("No more data");

            var s = ReadLine();
            Log("R: {0}", s);

            switch (c)
            {
                case '$':
                    return ParseSingleLine(string.Concat(char.ToString((char) c), s));

                case '-':
                    throw CreateResponseError(s.StartsWith("ERR") ? s.Substring(4) : s);

                case '*':
                    int count;
                    if (int.TryParse(s, out count))
                    {
                        var array = new object[count];
                        for (int i = 0; i < count; i++)
                        {
                            array[i] = ReadDeeplyNestedMultiDataItem();
                        }

                        return array;
                    }

                    break;

                default:
                    return s;
            }

            throw CreateResponseError("Unknown reply on multi-request: " + c + s);
        }

19 View Source File : AElfString.cs
License : MIT License
Project Creator : AElfProject

public static string Concat(string str0, string str1)
        {
            return ValidatedString(string.Concat(str0, str1));
        }

19 View Source File : Truncate.cs
License : MIT License
Project Creator : akasarto

public static string Truncate(this string @this, int maxLength, string truncatedSuffix = null)
		{
			if (string.IsNullOrEmpty(@this))
			{
				return string.Empty;
			}

			if (string.IsNullOrWhiteSpace(truncatedSuffix))
			{
				truncatedSuffix = string.Empty;
			}

			int inputLen = @this.Length;

			if (inputLen <= maxLength)
			{
				return @this;
			}

			int breakPosition = @this.IndexOf("\n");

			if (breakPosition < 0)
			{
				breakPosition = @this.IndexOf(".");
			}

			if (breakPosition < 0 || breakPosition > maxLength)
			{
				breakPosition = maxLength;
			}

			int suffixSize = truncatedSuffix.Length;

			if (breakPosition < 0)
			{
				return string.Concat(@this.Substring(0, inputLen - suffixSize), truncatedSuffix);
			}

			if (breakPosition > @this.Length)
			{
				breakPosition = @this.Length;
			}

			breakPosition = breakPosition - suffixSize;

			return string.Concat(@this.Substring(0, breakPosition).Trim(), truncatedSuffix);
		}

19 View Source File : UI.cs
License : MIT License
Project Creator : Alan-FGR

private void WrapText(int wrapWidth)
        {
            if(lastWrapWidth_ == wrapWidth) return;

            lastWrapWidth_ = wrapWidth;

            string[] words = Text.Split(' ');
            string line = String.Empty;
            string wrapped = String.Empty;
            int lines = 1;
            foreach (string word in words)
            {
                if (font.MeasureString(line + word).Length() > wrapWidth)
                {
                    wrapped = String.Concat(wrapped, line, '\n');
                    lines++;
                    line = String.Empty;
                }
                line = String.Concat(line, word, ' ');
            }

            int textHeight = lines * font.LineSpacing;
            rect.Height = textHeight  + Margins * 2;

            wrappedString_ = String.Concat(wrapped, line);
        }

19 View Source File : Auth.cs
License : MIT License
Project Creator : AlaricGilbert

private static async Task<string> EncryptPreplacedword(string preplacedWord)
        {
            string base64String;
            string url = "https://preplacedport.bilibili.com/login?act=getkey&_=" + Common.TimeSpan;
            using (HttpClient hc = new HttpClient())
            {
                var response = await hc.GetAsync(url);
                var stringAsync = await response.Content.ReadreplacedtringAsync();
                JObject jObjects = JObject.Parse(stringAsync);
                string str = jObjects["hash"].ToString();
                string str1 = jObjects["key"].ToString();
                string str2 = string.Concat(str, preplacedWord);
                string str3 = Regex.Match(str1, "BEGIN PUBLIC KEY-----(?<key>[\\s\\S]+)-----END PUBLIC KEY").Groups["key"].Value.Trim();
                byte[] numArray = Convert.FromBase64String(str3);
                Asn1Object obj = Asn1Object.FromByteArray(numArray);
                DerSequence publicKeySequence = (DerSequence)obj;

                DerBitString encodedPublicKey = (DerBitString)publicKeySequence[1];
                DerSequence publicKey = (DerSequence)Asn1Object.FromByteArray(encodedPublicKey.GetBytes());

                DerInteger modulus = (DerInteger)publicKey[0];
                DerInteger exponent = (DerInteger)publicKey[1];
                RsaKeyParameters keyParameters = new RsaKeyParameters(false, modulus.PositiveValue, exponent.PositiveValue);
                RSAParameters parameters = DotNetUtilities.ToRSAParameters(keyParameters);
                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                rsa.ImportParameters(parameters);
                var result = rsa.Encrypt(Encoding.UTF8.GetBytes(str2), RSAEncryptionPadding.Pkcs1);
                base64String = Convert.ToBase64String(result);
            }
            return base64String;
        }

19 View Source File : Common.cs
License : MIT License
Project Creator : AlbertMN

public static replacedembly ReadFromDiskCache(string tempBasePath, replacedemblyName requestedreplacedemblyName)
    {
        var name = requestedreplacedemblyName.Name.ToLowerInvariant();

        if (requestedreplacedemblyName.CultureInfo != null && !String.IsNullOrEmpty(requestedreplacedemblyName.CultureInfo.Name))
            name = $"{requestedreplacedemblyName.CultureInfo.Name}.{name}";

        var bittyness = IntPtr.Size == 8 ? "64" : "32";
        var replacedemblyTempFilePath = Path.Combine(tempBasePath, String.Concat(name, ".dll"));
        if (File.Exists(replacedemblyTempFilePath))
        {
            return replacedembly.LoadFile(replacedemblyTempFilePath);
        }
        replacedemblyTempFilePath = Path.ChangeExtension(replacedemblyTempFilePath, "exe");
        if (File.Exists(replacedemblyTempFilePath))
        {
            return replacedembly.LoadFile(replacedemblyTempFilePath);
        }
        replacedemblyTempFilePath = Path.Combine(Path.Combine(tempBasePath, bittyness), String.Concat(name, ".dll"));
        if (File.Exists(replacedemblyTempFilePath))
        {
            return replacedembly.LoadFile(replacedemblyTempFilePath);
        }
        replacedemblyTempFilePath = Path.ChangeExtension(replacedemblyTempFilePath, "exe");
        if (File.Exists(replacedemblyTempFilePath))
        {
            return replacedembly.LoadFile(replacedemblyTempFilePath);
        }
        return null;
    }

19 View Source File : SHA256.cs
License : MIT License
Project Creator : albyho

public static Byte[] EncryptToByteArray(string rawString, string salt)
        {
            if (rawString == null)
            {
                throw new ArgumentNullException(nameof(rawString));
            }
            if (salt == null)
            {
                throw new ArgumentNullException(nameof(salt));
            }
            var salted = Encoding.UTF8.GetBytes(String.Concat(rawString, salt));
            System.Security.Cryptography.SHA256 hasher = new SHA256Managed();
            var hashed = hasher.ComputeHash(salted);
            return hashed;
        }

19 View Source File : Block.cs
License : MIT License
Project Creator : alexanderdna

public static string ComputeMerkleHash(Block block)
        {
            if (block.Transactions.Count == 0)
            {
                return "";
            }

            var hashes = new List<string>(block.Transactions.Count);
            for (int i = 0, c = block.Transactions.Count; i < c; ++i)
            {
                hashes.Add(block.Transactions[i].Id);
            }

            if (hashes.Count % 2 != 0) hashes.Add(hashes[^1]);

            int count = hashes.Count;
            int step = 1;
            while (count > 1)
            {
                for (int i = 0, c = hashes.Count; i < c; i += step * step)
                {
                    var h1 = hashes[i];
                    var h2 = (i + step < c) ? hashes[i + step] : h1;
                    var combined = HashUtils.SHA256(string.Concat(h1, h2));
                    hashes[i] = combined;
                }

                if (count % 2 == 0)
                    count /= 2;
                else
                    count = (count + 1) / 2;

                step *= 2;
            }

            return hashes[0];
        }

19 View Source File : USPSInternationalProvider.cs
License : MIT License
Project Creator : alexeybusygin

private void ParseResult(string response)
        {
            var doreplacedent = XDoreplacedent.Load(new StringReader(response));

            var rates = doreplacedent.Descendants("Service").GroupBy(item => (string) item.Element("SvcDescription")).Select(g => new {Name = g.Key, TotalCharges = g.Sum(x => Decimal.Parse((string) x.Element("Postage")))});

            foreach (var r in rates)
            {
                var name = Regex.Replace(r.Name, "<.*gt;", "");

                if (_service == name || _service == "ALL")
                {
                    AddRate(name, string.Concat("USPS ", name), r.TotalCharges, DateTime.Now.AddDays(30), null, USPSCurrencyCode);
                }
            }

            //check for errors
            ParseErrors(doreplacedent.Root);
        }

19 View Source File : USPSProvider.cs
License : MIT License
Project Creator : alexeybusygin

private void ParseResult(string response, IList<SpecialServices> includeSpecialServiceCodes = null)
        {
            var doreplacedent = XElement.Parse(response, LoadOptions.None);

            var rates = from item in doreplacedent.Descendants("Postage")
                group item by (string) item.Element("MailService")
                into g
                select new {Name = g.Key,
                            TotalCharges = g.Sum(x => decimal.Parse((string) x.Element("Rate"))),
                            TotalCommercialCharges = g.Sum(x => decimal.Parse((string) x.Element("CommercialRate") ?? "0")),
                            DeliveryDate = g.Select(x => (string) x.Element("CommitmentDate")).FirstOrDefault(),
                            SpecialServices = g.Select(x => x.Element("SpecialServices")).FirstOrDefault() };

            foreach (var r in rates)
            {
                //string name = r.Name.Replace(REMOVE_FROM_RATE_NAME, string.Empty);
                var name = Regex.Replace(r.Name, "<.*>", "");
                var additionalCharges = 0.0m;

                if (includeSpecialServiceCodes != null && includeSpecialServiceCodes.Count > 0 && r.SpecialServices != null)
                {
                    var specialServices = r.SpecialServices.XPathSelectElements("SpecialService").ToList();
                    if (specialServices.Count > 0)
                    {
                        foreach (var specialService in specialServices)
                        {
                            var serviceId = (int)specialService.Element("ServiceID");
                            var price = decimal.Parse((string) specialService.Element("Price"));

                            if (includeSpecialServiceCodes.Contains((SpecialServices)serviceId))
                                additionalCharges += price;
                        }
                    }
                }

                var isNegotiatedRate = _service == Services.Online && r.TotalCommercialCharges > 0;
                var totalCharges = isNegotiatedRate ? r.TotalCommercialCharges : r.TotalCharges;

                if (r.DeliveryDate != null && DateTime.TryParse(r.DeliveryDate, out DateTime deliveryDate))
                {
                    var rateOptions = new RateOptions()
                    {
                        SaturdayDelivery = Shipment.Options.SaturdayDelivery && deliveryDate.DayOfWeek == DayOfWeek.Saturday
                    };
                    AddRate(name, string.Concat("USPS ", name), totalCharges + additionalCharges, deliveryDate, rateOptions, USPSCurrencyCode);
                }
                else
                {
                    AddRate(name, string.Concat("USPS ", name), totalCharges + additionalCharges, DateTime.Now.AddDays(30), null, USPSCurrencyCode);
                }
            }

            //check for errors
            ParseErrors(doreplacedent);
        }

19 View Source File : AliyunSDKUtils.cs
License : MIT License
Project Creator : aliyunmq

internal static string UrlEncode(int rfcNumber, string data, bool path)
        {
            StringBuilder encoded = new StringBuilder(data.Length * 2);
            string validUrlCharacters;
            if (!RFCEncodingSchemes.TryGetValue(rfcNumber, out validUrlCharacters))
                validUrlCharacters = ValidUrlCharacters;

            string unreservedChars = String.Concat(validUrlCharacters, (path ? ValidPathCharacters : ""));

            foreach (char symbol in Encoding.UTF8.GetBytes(data))
            {
                if (unreservedChars.IndexOf(symbol) != -1)
                {
                    encoded.Append(symbol);
                }
                else
                {
                    encoded.Append("%").Append(string.Format(CultureInfo.InvariantCulture, "{0:X2}", (int)symbol));
                }
            }

            return encoded.ToString();
        }

19 View Source File : MD5Encrypt.cs
License : MIT License
Project Creator : alonsoalon

public static string Encrypt32(string preplacedword = "")
        {
            if (preplacedword.IsNull())
                return null;

            using (var md5 = MD5.Create())
            {
                string pwd = string.Empty;
                byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(preplacedword));
                foreach (var item in s)
                {
                    pwd = string.Concat(pwd, item.ToString("X"));
                }
                return pwd;
            }
        }

19 View Source File : DefaultRedisProvider.cs
License : MIT License
Project Creator : AlphaYu

private string HandlePrefix(string prefix)
        {
            // Forbid
            if (prefix.Equals("*"))
                throw new ArgumentException("the prefix should not equal to *");

            // Don't start with *
            prefix = new System.Text.RegularExpressions.Regex("^\\*+").Replace(prefix, "");

            // End with *
            if (!prefix.EndsWith("*", StringComparison.OrdinalIgnoreCase))
                prefix = string.Concat(prefix, "*");

            return prefix;
        }

19 View Source File : AuthenticationService.cs
License : MIT License
Project Creator : Amitpnk

private async Task<string> SendVerificationEmail(ApplicationUser user, string origin)
        {
            var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
            code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
            var route = "api/account/confirm-email/";
            var _enpointUri = new Uri(string.Concat($"{origin}/", route));
            var verificationUri = QueryHelpers.AddQueryString(_enpointUri.ToString(), "userId", user.Id);
            verificationUri = QueryHelpers.AddQueryString(verificationUri, "code", code);
            //Email Service Call Here
            return verificationUri;
        }

19 View Source File : AuthenticationService.cs
License : MIT License
Project Creator : Amitpnk

public async Task ForgotPreplacedword(ForgotPreplacedwordRequest model, string origin)
        {
            var account = await _userManager.FindByEmailAsync(model.Email);

            // always return ok response to prevent email enumeration
            if (account == null) return;

            var code = await _userManager.GeneratePreplacedwordResetTokenAsync(account);
            var route = "api/account/reset-preplacedword/";
            var _enpointUri = new Uri(string.Concat($"{origin}/", route));
            var emailRequest = new MailRequest()
            {
                Body = $"You reset token is - {code}",
                ToEmail = model.Email,
                Subject = "Reset Preplacedword",
            };
            await _emailService.SendEmailAsync(emailRequest);
        }

19 View Source File : NgWizardHelper.cs
License : MIT License
Project Creator : andfomin

internal static string RunNgNew(string projectDirectory, string projectName, bool addRouting, bool isNgFound)
        {
            var path = projectDirectory.EndsWith("\\") ? projectDirectory : string.Concat(projectDirectory, "\\");
            var directoryInfo = Directory.GetParent(path);
            var parentDirectory = directoryInfo.Parent.FullName;
            var directory = directoryInfo.Name;

            var routingOption = addRouting ? " --routing" : "";

            // CMD writes errors to the StandardError stream. NG writes errors to StandardOutput. 
            // To read both the streams is possible but needs extra effots to avoid a thread deadlock.
            // If NG was not found, we display the Command Window to the user to watch the errors.
            var cmdArguments = $"/c ng new {projectName} --directory {directory}{routingOption} --skip-git --skip-install"
                + (isNgFound ? "" : " & timeout /t 10");

            return RunCmd(cmdArguments, parentDirectory, isNgFound, isNgFound);
        }

19 View Source File : CsvOutputFormatter.cs
License : GNU General Public License v3.0
Project Creator : andysal

private void writeStream(Type type, object value, Stream stream)
        {
            Type itemType = type.GetGenericArguments()[0];

            StringWriter _stringWriter = new StringWriter();

            _stringWriter.WriteLine(
                string.Join<string>(
                    ";", itemType.GetProperties().Select(x => x.Name)
                )
            );

            foreach (var obj in (IEnumerable<object>)value)
            {

                var vals = obj.GetType().GetProperties().Select(
                    pi => new {
                        Value = pi.GetValue(obj, null)
                    }
                );

                string _valueLine = string.Empty;

                foreach (var val in vals)
                {

                    if (val.Value != null)
                    {

                        var _val = val.Value.ToString();

                        //Check if the value contans a comma and place it in quotes if so
                        if (_val.Contains(","))
                            _val = string.Concat("\"", _val, "\"");

                        //Replace any \r or \n special characters from a new line with a space
                        if (_val.Contains("\r"))
                            _val = _val.Replace("\r", " ");
                        if (_val.Contains("\n"))
                            _val = _val.Replace("\n", " ");

                        _valueLine = string.Concat(_valueLine, _val, ";");

                    }
                    else
                    {

                        _valueLine = string.Concat(string.Empty, ";");
                    }
                }

                _stringWriter.WriteLine(_valueLine.TrimEnd(';'));
            }

            var streamWriter = new StreamWriter(stream);
            streamWriter.Write(_stringWriter.ToString());
            streamWriter.Flush();
        }

19 View Source File : BaseEngine.cs
License : MIT License
Project Creator : angelsix

protected void ReplaceTag(ref string fileContents, Match match, string newContent, bool removeNewline = true)
        {
            // If we want to remove a suffixed newline...
            if (removeNewline)
            {
                // Remove carriage return
                if ((fileContents.Length > match.Index + match.Length) &&
                    fileContents[match.Index + match.Length] == '\r')
                    fileContents = string.Concat(fileContents.Substring(0, match.Index + match.Length), fileContents.Substring(match.Index + match.Length + 1));

                // Return newline
                if ((fileContents.Length > match.Index + match.Length) &&
                    fileContents[match.Index + match.Length] == '\n')
                    fileContents = string.Concat(fileContents.Substring(0, match.Index + match.Length), fileContents.Substring(match.Index + match.Length + 1));
            }

            // If the match is at the start, replace it
            if (match.Index == 0)
                fileContents = newContent + fileContents.Substring(match.Length);
            // Otherwise do an inner replace
            else
                fileContents = string.Concat(fileContents.Substring(0, match.Index), newContent, fileContents.Substring(match.Index + match.Length));
        }

19 View Source File : MD5Hepler.cs
License : Apache License 2.0
Project Creator : anjoy8

public static string MD5Encrypt32(string preplacedword = "")
        {
            string pwd = string.Empty;
            try
            {
                if (!string.IsNullOrEmpty(preplacedword) && !string.IsNullOrWhiteSpace(preplacedword))
                {
                    MD5 md5 = MD5.Create(); //实例化一个md5对像
                    // 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择 
                    byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(preplacedword));
                    // 通过使用循环,将字节类型的数组转换为字符串,此字符串是常规字符格式化所得
                    foreach (var item in s)
                    {
                        // 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母,如果使用大写(X)则格式后的字符是大写字符 
                        pwd = string.Concat(pwd, item.ToString("X2"));
                    }
                }
            }
            catch
            {
                throw new Exception($"错误的 preplacedword 字符串:【{preplacedword}】");
            }
            return pwd;
        }

19 View Source File : MD5Hepler.cs
License : Apache License 2.0
Project Creator : anjoy8

public static string MD5Encrypt32(string preplacedword = "")
        {
            string pwd = string.Empty;
            try
            {
                if (!string.IsNullOrEmpty(preplacedword) && !string.IsNullOrWhiteSpace(preplacedword))
                {
                    MD5 md5 = MD5.Create(); //实例化一个md5对像
                    // 加密后是一个字节类型的数组,这里要注意编码UTF8/Unicode等的选择 
                    byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(preplacedword));
                    // 通过使用循环,将字节类型的数组转换为字符串,此字符串是常规字符格式化所得
                    foreach (var item in s)
                    {
                        // 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母,如果使用大写(X)则格式后的字符是大写字符 
                        pwd = string.Concat(pwd, item.ToString("X"));
                    }
                }
            }
            catch
            {
                throw new Exception($"错误的 preplacedword 字符串:【{preplacedword}】");
            }
            return pwd;
        }

19 View Source File : OCR.razor.cs
License : MIT License
Project Creator : AnkitSharma-007

protected async Task ViewImage(InputFileChangeEventArgs e)
        {
            if (e.File.Size > MaxFileSize)
            {
                status = $"The file size is {e.File.Size} bytes, this is more than the allowed limit of {MaxFileSize} bytes.";
                return;
            }
            else if (!e.File.ContentType.Contains("image"))
            {
                status = "Please uplaod a valid image file";
                return;
            }
            else
            {
                using var reader = new StreamReader(e.File.OpenReadStream(MaxFileSize));
                var format = "image/jpeg";
                var imageFile = await e.File.RequestImageFileAsync(format, 640, 480);

                using var fileStream = imageFile.OpenReadStream(MaxFileSize);
                using var memoryStream = new MemoryStream();
                await fileStream.CopyToAsync(memoryStream);
                imageFileBytes = memoryStream.ToArray();
                imagePreview = string.Concat("data:image/png;base64,", Convert.ToBase64String(memoryStream.ToArray()));

                status = DefaultStatus;
            }
        }

19 View Source File : RecastInterface.cs
License : MIT License
Project Creator : AnotherEnd15

public static bool FindPath(int id, Vector3 spos, Vector3 epos)
        {
            {
                float[] fixPos = fixposition(id, spos);
                if (fixPos != null)
                {
                    spos.y = fixPos[1];
                }
                else
                {
                    Console.WriteLine(string.Concat("错误:", ($"Recast寻路 FindPath Error:- 起点非法 - spos:{spos} - MapId:{id}")));
                }

                SPos = spos;
            }
            {
                float[] fixPos = fixposition(id, epos);
                if (fixPos != null)
                {
                    epos.y = fixPos[1];
                }
                else
                {
                    Console.WriteLine(string.Concat("错误:",($"Recast寻路 FindPath Error:- 终点非法 - epos:{epos} - MapId:{id}")));
                }

                EPos = epos;
            }
            dtStatus status = (dtStatus) recast_findpath(id, new[] { -spos.x, spos.y, spos.z }, new[] { -epos.x, epos.y, epos.z });
            if (dtStatusFailed(status))
            {
                dtStatus statusDetail = status & dtStatus.DT_STATUS_DETAIL_MASK;
                string _strLastError = $"Recast寻路 FindPath Error:寻路失败!错误码<" + statusDetail + $"> - MapId:{id}";
                if (statusDetail == dtStatus.DT_COORD_INVALID)
                {
                    _strLastError += " - 坐标非法!From<" + spos + "> To<" + epos + $"> - MapId:{id}";
                }
                Console.WriteLine(string.Concat("错误:",_strLastError));
                return false;
            }
            else if (dtStatusInProgress(status))
            {
                string _strLastError = $"Recast寻路 Error:寻路尚未结束!- MapId:{id}";
                Console.WriteLine(string.Concat("错误:",_strLastError));
                return false;
            }

            return true;
        }

19 View Source File : RecastInterface.cs
License : MIT License
Project Creator : AnotherEnd15

public static bool Raycast(int id, Vector3 spos, Vector3 epos)
        {
            dtStatus status = (dtStatus) recast_raycast(id, new float[] { -spos.x, spos.y, spos.z }, new float[] { -epos.x, epos.y, epos.z });
            if (dtStatusFailed(status))
            {
                dtStatus statusDetail = status & dtStatus.DT_STATUS_DETAIL_MASK;
                string _strLastError = "Recast寻路 Raycast Error:寻路失败!错误码<" + statusDetail + $"> - MapId:{id}";
                if (statusDetail == dtStatus.DT_COORD_INVALID)
                {
                    _strLastError += " - 坐标非法!From<" + spos + "> To<" + epos + $"> - MapId:{id}";
                }
                Console.WriteLine(string.Concat("错误:",_strLastError));
                return false;
            }
            else if (dtStatusInProgress(status))
            {
                string _strLastError = $"Recast寻路 Error:寻路尚未结束! - MapId:{id}";
                Console.WriteLine(string.Concat("错误:",_strLastError));
                return false;
            }

            return true;
        }

19 View Source File : RecastInterface.cs
License : MIT License
Project Creator : AnotherEnd15

public static float[] getHitPosition(int id)
        {
            unsafe
            {
                try
                {
                    IntPtr hitPos = recast_gethitposition(id);
                    float[] arrHitPos = new float[3];
                    if (hitPos.ToPointer() != null)
                    {
                        Marshal.Copy(hitPos, arrHitPos, 0, 3);
                        arrHitPos[0] = -arrHitPos[0];
                        return arrHitPos;
                    }
                    else
                    {
                        return null;
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(string.Concat("错误:",($"RecstInterface getHitPosition Exception! - {e}")));
                    return null;
                }
            }
        }

19 View Source File : RecastInterface.cs
License : MIT License
Project Creator : AnotherEnd15

public static float[] fixposition(int id, Vector3 pos)
        {
            unsafe
            {
                try
                {
                    IntPtr fixPos = recast_getfixposition(id, new float[] { -pos.x, pos.y, pos.z }); // (pos.y+1)抬高一点计算
                    float[] arrFixPos = new float[3];
                    if (fixPos.ToPointer() != null)
                    {
                        Marshal.Copy(fixPos, arrFixPos, 0, 3);
                        arrFixPos[0] = -arrFixPos[0];
                        return arrFixPos;
                    }
                    else
                    {
                        return null;
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(string.Concat("错误:",($"RecstInterface fixposition Exception! - {e}")));
                    return null;
                }
            }
        }

19 View Source File : RecastInterface.cs
License : MIT License
Project Creator : AnotherEnd15

public static int[] GetPathPoly(int id, out int polyCount)
        {
            unsafe
            {
                try
                {
                    // https://bbs.csdn.net/topics/392618929?list=676344
                    polyCount = recast_getcountpoly(id);
                    IntPtr polys = recast_getpathpoly(id);
                    if (polys.ToPointer() != null)
                    {
                        int[] arrPolys = new int[polyCount];
                        Marshal.Copy(polys, arrPolys, 0, polyCount);
                        return arrPolys;
                    }

                    return null;
                }
                catch (Exception e)
                {
                    polyCount = 0;
                    Console.WriteLine(string.Concat("错误:",($"RecstInterface fixposition Exception! - {e}")));
                    return null;
                }
            }
        }

19 View Source File : RecastInterface.cs
License : MIT License
Project Creator : AnotherEnd15

public static float[] GetPathSmooth(int id, out int smoothCount)
        {
            unsafe
            {
                try
                {
                    int polyCount = recast_getcountpoly(id);
                    smoothCount = recast_getcountsmooth(id);
                    IntPtr smooths = recast_getpathsmooth(id);
                    float[] arrSmooths = new float[smoothCount * 3];
                    Marshal.Copy(smooths, arrSmooths, 0, smoothCount * 3);
                    for (int i = 0; i < smoothCount; ++i)
                    {
                        arrSmooths[i * 3] = -arrSmooths[i * 3];
                    }

                    return arrSmooths;
                }
                catch (Exception e)
                {
                    smoothCount = 0;
                    Console.WriteLine(string.Concat("错误:",($"RecstInterface fixposition Exception! - {e}")));
                    return null;
                }
            }
        }

19 View Source File : Dbg.cs
License : Apache License 2.0
Project Creator : AnthonyLloyd

public static void Output(Action<string> output)
    {
        foreach (var s in info)
            output(string.Concat("[Dbg] ", s));
        int maxLength = 0, total = 0;
        foreach (var kv in counts)
        {
            total += kv.Value;
            if (kv.Key.Length > maxLength) maxLength = kv.Key.Length;
        }
        foreach (var kc in counts.OrderByDescending(i => i.Value))
        {
            var percent = ((float)kc.Value / total).ToString("0.0%").PadLeft(7);
            output(string.Concat("Count: ", kc.Key.PadRight(maxLength), percent, " ", kc.Value));
        }
        maxLength = 0;
        int maxPercent = 0, maxTime = 0, maxCount = 0;
        foreach (var kv in times)
        {
            if (kv.Key.Length > maxLength) maxLength = kv.Key.Length;
            if ((kv.Value.Item1 * 1000L / Stopwatch.Frequency).ToString("#,0").Length > maxTime)
                maxTime = (kv.Value.Item1 * 1000L / Stopwatch.Frequency).ToString("#,0").Length;
            if (((float)kv.Value.Item1 / times.Value(0).Item1).ToString("0.0%").Length > maxPercent)
                maxPercent = ((float)kv.Value.Item1 / times.Value(0).Item1).ToString("0.0%").Length;
            if (kv.Value.Item2.ToString().Length > maxCount)
                maxCount = kv.Value.Item2.ToString().Length;
        }
        foreach (var kc in times)
        {
            var time = (kc.Value.Item1 * 1000L / Stopwatch.Frequency).ToString("#,0").PadLeft(maxTime + 1);
            var percent = ((float)kc.Value.Item1 / times.Value(0).Item1).ToString("0.0%").PadLeft(maxPercent + 1);
            var count = kc.Value.Item2.ToString().PadLeft(maxCount + 1);
            output(string.Concat("Time: ", kc.Key.PadRight(maxLength), time, "ms", percent, count));
        }
        Clear();
    }

19 View Source File : RecordingDestinationService.cs
License : MIT License
Project Creator : AntonyCorbett

private static string GetTempRecordingFile()
        {
            var folder = FileUtils.GetTempRecordingFolder();
            var file = string.Concat(Guid.NewGuid().ToString("N"), ".mp3");
            return Path.Combine(folder, file);
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : anupavanm

public string GetDescription()
  {
    return String.Concat(mCoffee.GetDescription(), ", milk");
  }

19 View Source File : Program.cs
License : MIT License
Project Creator : anupavanm

public string GetDescription()
  {
    return String.Concat(mCoffee.GetDescription(), ", vanilla");
  }

19 View Source File : Program.cs
License : MIT License
Project Creator : anupavanm

public string GetDescription()
  {
    return String.Concat(mCoffee.GetDescription(), ", whip");
  }

19 View Source File : ProductManager.cs
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools

internal static void ApplyPatches(ProductInfo p, ApexSettings settings)
        {
            var client = new WebClient
            {
                BaseAddress = EnsureTrailingSlash(settings.updateCheckBaseUrl)
            };

            client.Headers.Add("Accept", "application/xml");
            var request = string.Format("api/Products/GetAvailablePatches?productName={0}&version={1}", p.generalName, p.installedVersion);
            var patchList = client.DownloadString(request);

            var doc = XDoreplacedent.Parse(patchList);
            var ns = XNamespace.Get(doc.Root.Attribute("xmlns").Value);
            var patchFiles = from s in XDoreplacedent.Parse(patchList).Root.Elements(ns + "string")
                             select s.Value;

            foreach (var patchFile in patchFiles)
            {
                var patchPath = string.Concat(settings.dataFolder, "/", patchFile);
                var url = string.Concat("content/patches/", patchFile);
                client.DownloadFile(url, patchPath);

                replacedetDatabase.ImportPackage(patchPath, false);
            }
        }

19 View Source File : EditorUtilities.cs
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools

public static string Elipsify(this string s, int maxLength)
        {
            if (s.Length <= maxLength || s.Length <= 3)
            {
                return s;
            }

            return string.Concat(s.Substring(0, maxLength - 3), "...");
        }

19 View Source File : GridPortalComponentEditor.cs
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools

private void ShowPortalCommands(GridPortalComponent p)
        {
            EditorGUILayout.Separator();
            if (_inPortalMode)
            {
                var msg = "Using the Left mouse button, click and drag to place Portal One.\n\nUsing the Left mouse button and Shift, click and drag to place Portal Two.\n\nHolding Control or Command with either option will expand the portal along the nearest perimeter.";
                if (p.type == PortalType.Connector)
                {
                    msg = string.Concat(msg, "\n\nTo easily place a connector portal between adjacent grids, simply drag the rectangle over the two grids to connect.");
                }

                EditorGUILayout.HelpBox(msg, MessageType.Info);
                EditorGUILayout.Separator();

                if (GUILayout.Button("Done (Esc)"))
                {
                    ToggleEditMode(false);
                }
            }
            else if (GUILayout.Button("Edit Portals"))
            {
                ToggleEditMode(true);

                if (SceneView.sceneViews.Count > 0)
                {
                    ((SceneView)SceneView.sceneViews[0]).Focus();
                }
            }
        }

19 View Source File : HealthCheckResult.cs
License : Apache License 2.0
Project Creator : AppMetrics

private static string FormatStackTrace(Exception exception, int indent = 2)
        {
            var builder = new StringBuilder();

            var aggregate = exception as AggregateException;
            var pad = new string(' ', indent * 2);
            if (aggregate != null)
            {
                builder.AppendFormat("{0}{1}: {2}" + Environment.NewLine, pad, exception.GetType().Name, exception.Message);

                foreach (var inner in aggregate.InnerExceptions)
                {
                    builder.AppendLine(FormatStackTrace(inner, indent + 2));
                }
            }
            else
            {
                builder.AppendFormat("{0}{1}: {2}" + Environment.NewLine, pad, exception.GetType().Name, exception.Message);

                if (exception.StackTrace != null)
                {
                    var stackLines = exception.StackTrace.Split('\n')
                                              .Where(l => !string.IsNullOrWhiteSpace(l))
                                              .Select(l => string.Concat(pad, l.Trim()));

                    builder.AppendLine(string.Join(Environment.NewLine, stackLines));
                }
                else
                {
                    builder.AppendLine(string.Concat(pad, "[No Stacktrace]"));
                }

                if (exception.InnerException != null)
                {
                    builder.AppendLine(FormatStackTrace(exception.InnerException, indent + 2));
                }
            }

            return builder.ToString();
        }

19 View Source File : MssqlCommandFactory_2008.cs
License : MIT License
Project Creator : aquilahkj

public override CommandData CreateBaseInsertCommand(DataTableEnreplacedyMapping mapping, object enreplacedy, bool refresh,
            bool updateIdenreplacedy, CreateSqlState state)
        {
            string cacheKey = null;
            var idenreplacedy = updateIdenreplacedy && mapping.HasIdenreplacedy;
            if (state.Seed == 0 && !state.UseDirectNull)
            {
                cacheKey = CommandCache.CreateKey(mapping, state);
                if (idenreplacedy)
                {
                    cacheKey = string.Concat(cacheKey, "|id");
                }

                if (_baseInsertCache.TryGetCommand(cacheKey, out var cache))
                {
                    var command1 = new CommandData(cache) {IdenreplacedySql = idenreplacedy};
                    foreach (var field in mapping.CreateFieldList)
                    {
                        var value = field.ToInsert(enreplacedy, refresh);
                        state.AddDataParameter(this, value, field.DBType, field.ObjectType);
                    }

                    return command1;
                }
            }

            IList<DataFieldMapping> fields = mapping.CreateFieldList;
            var insertLen = fields.Count;
            if (insertLen == 0)
            {
                throw new LightDataException(string.Format(SR.NotContainNonIdenreplacedyKeyFields, mapping.ObjectType));
            }

            var insertList = new string[insertLen];
            var valuesList = new string[insertLen];
            for (var i = 0; i < insertLen; i++)
            {
                var field = fields[i];
                var value = field.ToInsert(enreplacedy, refresh);
                insertList[i] = CreateDataFieldSql(field.Name);
                valuesList[i] = state.AddDataParameter(this, value, field.DBType, field.ObjectType);
            }

            var insert = string.Join(",", insertList);
            var values = string.Join(",", valuesList);
            var sql = idenreplacedy
                ? $"insert into {CreateDataTableMappingSql(mapping, state)}({insert}) output inserted.{CreateDataFieldSql(mapping.IdenreplacedyField.Name)} values({values})"
                : $"insert into {CreateDataTableMappingSql(mapping, state)}({insert})values({values})";

            var command = new CommandData(sql) {IdenreplacedySql = idenreplacedy};
            if (cacheKey != null)
            {
                _baseInsertCache.SetCommand(cacheKey, command.CommandText);
            }

            return command;
        }

19 View Source File : PhotonEditor.cs
License : MIT License
Project Creator : ArcturusZhang

protected virtual void UiSetupApp()
        {
            GUI.skin.label.wordWrap = true;
            if (!this.isSetupWizard)
            {
                GUILayout.BeginHorizontal();
                GUILayout.FlexibleSpace();
                if (GUILayout.Button(CurrentLang.MainMenuButton, GUILayout.ExpandWidth(false)))
                {
                    this.photonSetupState = PhotonSetupStates.MainUi;
                }

                GUILayout.EndHorizontal();
            }


            // setup header
            this.UireplacedleBox(CurrentLang.SetupWizardreplacedle, BackgroundImage);

            // setup info text
            GUI.skin.label.richText = true;
            GUILayout.Label(CurrentLang.SetupWizardInfo);

            // input of appid or mail
            EditorGUILayout.Separator();
            GUILayout.Label(CurrentLang.EmailOrAppIdLabel);
            this.mailOrAppId = EditorGUILayout.TextField(this.mailOrAppId); 
            if (!string.IsNullOrEmpty(this.mailOrAppId))
            {
                this.mailOrAppId = this.mailOrAppId.Trim(); // note: we trim all input
                if (PhotonEditor.IsValidEmail(this.mailOrAppId))
                {
                    // this should be a mail address
                    this.minimumInput = true;
                    this.useMail = this.minimumInput;
                    this.useAppId = false;
                }
                else if (ServerSettings.IsAppId(this.mailOrAppId))
                {
                    // this should be an appId
                    this.minimumInput = true;
                    this.useMail = false;
                    this.useAppId = this.minimumInput;
                }
                else
                {
                    this.minimumInput = false;
                    this.useMail = false;
                    this.useAppId = false;
                }
            }
            else
            {
                this.minimumInput = false;
                this.useMail = false;
                this.useAppId = false;
            }

            // button to skip setup
            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            if (GUILayout.Button(CurrentLang.SkipButton, GUILayout.Width(100)))
            {
                this.photonSetupState = PhotonSetupStates.GoEditPhotonServerSettings;
                this.useSkip = true;
                this.useMail = false;
                this.useAppId = false;
            }

            // SETUP button
            EditorGUI.BeginDisabledGroup(!this.minimumInput);
            if (GUILayout.Button(CurrentLang.SetupButton, GUILayout.Width(100)))
            {
                this.useSkip = false;
                GUIUtility.keyboardControl = 0;
                if (this.useMail)
                {
                    this.RegisterWithEmail(this.mailOrAppId); // sets state
                }
                if (this.useAppId)
                {
                    this.photonSetupState = PhotonSetupStates.GoEditPhotonServerSettings;
                    Undo.RecordObject(PhotonNetwork.PhotonServerSettings, "Update PhotonServerSettings for PUN");
                    PhotonNetwork.PhotonServerSettings.UseCloud(this.mailOrAppId);
                    PhotonEditor.SaveSettings();
                }
            }
            EditorGUI.EndDisabledGroup();
            GUILayout.FlexibleSpace();
            GUILayout.EndHorizontal();


            // existing account needs to fetch AppId online
            if (this.photonSetupState == PhotonSetupStates.EmailAlreadyRegistered)
            {
                // button to open dashboard and get the AppId
                GUILayout.Space(15);
                GUILayout.Label(CurrentLang.AlreadyRegisteredInfo);


                GUILayout.BeginHorizontal();
                GUILayout.FlexibleSpace();
                if (GUILayout.Button(new GUIContent(CurrentLang.OpenCloudDashboardText, CurrentLang.OpenCloudDashboardTooltip), GUILayout.Width(205)))
                {
                    Application.OpenURL(string.Concat(UrlCloudDashboard, Uri.EscapeUriString(this.mailOrAppId)));
                    this.mailOrAppId = string.Empty;
                }
                GUILayout.FlexibleSpace();
                GUILayout.EndHorizontal();
            }


            if (this.photonSetupState == PhotonSetupStates.GoEditPhotonServerSettings)
            {
                if (!this.highlightedSettings)
                {
                    this.highlightedSettings = true;
                    HighlightSettings();
                }

                GUILayout.Space(15);
                if (this.useSkip)
                {
                    GUILayout.Label(CurrentLang.SkipRegistrationInfo);
                }
                else if (this.useMail)
                {
                    GUILayout.Label(CurrentLang.RegisteredNewAccountInfo);
                }
                else if (this.useAppId)
                {
                    GUILayout.Label(CurrentLang.AppliedToSettingsInfo);
                }


                // setup-complete info
                GUILayout.Space(15);
                GUILayout.Label(CurrentLang.SetupCompleteInfo);


                // close window (done)
                GUILayout.BeginHorizontal();
                GUILayout.FlexibleSpace();
                if (GUILayout.Button(CurrentLang.CloseWindowButton, GUILayout.Width(205)))
                {
                    this.close = true;
                }
                GUILayout.FlexibleSpace();
                GUILayout.EndHorizontal();
            }
            GUI.skin.label.richText = false;
        }

19 View Source File : DefaultTagHelperCompletionService.cs
License : Apache License 2.0
Project Creator : aspnet

private bool TryResolveAttributeInsertionSnippet(
            string text,
            IEnumerable<BoundAttributeDescriptor> boundAttributes,
            bool indexerCompletion,
            out string snippetText)
        {
            const string BoolTypeName = "System.Boolean";

            // Boolean returning bound attribute, auto-complete to just the attribute name.
            if (indexerCompletion)
            {
                if (boundAttributes.All(boundAttribute => boundAttribute.IndexerTypeName == BoolTypeName))
                {
                    snippetText = null;
                    return false;
                }

                snippetText = string.Concat(text, "$1=\"$2\"");
                return true;
            }
            else if (boundAttributes.All(boundAttribute => boundAttribute.TypeName == BoolTypeName))
            {
                snippetText = null;
                return false;
            }

            snippetText = string.Concat(text, "=\"$1\"");
            return true;
        }

See More Examples