Here are the examples of the csharp api string.Join(string, params string[]) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
4729 Examples
19
View Source File : Program.cs
License : MIT License
Project Creator : 0ffffffffh
License : MIT License
Project Creator : 0ffffffffh
[STAThread]
static void Main(string[] args)
{
bool enableWatchdog;
Log.Init("sbmon");
Log.EnableAll();
int backendPid,memcachedPid;
var opts = Helper.ParseOptions(string.Join(" ", args));
talk = new InternalTalk(false);
backendPid = GetVal<int>(opts, "-backend", 0);
memcachedPid = GetVal<int>(opts, "-memcached", 0);
MEMCACHED_PORT = GetVal<ushort>(opts, "-mport", 0);
enableWatchdog = GetVal<bool>(opts, "-watchdog", true);
if (backendPid==0 && memcachedPid==0)
{
Log.Critical("There are no pids supplied to monitor");
return;
}
if (!InstanceCheck())
{
return;
}
if (enableWatchdog)
{
watchdog = new Watchdog();
watchdog.Start();
}
else
{
Log.Warning("Watchdog disabled.");
}
if (backendPid > 0)
new HealthMonitor(backendPid, HealthMonitor.ProcessType.BackendProcess
,RecoverPolicy.RecoverBackendAndPreplacedExistedMemcachedInstance).Start();
if (memcachedPid > 0)
new HealthMonitor(memcachedPid, HealthMonitor.ProcessType.MemcachedProcess,
RecoverPolicy.RecoverMemcachedAndPreplacedNewMemcachedInstance).Start();
Console.CancelKeyPress += Console_CancelKeyPress;
while (running)
Thread.Sleep(10);
if (enableWatchdog)
watchdog.Dispose();
talk.Stop();
mutant.Dispose();
Log._Finalize();
}
19
View Source File : FileOrganization.cs
License : Apache License 2.0
Project Creator : 0xFireball
License : Apache License 2.0
Project Creator : 0xFireball
private static string JoinPathSegments(string[] segments)
{
return "/" + string.Join("/", segments) + "/";
}
19
View Source File : RedisPartitionCaching.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
public async Task Remove(params string[] keys)
{
await Cache.RemoveAsync(string.Join("|", keys));
}
19
View Source File : Dumper.cs
License : MIT License
Project Creator : 13xforever
License : MIT License
Project Creator : 13xforever
private void CheckParamSfo(ParamSfo sfo)
{
replacedle = sfo.Items.FirstOrDefault(i => i.Key == "replacedLE")?.StringValue?.Trim(' ', '\0');
var replacedleParts = replacedle.Split(MultilineSplit, StringSplitOptions.RemoveEmptyEntries);
if (replacedleParts.Length > 1)
replacedle = string.Join(" ", replacedleParts);
ProductCode = sfo.Items.FirstOrDefault(i => i.Key == "replacedLE_ID")?.StringValue?.Trim(' ', '\0');
DiscVersion = sfo.Items.FirstOrDefault(i => i.Key == "VERSION")?.StringValue?.Trim();
Log.Info($"Game replacedle: {replacedle}");
}
19
View Source File : JScriptGenerator.cs
License : MIT License
Project Creator : 1y0n
License : MIT License
Project Creator : 1y0n
public string GenerateScript(byte[] serialized_object, string entry_clreplaced_name, string additional_script, RuntimeVersion version, bool enable_debug)
{
string[] lines = BinToBase64Lines(serialized_object);
return GetScriptHeader(version, enable_debug)
+ Global_Var.jscript_template.Replace("%SERIALIZED%", String.Join("+" + Environment.NewLine, lines)).Replace("%CLreplaced%", entry_clreplaced_name).Replace("%ADDEDSCRIPT%", additional_script);
}
19
View Source File : Core.cs
License : MIT License
Project Creator : 1y0n
License : MIT License
Project Creator : 1y0n
public static string XOR_C(string format, string raw)
{
string result = "";
string[] shellcode_array = raw.Split(',');
string[] temp = new string[shellcode_array.Length];
int j = 234;
int add = 12;
for (int i = 0; i < shellcode_array.Length; i++)
{
temp[i] = string.Format("{0:x2}", string_to_int(shellcode_array[i]) ^ 123 ^ j);
temp[i] = "0x" + temp[i].Substring(temp[i].Length - 2, 2);
j += add;
}
result = string.Join(",", temp);
//转换一下格式
if (format == "c")
{
result = result.Replace("0x", @"\x").Replace(",", "");
}
return result;
}
19
View Source File : DotNetToJScript.cs
License : MIT License
Project Creator : 1y0n
License : MIT License
Project Creator : 1y0n
static string GetEnumString(Type enum_type)
{
return String.Join(", ", Enum.GetNames(enum_type));
}
19
View Source File : VBScriptGenerator.cs
License : MIT License
Project Creator : 1y0n
License : MIT License
Project Creator : 1y0n
public string GenerateScript(byte[] serialized_object, string entry_clreplaced_name, string additional_script, RuntimeVersion version, bool enable_debug)
{
string[] lines = JScriptGenerator.BinToBase64Lines(serialized_object);
return GetScriptHeader(version, enable_debug)
+ Global_Var.vbs_template.Replace(
"%SERIALIZED%",
String.Join(Environment.NewLine + "s = s & ", lines)
).Replace(
"%CLreplaced%",
entry_clreplaced_name
).Replace(
"%ADDEDSCRIPT%",
additional_script
);
}
19
View Source File : TemplateEngin.cs
License : MIT License
Project Creator : 2881099
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 : TemplateEngin.cs
License : MIT License
Project Creator : 2881099
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 : DbSetAsync.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
async Task<int> DbContextBetchUpdatePrivAsync(EnreplacedyState[] ups, bool isLiveUpdate) {
if (ups.Any() == false) return 0;
var uplst1 = ups[ups.Length - 1];
var uplst2 = ups.Length > 1 ? ups[ups.Length - 2] : null;
if (_states.TryGetValue(uplst1.Key, out var lstval1) == false) return -999;
var lstval2 = default(EnreplacedyState);
if (uplst2 != null && _states.TryGetValue(uplst2.Key, out lstval2) == false) throw new Exception($"特别错误:更新失败,数据未被跟踪:{_fsql.GetEnreplacedyString(_enreplacedyType, uplst2.Value)}");
var cuig1 = _fsql.CompareEnreplacedyValueReturnColumns(_enreplacedyType, uplst1.Value, lstval1.Value, true);
var cuig2 = uplst2 != null ? _fsql.CompareEnreplacedyValueReturnColumns(_enreplacedyType, uplst2.Value, lstval2.Value, true) : null;
List<EnreplacedyState> data = null;
string[] cuig = null;
if (uplst2 != null && string.Compare(string.Join(",", cuig1), string.Join(",", cuig2)) != 0) {
//最后一个不保存
data = ups.ToList();
data.RemoveAt(ups.Length - 1);
cuig = cuig2;
} else if (isLiveUpdate) {
//立即保存
data = ups.ToList();
cuig = cuig1;
}
if (data?.Count > 0) {
if (cuig.Length == _table.Columns.Count)
return ups.Length == data.Count ? -998 : -997;
var updateSource = data.Select(a => a.Value).ToArray();
var update = this.OrmUpdate(null).SetSource(updateSource).IgnoreColumns(cuig);
var affrows = await update.ExecuteAffrowsAsync();
foreach (var newval in data) {
if (_states.TryGetValue(newval.Key, out var tryold))
_fsql.MapEnreplacedyValue(_enreplacedyType, newval.Value, tryold.Value);
if (newval.OldValue != null)
_fsql.MapEnreplacedyValue(_enreplacedyType, newval.Value, newval.OldValue);
}
return affrows;
}
//等待下次对比再保存
return 0;
}
19
View Source File : DbSetSync.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
int DbContextBetchUpdatePriv(EnreplacedyState[] ups, bool isLiveUpdate) {
if (ups.Any() == false) return 0;
var uplst1 = ups[ups.Length - 1];
var uplst2 = ups.Length > 1 ? ups[ups.Length - 2] : null;
if (_states.TryGetValue(uplst1.Key, out var lstval1) == false) return -999;
var lstval2 = default(EnreplacedyState);
if (uplst2 != null && _states.TryGetValue(uplst2.Key, out lstval2) == false) throw new Exception($"特别错误:更新失败,数据未被跟踪:{_fsql.GetEnreplacedyString(_enreplacedyType, uplst2.Value)}");
var cuig1 = _fsql.CompareEnreplacedyValueReturnColumns(_enreplacedyType, uplst1.Value, lstval1.Value, true);
var cuig2 = uplst2 != null ? _fsql.CompareEnreplacedyValueReturnColumns(_enreplacedyType, uplst2.Value, lstval2.Value, true) : null;
List<EnreplacedyState> data = null;
string[] cuig = null;
if (uplst2 != null && string.Compare(string.Join(",", cuig1), string.Join(",", cuig2)) != 0) {
//最后一个不保存
data = ups.ToList();
data.RemoveAt(ups.Length - 1);
cuig = cuig2;
} else if (isLiveUpdate) {
//立即保存
data = ups.ToList();
cuig = cuig1;
}
if (data?.Count > 0) {
if (cuig.Length == _table.Columns.Count)
return ups.Length == data.Count ? -998 : -997;
var updateSource = data.Select(a => a.Value).ToArray();
var update = this.OrmUpdate(null).SetSource(updateSource).IgnoreColumns(cuig);
var affrows = update.ExecuteAffrows();
foreach (var newval in data) {
if (_states.TryGetValue(newval.Key, out var tryold))
_fsql.MapEnreplacedyValue(_enreplacedyType, newval.Value, tryold.Value);
if (newval.OldValue != null)
_fsql.MapEnreplacedyValue(_enreplacedyType, newval.Value, newval.OldValue);
}
return affrows;
}
//等待下次对比再保存
return 0;
}
19
View Source File : ShareHandler.cs
License : GNU General Public License v3.0
Project Creator : 2dust
License : GNU General Public License v3.0
Project Creator : 2dust
public static string GetShareUrl(Config config, int index)
{
try
{
string url = string.Empty;
VmessItem item = config.vmess[index];
if (item.configType == (int)EConfigType.Vmess)
{
VmessQRCode vmessQRCode = new VmessQRCode
{
v = item.configVersion.ToString(),
ps = item.remarks.TrimEx(), //备注也许很长 ;
add = item.address,
port = item.port.ToString(),
id = item.id,
aid = item.alterId.ToString(),
scy = item.security,
net = item.network,
type = item.headerType,
host = item.requestHost,
path = item.path,
tls = item.streamSecurity,
sni = item.sni
};
url = Utils.ToJson(vmessQRCode);
url = Utils.Base64Encode(url);
url = string.Format("{0}{1}", Global.vmessProtocol, url);
}
else if (item.configType == (int)EConfigType.Shadowsocks)
{
string remark = string.Empty;
if (!Utils.IsNullOrEmpty(item.remarks))
{
remark = "#" + Utils.UrlEncode(item.remarks);
}
url = string.Format("{0}:{1}@{2}:{3}",
item.security,
item.id,
item.address,
item.port);
url = Utils.Base64Encode(url);
url = string.Format("{0}{1}{2}", Global.ssProtocol, url, remark);
}
else if (item.configType == (int)EConfigType.Socks)
{
string remark = string.Empty;
if (!Utils.IsNullOrEmpty(item.remarks))
{
remark = "#" + Utils.UrlEncode(item.remarks);
}
url = string.Format("{0}:{1}@{2}:{3}",
item.security,
item.id,
item.address,
item.port);
url = Utils.Base64Encode(url);
url = string.Format("{0}{1}{2}", Global.socksProtocol, url, remark);
}
else if (item.configType == (int)EConfigType.Trojan)
{
string remark = string.Empty;
if (!Utils.IsNullOrEmpty(item.remarks))
{
remark = "#" + Utils.UrlEncode(item.remarks);
}
string query = string.Empty;
if (!Utils.IsNullOrEmpty(item.sni))
{
query = string.Format("?sni={0}", Utils.UrlEncode(item.sni));
}
url = string.Format("{0}@{1}:{2}",
item.id,
GetIpv6(item.address),
item.port);
url = string.Format("{0}{1}{2}{3}", Global.trojanProtocol, url, query, remark);
}
else if (item.configType == (int)EConfigType.VLESS)
{
string remark = string.Empty;
if (!Utils.IsNullOrEmpty(item.remarks))
{
remark = "#" + Utils.UrlEncode(item.remarks);
}
var dicQuery = new Dictionary<string, string>();
if (!Utils.IsNullOrEmpty(item.flow))
{
dicQuery.Add("flow", item.flow);
}
if (!Utils.IsNullOrEmpty(item.security))
{
dicQuery.Add("encryption", item.security);
}
else
{
dicQuery.Add("encryption", "none");
}
if (!Utils.IsNullOrEmpty(item.streamSecurity))
{
dicQuery.Add("security", item.streamSecurity);
}
else
{
dicQuery.Add("security", "none");
}
if (!Utils.IsNullOrEmpty(item.sni))
{
dicQuery.Add("sni", item.sni);
}
if (!Utils.IsNullOrEmpty(item.network))
{
dicQuery.Add("type", item.network);
}
else
{
dicQuery.Add("type", "tcp");
}
switch (item.network)
{
case "tcp":
if (!Utils.IsNullOrEmpty(item.headerType))
{
dicQuery.Add("headerType", item.headerType);
}
else
{
dicQuery.Add("headerType", "none");
}
if (!Utils.IsNullOrEmpty(item.requestHost))
{
dicQuery.Add("host", Utils.UrlEncode(item.requestHost));
}
break;
case "kcp":
if (!Utils.IsNullOrEmpty(item.headerType))
{
dicQuery.Add("headerType", item.headerType);
}
else
{
dicQuery.Add("headerType", "none");
}
if (!Utils.IsNullOrEmpty(item.path))
{
dicQuery.Add("seed", Utils.UrlEncode(item.path));
}
break;
case "ws":
if (!Utils.IsNullOrEmpty(item.requestHost))
{
dicQuery.Add("host", Utils.UrlEncode(item.requestHost));
}
if (!Utils.IsNullOrEmpty(item.path))
{
dicQuery.Add("path", Utils.UrlEncode(item.path));
}
break;
case "http":
case "h2":
dicQuery["type"] = "http";
if (!Utils.IsNullOrEmpty(item.requestHost))
{
dicQuery.Add("host", Utils.UrlEncode(item.requestHost));
}
if (!Utils.IsNullOrEmpty(item.path))
{
dicQuery.Add("path", Utils.UrlEncode(item.path));
}
break;
case "quic":
if (!Utils.IsNullOrEmpty(item.headerType))
{
dicQuery.Add("headerType", item.headerType);
}
else
{
dicQuery.Add("headerType", "none");
}
dicQuery.Add("quicSecurity", Utils.UrlEncode(item.requestHost));
dicQuery.Add("key", Utils.UrlEncode(item.path));
break;
case "grpc":
if (!Utils.IsNullOrEmpty(item.path))
{
dicQuery.Add("serviceName", Utils.UrlEncode(item.path));
if (item.headerType == Global.GrpcgunMode || item.headerType == Global.GrpcmultiMode)
{
dicQuery.Add("mode", Utils.UrlEncode(item.headerType));
}
}
break;
}
string query = "?" + string.Join("&", dicQuery.Select(x => x.Key + "=" + x.Value).ToArray());
url = string.Format("{0}@{1}:{2}",
item.id,
GetIpv6(item.address),
item.port);
url = string.Format("{0}{1}{2}{3}", Global.vlessProtocol, url, query, remark);
}
else
{
}
return url;
}
catch
{
return "";
}
}
19
View Source File : Utils.cs
License : GNU General Public License v3.0
Project Creator : 2dust
License : GNU General Public License v3.0
Project Creator : 2dust
public static string List2String(List<string> lst, bool wrap = false)
{
try
{
if (wrap)
{
return string.Join("," + Environment.NewLine, lst.ToArray());
}
else
{
return string.Join(",", lst.ToArray());
}
}
catch (Exception ex)
{
SaveLog(ex.Message, ex);
return string.Empty;
}
}
19
View Source File : Machine.cs
License : MIT License
Project Creator : 3RD-Dimension
License : MIT License
Project Creator : 3RD-Dimension
private void ParseStatus(string line)
{
MatchCollection statusMatch = StatusEx.Matches(line);
if (statusMatch.Count == 0)
{
NonFatalException.Invoke(string.Format("Received Bad Status: '{0}'", line));
return;
}
bool posUpdate = false;
bool overrideUpdate = false;
bool pinStateUpdate = false;
bool resetPins = true;
foreach (Match m in statusMatch)
{
if (m.Index == 1)
{
Status = m.Groups[1].Value;
continue;
}
if (m.Groups[1].Value == "Ov")
{
try
{
string[] parts = m.Groups[2].Value.Split(',');
FeedOverride = int.Parse(parts[0]);
RapidOverride = int.Parse(parts[1]);
SpindleOverride = int.Parse(parts[2]);
overrideUpdate = true;
}
catch { NonFatalException.Invoke(string.Format("Received Bad Status: '{0}'", line)); }
}
else if (m.Groups[1].Value == "WCO")
{
try
{
string OffsetString = m.Groups[2].Value;
if (Properties.Settings.Default.IgnoreAdditionalAxes)
{
string[] parts = OffsetString.Split(',');
if (parts.Length > 3)
{
Array.Resize(ref parts, 3);
OffsetString = string.Join(",", parts);
}
}
WorkOffset = Vector3.Parse(OffsetString);
posUpdate = true;
}
catch { NonFatalException.Invoke(string.Format("Received Bad Status: '{0}'", line)); }
}
else if (SyncBuffer && m.Groups[1].Value == "Bf")
{
try
{
int availableBytes = int.Parse(m.Groups[2].Value.Split(',')[1]);
int used = Properties.Settings.Default.ControllerBufferSize - availableBytes;
if (used < 0)
used = 0;
BufferState = used;
RaiseEvent(Info, $"Buffer State Synced ({availableBytes} bytes free)");
}
catch { NonFatalException.Invoke(string.Format("Received Bad Status: '{0}'", line)); }
}
else if (m.Groups[1].Value == "Pn")
{
resetPins = false;
string states = m.Groups[2].Value;
bool stateX = states.Contains("X");
if (stateX != PinStateLimitX)
pinStateUpdate = true;
PinStateLimitX = stateX;
bool stateY = states.Contains("Y");
if (stateY != PinStateLimitY)
pinStateUpdate = true;
PinStateLimitY = stateY;
bool stateZ = states.Contains("Z");
if (stateZ != PinStateLimitZ)
pinStateUpdate = true;
PinStateLimitZ = stateZ;
bool stateP = states.Contains("P");
if (stateP != PinStateProbe)
pinStateUpdate = true;
PinStateProbe = stateP;
}
else if (m.Groups[1].Value == "F")
{
try
{
FeedRateRealtime = double.Parse(m.Groups[2].Value, Constants.DecimalParseFormat);
posUpdate = true;
}
catch { NonFatalException.Invoke(string.Format("Received Bad Status: '{0}'", line)); }
}
else if (m.Groups[1].Value == "FS")
{
try
{
string[] parts = m.Groups[2].Value.Split(',');
FeedRateRealtime = double.Parse(parts[0], Constants.DecimalParseFormat);
SpindleSpeedRealtime = double.Parse(parts[1], Constants.DecimalParseFormat);
posUpdate = true;
}
catch { NonFatalException.Invoke(string.Format("Received Bad Status: '{0}'", line)); }
}
}
SyncBuffer = false; //only run this immediately after button press
//run this later to catch work offset changes before parsing position
Vector3 NewMachinePosition = MachinePosition;
foreach (Match m in statusMatch)
{
if (m.Groups[1].Value == "MPos" || m.Groups[1].Value == "WPos")
{
try
{
string PositionString = m.Groups[2].Value;
if (Properties.Settings.Default.IgnoreAdditionalAxes)
{
string[] parts = PositionString.Split(',');
if (parts.Length > 3)
{
Array.Resize(ref parts, 3);
PositionString = string.Join(",", parts);
}
}
NewMachinePosition = Vector3.Parse(PositionString);
if (m.Groups[1].Value == "WPos")
NewMachinePosition += WorkOffset;
if (NewMachinePosition != MachinePosition)
{
posUpdate = true;
MachinePosition = NewMachinePosition;
}
}
catch { NonFatalException.Invoke(string.Format("Received Bad Status: '{0}'", line)); }
}
}
if (posUpdate && Connected && PositionUpdateReceived != null)
PositionUpdateReceived.Invoke();
if (overrideUpdate && Connected && OverrideChanged != null)
OverrideChanged.Invoke();
if (resetPins) //no pin state received in status -> all zero
{
pinStateUpdate = PinStateLimitX | PinStateLimitY | PinStateLimitZ | PinStateProbe; //was any pin set before
PinStateLimitX = false;
PinStateLimitY = false;
PinStateLimitZ = false;
PinStateProbe = false;
}
if (pinStateUpdate && Connected && PinStateChanged != null)
PinStateChanged.Invoke();
if (Connected && StatusReceived != null)
StatusReceived.Invoke(line);
}
19
View Source File : Machine.cs
License : MIT License
Project Creator : 3RD-Dimension
License : MIT License
Project Creator : 3RD-Dimension
private void ParseProbe(string line)
{
if (ProbeFinished == null)
return;
Match probeMatch = ProbeEx.Match(line);
Group pos = probeMatch.Groups["Pos"];
Group success = probeMatch.Groups["Success"];
if (!probeMatch.Success || !(pos.Success & success.Success))
{
NonFatalException.Invoke($"Received Bad Probe: '{line}'");
return;
}
string PositionString = pos.Value;
if (Properties.Settings.Default.IgnoreAdditionalAxes)
{
string[] parts = PositionString.Split(',');
if (parts.Length > 3)
{
Array.Resize(ref parts, 3);
PositionString = string.Join(",", parts);
}
}
Vector3 ProbePos = Vector3.Parse(PositionString);
LastProbePosMachine = ProbePos;
ProbePos -= WorkOffset;
LastProbePosWork = ProbePos;
bool ProbeSuccess = success.Value == "1";
ProbeFinished.Invoke(ProbePos, ProbeSuccess);
}
19
View Source File : LoremFuzzer.cs
License : Apache License 2.0
Project Creator : 42skillz
License : Apache License 2.0
Project Creator : 42skillz
public string GenerateSentence(int? nbOfWords = null)
{
nbOfWords = nbOfWords ?? 6;
if(nbOfWords < MinNumberOfWordsInASentence)
{
throw new ArgumentOutOfRangeException(nameof(nbOfWords), "A sentence must have more than 1 word.");
}
var words = GenerateWords(nbOfWords.Value).ToArray();
var firstWordCapitalized = words.First().FirstCharToUpper();
words[0] = firstWordCapitalized;
var sentence = $"{string.Join(" ", words)}.";
return sentence;
}
19
View Source File : Modifier_DefineSymbol.cs
License : MIT License
Project Creator : 5minlab
License : MIT License
Project Creator : 5minlab
public void Reload(AnyDictionary dict) {
var prev = PlayerSettings.GetScriptingDefineSymbolsForGroup(targetGroup);
var tokens = new List<string>();
if (prev.Length > 0) {
tokens.Add(prev);
}
for(int i = 0; i < dict.Count; i++) {
var s = dict.GetAt<string>(i);
if(s == null || s == "") {
continue;
}
tokens.Add(s);
}
this.defines = string.Join(";", tokens.ToArray());
}
19
View Source File : Modifier_Publishing.cs
License : MIT License
Project Creator : 5minlab
License : MIT License
Project Creator : 5minlab
public string GetConfigText() {
var cb = new ConfigTextBuilder();
// android
cb.Append("android_useApkExpansion", android_useApkExpansion);
cb.Append("uwp_capability", string.Join("|", uwp_capability));
// ps4 attributes
cb.Append("ps4_attribExclusiveVR", ps4_attribExclusiveVR);
cb.Append("ps4_attribShareSupport", ps4_attribShareSupport);
cb.Append("ps4_attribMoveSupport", ps4_attribMoveSupport);
cb.Append("ps4_category", ps4_category);
cb.Append("ps4_masterVersion", ps4_masterVersion);
cb.Append("ps4_contentID", ps4_contentID);
cb.Append("ps4_applicationParameter1", ps4_applicationParameter1);
cb.Append("ps4_applicationParameter2", ps4_applicationParameter2);
cb.Append("ps4_applicationParameter3", ps4_applicationParameter3);
cb.Append("ps4_applicationParameter4", ps4_applicationParameter4);
cb.Append("ps4_enterButtonreplacedignment", ps4_enterButtonreplacedignment);
return cb.ToString();
}
19
View Source File : Modifier_XR.cs
License : MIT License
Project Creator : 5minlab
License : MIT License
Project Creator : 5minlab
public string GetConfigText() {
var sb = new StringBuilder();
sb.AppendFormat("enabled={0}, ", enabled);
sb.AppendFormat("devices={0}, ", string.Join(",", devices));
sb.AppendFormat("stereoRenderingPath={0}", stereoRenderingPath);
return sb.ToString();
}
19
View Source File : PlayerBuildExecutor.cs
License : MIT License
Project Creator : 5minlab
License : MIT License
Project Creator : 5minlab
internal string GetConfigText() {
var sb = new StringBuilder();
sb.AppendFormat("buildTarget={0}, ", Target);
sb.AppendFormat("buildTargetGroup={0}, ", TargetGroup);
sb.AppendFormat("options={0}, ", Options);
sb.AppendFormat("scenes={0}", string.Join(",", scenes));
return sb.ToString();
}
19
View Source File : Version.cs
License : MIT License
Project Creator : 5minlab
License : MIT License
Project Creator : 5minlab
internal static string Name() {
var tokens = new string[]
{
Major.ToString(),
Minor.ToString(),
Patch.ToString(),
};
return string.Join(".", tokens);
}
19
View Source File : Server.cs
License : MIT License
Project Creator : 5minlab
License : MIT License
Project Creator : 5minlab
static void RegisterFileHandlers() {
string pattern = string.Format("({0})", string.Join("|", fileTypes.Select(x => x.Key).ToArray()));
RouteAttribute downloadRoute = new RouteAttribute(string.Format(@"^/download/(.*\.{0})$", pattern));
RouteAttribute fileRoute = new RouteAttribute(string.Format(@"^/(.*\.{0})$", pattern));
bool needs_www = fileRoot.Contains("://");
downloadRoute.m_runOnMainThread = needs_www;
fileRoute.m_runOnMainThread = needs_www;
FileHandlerDelegate callback = FileHandler;
if (needs_www)
callback = WWWFileHandler;
downloadRoute.m_callback = delegate (RequestContext context) { callback(context, true); };
fileRoute.m_callback = delegate (RequestContext context) { callback(context, false); };
registeredRoutes.Add(downloadRoute);
registeredRoutes.Add(fileRoute);
}
19
View Source File : Shell.cs
License : MIT License
Project Creator : 5minlab
License : MIT License
Project Creator : 5minlab
public static string Output() {
return string.Join("\n", Instance.m_output.ToArray());
}
19
View Source File : MainWindow.cs
License : GNU General Public License v3.0
Project Creator : a4004
License : GNU General Public License v3.0
Project Creator : a4004
private async void Init()
{
if (Program.Portable)
goto InitTaskEnd;
InitPyChk:
WaitFm.Caption("Checking if Python is installed");
await Task.Delay(1000);
if (!ShellManager.CheckCommand("py", "--version"))
{
WaitFm.Debug("Python could not be detected on your system. You can choose to install Python or use N2D22 in portable mode.", Event.Warning);
CreateRequest("Python isn't installed on this PC", "You can choose to install Python",
"Install Python 3.9.7 (Recommended)", "Portable mode (Legacy, not recommended)", out int result);
if (result == 1 /*install python*/)
{
WaitFm.Caption("Downloading Python x64 3.9.7");
try
{
WebClient client = new WebClient();
client.DownloadProgressChanged += (s, e) =>
{
WaitFm.Caption($"Downloading Python x64 3.9.7 from python.org ({e.ProgressPercentage}%)");
};
client.DownloadFileCompleted += delegate
{
WaitFm.Debug("Successfully downloaded python-3.9.7-amd64.exe from python.org", Event.Success);
WaitFm.Caption("Installing Python x64 3.9.7");
};
WaitFm.Debug("Downloading python-3.9.7-amd64.exe from python.org");
await client.DownloadFileTaskAsync("https://www.python.org/ftp/python/3.9.7/python-3.9.7-amd64.exe", "python-3.9.7-amd64.exe");
WaitFm.Caption("Installing Python");
WaitFm.Debug("Installing Python x64 3.9.7");
if (ShellManager.RunCommand(out string output, "python-3.9.7-amd64.exe", "/quiet InstallAllUsers=1 PrependPath=1"))
{
WaitFm.Caption("Verifying Python is installed");
WaitFm.Debug("Verifying Python x64 3.9.7", Event.Success);
WaitFm.replacedle("Preparing");
await Task.Delay(1000);
goto InitPyChk;
}
else
throw new Exception(output == default ? "Process not started." : output);
}
catch (Exception ex)
{
WaitFm.Debug($"Python could not be installed due to an error. {ex.Message}", Event.Critical);
await CreateMessage("We couldn't install Python", "Something went wrong during the install process. You can try again.");
WaitFm.Host.CloseTask();
WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
TaskManager.ReleaseFLock();
return;
}
}
else if (result == 2 /*run in portable mode*/)
{
Process.Start(Application.ExecutablePath, string.Join(" ", Environment.GetCommandLineArgs()) + " --portable");
Program.Terminate();
return;
}
else
throw new Exception($"The selection could not be determined due to an invalid value. {result}");
}
else
{
if (ShellManager.RunCommand(out string filePath, "py", "-c \"import sys; print(sys.executable)\""))
WaitFm.Debug($"Python is installed on this PC at \"{filePath}\".", Event.Success);
else
WaitFm.Debug("Could not get the executable path of the Python binary.", Event.Warning);
Program.Settings.PythonExe = filePath;
WaitFm.replacedle("Getting ready");
WaitFm.Caption("Checking for esptool.py");
await Task.Delay(1000);
if (!ShellManager.CheckCommand("py", "-m esptool --help"))
{
WaitFm.Debug("esptool.py isn't installed in the default Python environment. " +
"You can choose to install esptool or use N2D22 in portable mode.");
CreateRequest("esptool.py is missing", "You can choose to install it right now",
"Install esptool.py (Recommended)", "Portable mode (Legacy, not recommended)", out int result);
if (result == 1 /*install esptool*/)
{
WaitFm.Debug("Installing esptool.py");
WaitFm.Caption("Installing esptool.py");
if (ShellManager.RunCommand(out string output, "py", "-m pip install esptool"))
{
WaitFm.Debug("esptool.py was installed successfully.");
WaitFm.replacedle("Preparing");
await Task.Delay(3000);
goto InitPyChk;
}
}
else if (result == 2 /*run in portable mode*/)
{
Process.Start(Application.ExecutablePath, string.Join(" ", Environment.GetCommandLineArgs()) + " --portable");
Program.Terminate();
return;
}
else
throw new Exception($"The selection could not be determined due to an invalid value. {result}");
}
else
{
WaitFm.Caption("Making sure you're ready to flash");
WaitFm.Debug("esptool.py is installed in the default Python environment.");
Program.Settings.EsptoolPy = true;
await Task.Delay(1000);
WaitFm.Debug("Searching for device drivers.");
await Task.Delay(1000);
string silabserPath = Directory.GetDirectories(Environment.SystemDirectory + "\\DriverStore\\FileRepository\\")
.ToList().Where(o => o.Contains("silabser")).FirstOrDefault();
WaitFm.Debug($"Check \"{Environment.SystemDirectory}\\DriverStore\\FileRepository\\\" for \"silabser\"");
string ch34serPath = Directory.GetDirectories(Environment.SystemDirectory + "\\DriverStore\\FileRepository\\")
.ToList().Where(o => o.Contains("ch341ser")).FirstOrDefault();
WaitFm.Debug($"Check \"{Environment.SystemDirectory}\\DriverStore\\FileRepository\\\" for \"ch34ser\"");
string ftdiPortPath = Directory.GetDirectories(Environment.SystemDirectory + "\\DriverStore\\FileRepository\\")
.ToList().Where(o => o.Contains("ftdiport")).FirstOrDefault();
WaitFm.Debug($"Check \"{Environment.SystemDirectory}\\DriverStore\\FileRepository\\\" for \"ftdiport\"");
string ftdiBusPath = Directory.GetDirectories(Environment.SystemDirectory + "\\DriverStore\\FileRepository\\")
.ToList().Where(o => o.Contains("ftdibus")).FirstOrDefault();
WaitFm.Debug($"Check \"{Environment.SystemDirectory}\\DriverStore\\FileRepository\\\" for \"ftdibus\"");
if (silabserPath == default && ch34serPath == default && ftdiPortPath == default && ftdiBusPath == default)
{
WaitFm.Debug("Driver files not found in FileRepository.", Event.Warning);
await CreateMessage("Device drivers not found", "We could not detect any Espressif compatible device drivers " +
"on this PC. You can still try flashing your device as Windows may automatically install the correct drivers " +
"for you.", 10);
}
else if (silabserPath != default && ch34serPath != default && ftdiPortPath != default && ftdiBusPath != default)
{
WaitFm.Debug("Detected drivers: SILABSER, CH34SER, FTDIPORT-FTDIBUS", Event.Success);
await CreateMessage("Found multiple device drivers", "We found device drivers for Silicon Labs, CH34 and FTDI compatible " +
"devices on this PC. The correct driver will automatically take control of your device when flashing.", 10);
}
else
{
if (silabserPath != default)
{
WaitFm.Debug("Detected driver: SILABSER", Event.Success);
await CreateMessage("Found device driver (Silicon Labs)", "We found a device driver for Silicon Labs devices on this PC. " +
"Please ensure it is the correct driver for your device otherwise flashing might not work.", 5);
}
if (ch34serPath != default)
{
WaitFm.Debug("Detected driver: CH34SER", Event.Success);
await CreateMessage("Found device driver (CH34)", "We found a device driver for CH34 devices on this PC. " +
"Please ensure it is the correct driver for your device otherwise flashing might not work.", 5);
}
if (ftdiBusPath != default && ftdiPortPath != default)
{
WaitFm.Debug("Detected driver: FTDIPORT-FTDIBUS", Event.Success);
await CreateMessage("Found device driver (FTDI)", "We found a device driver for FTDI devices on this PC. " +
"Please ensure it is the correct driver for your device otherwise flashing might not work.", 5);
}
else if (ftdiBusPath != default || ftdiPortPath != default)
{
WaitFm.Debug($"Detected partial driver: {(ftdiPortPath != default ? "FTDIPORT" : ftdiBusPath != default ? "FTDIBUS" : "?")}", Event.Warning);
await CreateMessage("Found device driver files (FTDI)", "We found parts of a device driver package for FTDU " +
"devices on this PC. The driver might not be installed correctly. Ensure the driver is correct and/or " +
"installed correctly.", 7);
}
}
}
}
InitTaskEnd:
WaitFm.Caption("");
await Task.Delay(1000);
WaitFm.Host.CloseTask();
WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
TaskManager.ReleaseFLock();
if (Program.Settings.PortFix)
{
Invoke(new Action(() =>
{
mitigationNotice.Show();
CreateForegroundTask("devicescan-patch", new Task(delegate() { }), "", "Please connect your device to this PC. When you've confirmed it's connected, click Continue.");
}));
}
else
{
Invoke(new Action(() =>
{
CreateForegroundTask("devicescan", new Task(Search), "Searching for your device", "You should connect your device now");
}));
}
}
19
View Source File : GithubManager.cs
License : GNU General Public License v3.0
Project Creator : a4004
License : GNU General Public License v3.0
Project Creator : a4004
public static HttpStatusCode MakeApiRequestGet(out string content, string url, params string[] args)
{
HttpClient httpClient = new HttpClient();
HttpRequestMessage httpRequest = new HttpRequestMessage()
{
RequestUri = new Uri(args == null ? url : $"{url}?{string.Join("&", args)}"),
Method = HttpMethod.Get,
Version = HttpVersion.Version11
};
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("User-Agent", $"N2D22webAPI/{Environment.OSVersion.VersionString}");
HttpResponseMessage httpResponse = httpClient.SendAsync(httpRequest,
HttpCompletionOption.ResponseContentRead).GetAwaiter().GetResult();
content = httpResponse.Content.ReadreplacedtringAsync().GetAwaiter().GetResult();
Program.Debug("github", $"Request {(args == null ? url : $"{url}?{string.Join("&", args)}")}");
Program.Debug("github", $"Headers\r\n\t{string.Join("\t", httpRequest.Headers.ToString().Split('\n')).Replace("\r", "\r\n")}");
Program.Debug("github", $"Status Code {httpResponse.StatusCode} ({(int)httpResponse.StatusCode})",
httpResponse.StatusCode == HttpStatusCode.OK ? Event.Success : Event.Warning);
return httpResponse.StatusCode;
}
19
View Source File : WexApi.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
private static string Query(string method, IEnumerable<WexPair> pairlist, Dictionary<string, string> args = null)
{
var pairliststr = MakePairListString(pairlist);
var sb = new StringBuilder();
sb.Append(WebApi.RootUrl + "/api/3/");
sb.Append(method);
sb.Append("/");
sb.Append(pairliststr);
if (args != null && args.Count > 0)
{
sb.Append("?");
var arr = args.Select(x => string.Format(CultureInfo.InvariantCulture, "{0}={1}", WebUtility.UrlEncode(x.Key), WebUtility.UrlEncode(x.Value))).ToArray();
sb.Append(string.Join("&", arr));
}
var queryStr = sb.ToString();
return WebApi.Query(queryStr);
}
19
View Source File : Wildcard.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
public static string WildcardToRegex(string pattern)
{
if (pattern == null) throw new ArgumentNullException(nameof(pattern));
// Remove whitespaces
var items = pattern.Split(new []{';'}, StringSplitOptions.RemoveEmptyEntries);
for(var i=0; i<items.Length; i++)
{
items[i] = "^" + Escape(items[i].Trim()).
Replace("\\*", ".*").
Replace("\\?", ".") + "$";
}
return string.Join("|", items);
}
19
View Source File : BTCChinaAPI.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
private string GetHMACSHA1Hash(NameValueCollection parameters)
{
var keyValues = new List<string>();
foreach (string key in parameters)
{
keyValues.Add(key + "=" + parameters[key]);
}
string input = String.Join("&", keyValues.ToArray());
//signature string for hash is NOT JSON-compatible
//watch out for API changes on the website.
input = input.Replace("\"", "");
input = input.Replace("true", "1");
input = input.Replace("false", "");
input = input.Replace("null", "");
//Console.WriteLine(input);
using (var hmacsha1 = new HMACSHA1(Encoding.ASCII.GetBytes(secretKey)))
{
byte[] hashData;
using (var stream = new MemoryStream(Encoding.ASCII.GetBytes(input)))
{
hashData = hmacsha1.ComputeHash(stream);
}
// Format as hexadecimal string.
var hashBuilder = new StringBuilder();
foreach (byte data in hashData)
{
hashBuilder.Append(data.ToString("x2", CultureInfo.InvariantCulture));
}
return hashBuilder.ToString();
}
}
19
View Source File : ReaderCache.cs
License : Apache License 2.0
Project Creator : aadreja
License : Apache License 2.0
Project Creator : aadreja
public override string ToString()
{
// to be used in the debugger
if (names != null)
{
return string.Join(", ", names);
}
if (reader != null)
{
var sb = new StringBuilder();
int index = 0;
for (int i = 0; i < length; i++)
{
if (i != 0) sb.Append(", ");
sb.Append(reader.GetName(index++));
}
return sb.ToString();
}
return base.ToString();
}
19
View Source File : ReaderCache.cs
License : Apache License 2.0
Project Creator : aadreja
License : Apache License 2.0
Project Creator : aadreja
public override string ToString()
{
// to be used in the debugger
if (names != null)
{
return string.Join(", ", names);
}
if (dynamicObject != null)
{
var sb = new StringBuilder();
int index = 0;
for (int i = 0; i < length; i++)
{
if (i != 0) sb.Append(", ");
sb.Append(properytInfo[index++].Name);
}
return sb.ToString();
}
return base.ToString();
}
19
View Source File : GenericTypeExtensions.cs
License : MIT License
Project Creator : Abdulrhman5
License : MIT License
Project Creator : Abdulrhman5
public static string GetGenericTypeName(this Type type)
{
var typeName = string.Empty;
if (type.IsGenericType)
{
var genericTypes = string.Join(",", type.GetGenericArguments().Select(t => t.Name).ToArray());
typeName = $"{type.Name.Remove(type.Name.IndexOf('`'))}<{genericTypes}>";
}
else
{
typeName = type.Name;
}
return typeName;
}
19
View Source File : ServiceFacadeInspector.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
private bool DrawDataProviders(Type serviceType)
{
// If this is a data provider being used by other services, mention that now
dataProviderList.Clear();
foreach (MixedRealityDataProviderAttribute dataProviderAttribute in serviceType.GetCustomAttributes(typeof(MixedRealityDataProviderAttribute), true))
{
dataProviderList.Add(" • " + dataProviderAttribute.ServiceInterfaceType.Name);
}
if (dataProviderList.Count > 0)
{
EditorGUILayout.HelpBox("This data provider is used by the following services:\n " + String.Join("\n", dataProviderList.ToArray()), MessageType.Info);
EditorGUILayout.Space();
return true;
}
return false;
}
19
View Source File : ScriptUtilities.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
public static void AppendScriptingDefinitions(
BuildTargetGroup targetGroup,
string[] symbols)
{
if (symbols == null || symbols.Length == 0) { return; }
List<string> toAdd = new List<string>(symbols);
List<string> defines = new List<string>(PlayerSettings.GetScriptingDefineSymbolsForGroup(targetGroup).Split(';'));
PlayerSettings.SetScriptingDefineSymbolsForGroup(targetGroup, string.Join(";", defines.Union(toAdd).ToArray()));
}
19
View Source File : BuildInfoExtensions.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
public static void AppendSymbols(this IBuildInfo buildInfo, IEnumerable<string> symbols)
{
string[] toAdd = symbols.Except(buildInfo.BuildSymbols.Split(';'))
.Where(symbol => !string.IsNullOrEmpty(symbol)).ToArray();
if (!toAdd.Any())
{
return;
}
if (!string.IsNullOrEmpty(buildInfo.BuildSymbols))
{
buildInfo.BuildSymbols += ";";
}
buildInfo.BuildSymbols += string.Join(";", toAdd);
}
19
View Source File : BuildInfoExtensions.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
public static void RemoveSymbols(this IBuildInfo buildInfo, IEnumerable<string> symbolsToRemove)
{
string[] toKeep = buildInfo.BuildSymbols.Split(';').Except(symbolsToRemove).ToArray();
if (!toKeep.Any())
{
return;
}
if (!string.IsNullOrEmpty(buildInfo.BuildSymbols))
{
buildInfo.BuildSymbols = string.Empty;
}
buildInfo.BuildSymbols += string.Join(";", toKeep);
}
19
View Source File : MixedRealityEditorSettings.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
private static void LogConfigurationWarnings()
{
// Ensure compatibility with the pre-2019.3 XR architecture for customers / platforms
// with legacy requirements.
if (!XRSettingsUtilities.LegacyXREnabled)
{
Debug.LogWarning("<b>Virtual reality supported</b> not enabled. Check <i>XR Settings</i> under <i>Player Settings</i>");
}
if (!MixedRealityOptimizeUtils.IsOptimalRenderingPath())
{
Debug.LogWarning($"XR stereo rendering mode not set to <b>{RenderingMode}</b>. See <i>Mixed Reality Toolkit</i> > <i>Utilities</i> > <i>Optimize Window</i> tool for more information to improve performance");
}
// If targeting Windows Mixed Reality platform
if (MixedRealityOptimizeUtils.IsBuildTargetUWP())
{
if (!MixedRealityOptimizeUtils.IsDepthBufferSharingEnabled())
{
// If depth buffer sharing not enabled, advise to enable setting
Debug.LogWarning("<b>Depth Buffer Sharing</b> is not enabled to improve hologram stabilization. See <i>Mixed Reality Toolkit</i> > <i>Utilities</i> > <i>Optimize Window</i> tool for more information to improve performance");
}
if (!MixedRealityOptimizeUtils.IsWMRDepthBufferFormat16bit())
{
// If depth format is 24-bit, advise to consider 16-bit for performance.
Debug.LogWarning("<b>Depth Buffer Sharing</b> has 24-bit depth format selected. Consider using 16-bit for performance. See <i>Mixed Reality Toolkit</i> > <i>Utilities</i> > <i>Optimize Window</i> tool for more information to improve performance");
}
if (!UwpRecommendedAudioSpatializers.Contains(SpatializerUtilities.CurrentSpatializer))
{
Debug.LogWarning($"This application is not using the recommended <b>Audio Spatializer Plugin</b>. Go to <i>Project Settings</i> > <i>Audio</i> > <i>Spatializer Plugin</i> and select one of the following: {string.Join(", ", UwpRecommendedAudioSpatializers)}.");
}
}
else if (SpatializerUtilities.CurrentSpatializer == null)
{
Debug.LogWarning($"This application is not using an <b>Audio Spatializer Plugin</b>. Go to <i>Project Settings</i> > <i>Audio</i> > <i>Spatializer Plugin</i> and select one of the available options.");
}
}
19
View Source File : ScriptUtilities.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
public static void RemoveScriptingDefinitions(
BuildTargetGroup targetGroup,
string[] symbols)
{
if (symbols == null || symbols.Length == 0) { return; }
List<string> toRemove = new List<string>(symbols);
List<string> defines = new List<string>(PlayerSettings.GetScriptingDefineSymbolsForGroup(targetGroup).Split(';'));
PlayerSettings.SetScriptingDefineSymbolsForGroup(targetGroup, string.Join(";", defines.Except(toRemove).ToArray()));
}
19
View Source File : OVRGradleGeneration.cs
License : MIT License
Project Creator : absurd-joy
License : MIT License
Project Creator : absurd-joy
public void OnPostGenerateGradleAndroidProject(string path)
{
UnityEngine.Debug.Log("OVRGradleGeneration triggered.");
var targetOculusPlatform = new List<string>();
if (OVRDeviceSelector.isTargetDeviceQuest)
{
targetOculusPlatform.Add("quest");
}
OVRPlugin.AddCustomMetadata("target_oculus_platform", String.Join("_", targetOculusPlatform.ToArray()));
UnityEngine.Debug.LogFormat("Quest = {0}", OVRDeviceSelector.isTargetDeviceQuest);
#if UNITY_2019_3_OR_NEWER
string gradleBuildPath = Path.Combine(path, "../launcher/build.gradle");
#else
string gradleBuildPath = Path.Combine(path, "build.gradle");
#endif
bool v2SigningEnabled = true;
if (File.Exists(gradleBuildPath))
{
try
{
string gradle = File.ReadAllText(gradleBuildPath);
int v2Signingindex = gradle.IndexOf("v2SigningEnabled false");
if (v2Signingindex != -1)
{
//v2 Signing flag found, ensure the correct value is set based on platform.
if (v2SigningEnabled)
{
gradle = gradle.Replace("v2SigningEnabled false", "v2SigningEnabled true");
System.IO.File.WriteAllText(gradleBuildPath, gradle);
}
}
else
{
//v2 Signing flag missing, add it right after the key store preplacedword and set the value based on platform.
int keyPreplacedIndex = gradle.IndexOf("keyPreplacedword");
if (keyPreplacedIndex != -1)
{
int v2Index = gradle.IndexOf("\n", keyPreplacedIndex) + 1;
if(v2Index != -1)
{
gradle = gradle.Insert(v2Index, "v2SigningEnabled " + (v2SigningEnabled ? "true" : "false") + "\n");
System.IO.File.WriteAllText(gradleBuildPath, gradle);
}
}
}
}
catch (System.Exception e)
{
UnityEngine.Debug.LogWarningFormat("Unable to overwrite build.gradle, error {0}", e.Message);
}
}
else
{
UnityEngine.Debug.LogWarning("Unable to locate build.gradle");
}
PatchAndroidManifest(path);
}
19
View Source File : AndroidVideoEditorUtil.cs
License : MIT License
Project Creator : absurd-joy
License : MIT License
Project Creator : absurd-joy
[MenuItem("Oculus/Video/Enable Native Android Video Player")]
public static void EnableNativeVideoPlayer()
{
// rename NativeJavaPlayer.java.DISABLED to NativeJavaPlayer.java
if (File.Exists(disabledPlayerFileName))
{
File.Move(disabledPlayerFileName, videoPlayerFileName);
File.Move(disabledPlayerFileName + ".meta", videoPlayerFileName + ".meta");
}
replacedetDatabase.Importreplacedet(videoPlayerFileName);
replacedetDatabase.Deletereplacedet(disabledPlayerFileName);
// Enable audio plugins
PluginImporter audio360 = (PluginImporter)replacedetImporter.GetAtPath(audio360PluginPath);
PluginImporter audio360exo29 = (PluginImporter)replacedetImporter.GetAtPath(audio360Exo29PluginPath);
if (audio360 != null && audio360exo29 != null)
{
audio360.SetCompatibleWithPlatform(BuildTarget.Android, true);
audio360exo29.SetCompatibleWithPlatform(BuildTarget.Android, true);
audio360.SaveAndReimport();
audio360exo29.SaveAndReimport();
}
// Enable gradle build with exoplayer
EditorUserBuildSettings.androidBuildSystem = AndroidBuildSystem.Gradle;
// create android plugins directory if it doesn't exist
if (!Directory.Exists(androidPluginsFolder))
{
Directory.CreateDirectory(androidPluginsFolder);
}
if (!File.Exists(gradleTemplatePath))
{
if (File.Exists(gradleTemplatePath + ".DISABLED"))
{
File.Move(disabledGradleTemplatePath, gradleTemplatePath);
File.Move(disabledGradleTemplatePath + ".meta", gradleTemplatePath+".meta");
}
else
{
File.Copy(internalGradleTemplatePath, gradleTemplatePath);
}
replacedetDatabase.Importreplacedet(gradleTemplatePath);
}
// parse the gradle file to check the current version:
string currentFile = File.ReadAllText(gradleTemplatePath);
List<string> lines = new List<string>(currentFile.Split('\n'));
var gradleVersion = new System.Text.RegularExpressions.Regex("com.android.tools.build:gradle:([0-9]+\\.[0-9]+\\.[0-9]+)").Match(currentFile).Groups[1].Value;
if (gradleVersion == "2.3.0")
{
// add google() to buildscript/repositories
int buildscriptRepositories = GoToSection("buildscript.repositories", lines);
if (FindInScope("google\\(\\)", buildscriptRepositories + 1, lines) == -1)
{
lines.Insert(GetScopeEnd(buildscriptRepositories + 1, lines), "\t\tgoogle()");
}
// add google() and jcenter() to allprojects/repositories
int allprojectsRepositories = GoToSection("allprojects.repositories", lines);
if (FindInScope("google\\(\\)", allprojectsRepositories + 1, lines) == -1)
{
lines.Insert(GetScopeEnd(allprojectsRepositories + 1, lines), "\t\tgoogle()");
}
if (FindInScope("jcenter\\(\\)", allprojectsRepositories + 1, lines) == -1)
{
lines.Insert(GetScopeEnd(allprojectsRepositories + 1, lines), "\t\tjcenter()");
}
}
// add "compile 'com.google.android.exoplayer:exoplayer:2.9.5'" to dependencies
int dependencies = GoToSection("dependencies", lines);
if (FindInScope("com\\.google\\.android\\.exoplayer:exoplayer", dependencies + 1, lines) == -1)
{
lines.Insert(GetScopeEnd(dependencies + 1, lines), "\tcompile 'com.google.android.exoplayer:exoplayer:2.9.5'");
}
int android = GoToSection("android", lines);
// add compileOptions to add Java 1.8 compatibility
if (FindInScope("compileOptions", android + 1, lines) == -1)
{
int compileOptionsIndex = GetScopeEnd(android + 1, lines);
lines.Insert(compileOptionsIndex, "\t}");
lines.Insert(compileOptionsIndex, "\t\ttargetCompatibility JavaVersion.VERSION_1_8");
lines.Insert(compileOptionsIndex, "\t\tsourceCompatibility JavaVersion.VERSION_1_8");
lines.Insert(compileOptionsIndex, "\tcompileOptions {");
}
// add sourceSets if Version < 2018.2
#if !UNITY_2018_2_OR_NEWER
if (FindInScope("sourceSets\\.main\\.java\\.srcDir", android + 1, lines) == -1)
{
lines.Insert(GetScopeEnd(android + 1, lines), "\tsourceSets.main.java.srcDir \"" + gradleSourceSetPath + "\"");
}
#endif
File.WriteAllText(gradleTemplatePath, string.Join("\n", lines.ToArray()));
}
19
View Source File : AndroidVideoEditorUtil.cs
License : MIT License
Project Creator : absurd-joy
License : MIT License
Project Creator : absurd-joy
[MenuItem("Oculus/Video/Disable Native Android Video Player")]
public static void DisableNativeVideoPlayer()
{
if (File.Exists(videoPlayerFileName))
{
File.Move(videoPlayerFileName, disabledPlayerFileName);
File.Move(videoPlayerFileName + ".meta", disabledPlayerFileName + ".meta");
}
replacedetDatabase.Importreplacedet(disabledPlayerFileName);
replacedetDatabase.Deletereplacedet(videoPlayerFileName);
// Disable audio plugins
PluginImporter audio360 = (PluginImporter)replacedetImporter.GetAtPath(audio360PluginPath);
PluginImporter audio360exo29 = (PluginImporter)replacedetImporter.GetAtPath(audio360Exo29PluginPath);
if (audio360 != null && audio360exo29 != null)
{
audio360.SetCompatibleWithPlatform(BuildTarget.Android, false);
audio360exo29.SetCompatibleWithPlatform(BuildTarget.Android, false);
audio360.SaveAndReimport();
audio360exo29.SaveAndReimport();
}
// remove exoplayer and sourcesets from gradle file (leave other parts since they are harmless).
if (File.Exists(gradleTemplatePath))
{
// parse the gradle file to check the current version:
string currentFile = File.ReadAllText(gradleTemplatePath);
List<string> lines = new List<string>(currentFile.Split('\n'));
int dependencies = GoToSection("dependencies", lines);
int exoplayer = FindInScope("com\\.google\\.android\\.exoplayer:exoplayer", dependencies + 1, lines);
if (exoplayer != -1)
{
lines.RemoveAt(exoplayer);
}
int android = GoToSection("android", lines);
int sourceSets = FindInScope("sourceSets\\.main\\.java\\.srcDir", android + 1, lines);
if (sourceSets != -1)
{
lines.RemoveAt(sourceSets);
}
File.WriteAllText(gradleTemplatePath, string.Join("\n", lines.ToArray()));
}
}
19
View Source File : OVRADBTool.cs
License : MIT License
Project Creator : absurd-joy
License : MIT License
Project Creator : absurd-joy
public int RunCommand(string[] arguments, WaitingProcessToExitCallback waitingProcessToExitCallback, out string outputString, out string errorString)
{
int exitCode = -1;
if (!isReady)
{
Debug.LogWarning("OVRADBTool not ready");
outputString = string.Empty;
errorString = "OVRADBTool not ready";
return exitCode;
}
string args = string.Join(" ", arguments);
ProcessStartInfo startInfo = new ProcessStartInfo(adbPath, args);
startInfo.WorkingDirectory = androidSdkRoot;
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
outputStringBuilder = new StringBuilder("");
errorStringBuilder = new StringBuilder("");
Process process = Process.Start(startInfo);
process.OutputDataReceived += new DataReceivedEventHandler(OutputDataReceivedHandler);
process.ErrorDataReceived += new DataReceivedEventHandler(ErrorDataReceivedHandler);
process.BeginOutputReadLine();
process.BeginErrorReadLine();
try
{
do
{
if (waitingProcessToExitCallback != null)
{
waitingProcessToExitCallback();
}
} while (!process.WaitForExit(100));
process.WaitForExit();
}
catch (Exception e)
{
Debug.LogWarningFormat("[OVRADBTool.RunCommand] exception {0}", e.Message);
}
exitCode = process.ExitCode;
process.Close();
outputString = outputStringBuilder.ToString();
errorString = errorStringBuilder.ToString();
outputStringBuilder = null;
errorStringBuilder = null;
if (!string.IsNullOrEmpty(errorString))
{
if (errorString.Contains("Warning"))
{
UnityEngine.Debug.LogWarning("OVRADBTool " + errorString);
}
else
{
UnityEngine.Debug.LogError("OVRADBTool " + errorString);
}
}
return exitCode;
}
19
View Source File : OVRADBTool.cs
License : MIT License
Project Creator : absurd-joy
License : MIT License
Project Creator : absurd-joy
public Process RunCommandAsync(string[] arguments, DataReceivedEventHandler outputDataRecievedHandler)
{
if (!isReady)
{
Debug.LogWarning("OVRADBTool not ready");
return null;
}
string args = string.Join(" ", arguments);
ProcessStartInfo startInfo = new ProcessStartInfo(adbPath, args);
startInfo.WorkingDirectory = androidSdkRoot;
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
Process process = Process.Start(startInfo);
if (outputDataRecievedHandler != null)
{
process.OutputDataReceived += new DataReceivedEventHandler(outputDataRecievedHandler);
}
process.BeginOutputReadLine();
process.BeginErrorReadLine();
return process;
}
19
View Source File : OVRPlatformTool.cs
License : MIT License
Project Creator : absurd-joy
License : MIT License
Project Creator : absurd-joy
private static bool genUploadCommand(TargetPlatform targetPlatform, out string command)
{
bool success = true;
command = "";
switch (targetPlatform)
{
case TargetPlatform.Rift:
command = "upload-rift-build";
break;
case TargetPlatform.Quest:
command = "upload-quest-build";
break;
default:
OVRPlatformTool.log += "ERROR: Invalid target platform selected";
success = false;
break;
}
// Add App ID
ValidateTextField(AppIDFieldValidator, OVRPlatformToolSettings.AppID, "App ID", ref success);
command += " --app-id \"" + OVRPlatformToolSettings.AppID + "\"";
// Add App Token
ValidateTextField(GenericFieldValidator, appToken, "App Token", ref success);
command += " --app-secret \"" + appToken + "\"";
// Add Platform specific fields
if (targetPlatform == TargetPlatform.Rift)
{
// Add Rift Build Directory
ValidateTextField(DirectoryValidator, OVRPlatformToolSettings.RiftBuildDirectory, "Rift Build Directory", ref success);
command += " --build-dir \"" + OVRPlatformToolSettings.RiftBuildDirectory + "\"";
// Add Rift Launch File
ValidateTextField(FileValidator, OVRPlatformToolSettings.RiftLaunchFile, "Rift Launch File Path", ref success);
command += " --launch-file \"" + OVRPlatformToolSettings.RiftLaunchFile + "\"";
// Add Rift Build Version
ValidateTextField(GenericFieldValidator, OVRPlatformToolSettings.RiftBuildVersion, "Build Version", ref success);
command += " --version \"" + OVRPlatformToolSettings.RiftBuildVersion + "\"";
// Add Rift Launch Parameters
if (!string.IsNullOrEmpty(OVRPlatformToolSettings.RiftLaunchParams))
{
ValidateTextField(LaunchParameterValidator, OVRPlatformToolSettings.RiftLaunchParams, "Launch Parameters", ref success);
command += " --launch_params \"" + OVRPlatformToolSettings.RiftLaunchParams + "\"";
}
// Add 2D Launch File
if (!string.IsNullOrEmpty(OVRPlatformToolSettings.Rift2DLaunchFile))
{
ValidateTextField(FileValidator, OVRPlatformToolSettings.Rift2DLaunchFile, "2D Launch File", ref success);
command += " --launch_file_2d \"" + OVRPlatformToolSettings.Rift2DLaunchFile + "\"";
if (!string.IsNullOrEmpty(OVRPlatformToolSettings.Rift2DLaunchParams))
{
ValidateTextField(LaunchParameterValidator, OVRPlatformToolSettings.Rift2DLaunchParams, "2D Launch Parameters", ref success);
command += " --launch_params_2d \"" + OVRPlatformToolSettings.Rift2DLaunchParams + "\"";
}
}
// Add Firewall Exception
if (OVRPlatformToolSettings.RiftFirewallException)
{
command += " --firewall_exceptions true";
}
// Add Redistributable Packages
List<string> redistCommandIds = new List<string>();
for (int i = 0; i < OVRPlatformToolSettings.RiftRedistPackages.Count; i++)
{
if (OVRPlatformToolSettings.RiftRedistPackages[i].include)
{
redistCommandIds.Add(OVRPlatformToolSettings.RiftRedistPackages[i].id);
}
}
if (redistCommandIds.Count > 0)
{
command += " --redistributables \"" + string.Join(",", redistCommandIds.ToArray()) + "\"";
}
// Add Gamepad Emulation
if (OVRPlatformToolSettings.RiftGamepadEmulation > GamepadType.OFF &&
OVRPlatformToolSettings.RiftGamepadEmulation <= GamepadType.LEFT_D_PAD)
{
command += " --gamepad-emulation ";
switch (OVRPlatformToolSettings.RiftGamepadEmulation)
{
case GamepadType.TWINSTICK: command += "TWINSTICK"; break;
case GamepadType.RIGHT_D_PAD: command += "RIGHT_D_PAD"; break;
case GamepadType.LEFT_D_PAD: command += "LEFT_D_PAD"; break;
default: command += "OFF"; break;
}
}
// Add Rift Language Pack Directory
if (!string.IsNullOrEmpty(OVRPlatformToolSettings.LanguagePackDirectory))
{
ValidateTextField(DirectoryValidator, OVRPlatformToolSettings.LanguagePackDirectory, "Language Pack Directory", ref success);
command += " --language_packs_dir \"" + OVRPlatformToolSettings.LanguagePackDirectory + "\"";
}
}
else
{
// Add APK Build Path
ValidateTextField(FileValidator, OVRPlatformToolSettings.ApkBuildPath, "APK Build Path", ref success);
command += " --apk \"" + OVRPlatformToolSettings.ApkBuildPath + "\"";
// Add OBB File Path
if (!string.IsNullOrEmpty(OVRPlatformToolSettings.ObbFilePath))
{
ValidateTextField(FileValidator, OVRPlatformToolSettings.ObbFilePath, "OBB File Path", ref success);
command += " --obb \"" + OVRPlatformToolSettings.ObbFilePath + "\"";
}
if (OVRPlatformToolSettings.TargetPlatform == TargetPlatform.Quest)
{
// Quest specific commands
}
}
// Add replacedets Directory
if (!string.IsNullOrEmpty(OVRPlatformToolSettings.replacedetsDirectory))
{
ValidateTextField(DirectoryValidator, OVRPlatformToolSettings.replacedetsDirectory, "replacedets Directory", ref success);
command += " --replacedets-dir \"" + OVRPlatformToolSettings.replacedetsDirectory + "\"";
// Add replacedet Configurations
if (OVRPlatformToolSettings.replacedetConfigs.Count > 0)
{
List<string> replacedetConfigs = new List<string>();
for (int i = 0; i < OVRPlatformToolSettings.replacedetConfigs.Count; i++)
{
List<string> configParameters = new List<string>();
replacedetConfig config = OVRPlatformToolSettings.replacedetConfigs[i];
if (config.required)
{
configParameters.Add("\\\"required\\\":true");
}
if (config.type > replacedetConfig.replacedetType.DEFAULT)
{
string typeCommand = "\\\"type\\\":";
switch (config.type)
{
case replacedetConfig.replacedetType.LANGUAGE_PACK:
configParameters.Add(typeCommand + "\\\"LANGUAGE_PACK\\\"");
break;
case replacedetConfig.replacedetType.STORE:
configParameters.Add(typeCommand + "\\\"STORE\\\"");
break;
default:
configParameters.Add(typeCommand + "\\\"DEFAULT\\\"");
break;
}
}
if (!string.IsNullOrEmpty(config.sku))
{
configParameters.Add("\\\"sku\\\":\\\"" + config.sku + "\\\"");
}
if (configParameters.Count > 0)
{
string configString = "\\\"" + config.name + "\\\":{" + string.Join(",", configParameters.ToArray()) + "}";
replacedetConfigs.Add(configString);
}
}
if (replacedetConfigs.Count > 0)
{
command += " --replacedet_files_config {" + string.Join(",", replacedetConfigs.ToArray()) + "}";
}
}
}
// Add Release Channel
ValidateTextField(GenericFieldValidator, OVRPlatformToolSettings.ReleaseChannel, "Release Channel", ref success);
command += " --channel \"" + OVRPlatformToolSettings.ReleaseChannel + "\"";
// Add Notes
if (!string.IsNullOrEmpty(OVRPlatformToolSettings.ReleaseNote))
{
string sanatizedReleaseNote = OVRPlatformToolSettings.ReleaseNote;
sanatizedReleaseNote = sanatizedReleaseNote.Replace("\"", "\"\"");
command += " --notes \"" + sanatizedReleaseNote + "\"";
}
return success;
}
19
View Source File : AdvocateCommands.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
[CommandHandler("bestow", AccessLevel.Advocate, CommandHandlerFlag.RequiresWorld, 2,
"Sets a character's Advocate Level.",
"<name> <level>\nAdvocates can bestow any level less than their own.")]
public static void HandleBestow(Session session, params string[] parameters)
{
var charName = string.Join(" ", parameters).Trim();
var level = parameters[parameters.Length - 1];
if (!int.TryParse(level, out var advocateLevel) || advocateLevel < 1 || advocateLevel > 7)
{
session.Network.EnqueueSend(new GameMessageSystemChat($"{level} is not a valid advocate level.", ChatMessageType.Broadcast));
return;
}
var advocateName = charName.TrimEnd((" " + level).ToCharArray());
var playerToFind = PlayerManager.FindByName(advocateName);
if (playerToFind != null)
{
if (playerToFind is Player player)
{
//if (!Advocate.IsAdvocate(player))
//{
// session.Network.EnqueueSend(new GameMessageSystemChat($"{playerToFind.Name} is not an Advocate.", ChatMessageType.Broadcast));
// return;
//}
if (player.IsPK || PropertyManager.GetBool("pk_server").Item)
{
session.Network.EnqueueSend(new GameMessageSystemChat($"{playerToFind.Name} in a Player Killer and cannot be an Advocate.", ChatMessageType.Broadcast));
return;
}
if (session.Player.AdvocateLevel <= player.AdvocateLevel)
{
session.Network.EnqueueSend(new GameMessageSystemChat($"You cannot change {playerToFind.Name}'s Advocate status because they are equal to or out rank you.", ChatMessageType.Broadcast));
return;
}
if (advocateLevel >= session.Player.AdvocateLevel && !session.Player.IsAdmin)
{
session.Network.EnqueueSend(new GameMessageSystemChat($"You cannot bestow {playerToFind.Name}'s Advocate rank to {advocateLevel} because that is equal to or higher than your rank.", ChatMessageType.Broadcast));
return;
}
if (advocateLevel == player.AdvocateLevel)
{
session.Network.EnqueueSend(new GameMessageSystemChat($"{playerToFind.Name}'s Advocate rank is already at level {advocateLevel}.", ChatMessageType.Broadcast));
return;
}
if (!Advocate.CanAcceptAdvocateItems(player, advocateLevel))
{
session.Network.EnqueueSend(new GameMessageSystemChat($"You cannot change {playerToFind.Name}'s Advocate status because they do not have capacity for the advocate items.", ChatMessageType.Broadcast));
return;
}
if (Advocate.Bestow(player, advocateLevel))
session.Network.EnqueueSend(new GameMessageSystemChat($"{playerToFind.Name} is now an Advocate, level {advocateLevel}.", ChatMessageType.Broadcast));
else
session.Network.EnqueueSend(new GameMessageSystemChat($"Advocate bestowal of {playerToFind.Name} failed.", ChatMessageType.Broadcast));
}
else
session.Network.EnqueueSend(new GameMessageSystemChat($"{playerToFind.Name} is not online. Cannot complete bestowal process.", ChatMessageType.Broadcast));
}
else
session.Network.EnqueueSend(new GameMessageSystemChat($"{advocateName} was not found in the database.", ChatMessageType.Broadcast));
}
19
View Source File : AdvocateCommands.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
[CommandHandler("remove", AccessLevel.Advocate, CommandHandlerFlag.RequiresWorld, 1,
"Removes the specified character from the Advocate ranks.",
"<character name>\nAdvocates can remove Advocate status for any Advocate of lower level than their own.")]
public static void HandleRemove(Session session, params string[] parameters)
{
var charName = string.Join(" ", parameters).Trim();
var playerToFind = PlayerManager.FindByName(charName);
if (playerToFind != null)
{
if (playerToFind is Player player)
{
if (!Advocate.IsAdvocate(player))
{
session.Network.EnqueueSend(new GameMessageSystemChat($"{playerToFind.Name} is not an Advocate.", ChatMessageType.Broadcast));
return;
}
if (session.Player.AdvocateLevel < player.AdvocateLevel)
{
session.Network.EnqueueSend(new GameMessageSystemChat($"You cannot remove {playerToFind.Name}'s Advocate status because they out rank you.", ChatMessageType.Broadcast));
return;
}
if (Advocate.Remove(player))
session.Network.EnqueueSend(new GameMessageSystemChat($"{playerToFind.Name} is no longer an Advocate.", ChatMessageType.Broadcast));
else
session.Network.EnqueueSend(new GameMessageSystemChat($"Advocate removal of {playerToFind.Name} failed.", ChatMessageType.Broadcast));
}
else
session.Network.EnqueueSend(new GameMessageSystemChat($"{playerToFind.Name} is not online. Cannot complete removal process.", ChatMessageType.Broadcast));
}
else
session.Network.EnqueueSend(new GameMessageSystemChat($"{charName} was not found in the database.", ChatMessageType.Broadcast));
}
19
View Source File : CharacterCommands.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
[CommandHandler("deletecharacter", AccessLevel.Admin, CommandHandlerFlag.None, 1,
"Deletes a character and removes it from players restore list",
"[character name]\n" +
"Given the name of a character, this command deletes that character, booting it if in game, and removes it from character's restore list. (You can find the name for a character using the @finger command.)\n")]
public static void HandleCharacterForcedDelete(Session session, params string[] parameters)
{
var characterName = string.Join(" ", parameters);
var foundPlayer = PlayerManager.FindByName(characterName, out var isOnline);
if (foundPlayer == null)
{
CommandHandlerHelper.WriteOutputInfo(session, $"There is no character named {characterName} in the database.", ChatMessageType.Broadcast);
return;
}
if (isOnline && foundPlayer is Player player)
{
player.Character.DeleteTime = (ulong)Time.GetUnixTime();
player.Character.IsDeleted = true;
player.CharacterChangesDetected = true;
player.Session.LogOffPlayer(true);
PlayerManager.HandlePlayerDelete(player.Character.Id);
var success = PlayerManager.ProcessDeletedPlayer(player.Character.Id);
if (success)
CommandHandlerHelper.WriteOutputInfo(session, $"Successfully {(isOnline ? "booted and " : "")}deleted character {foundPlayer.Name} (0x{foundPlayer.Guid}).", ChatMessageType.Broadcast);
else
CommandHandlerHelper.WriteOutputInfo(session, $"Unable to {(isOnline ? "boot and " : "")}delete character {foundPlayer.Name} (0x{foundPlayer.Guid}) due to PlayerManager failure.", ChatMessageType.Broadcast);
}
else
{
var existingCharId = foundPlayer.Guid.Full; //DatabaseManager.Shard.BaseDatabase.GetCharacterStubByName(foundPlayer.Name).Id;
DatabaseManager.Shard.GetCharacter(existingCharId, character =>
{
if (character != null)
{
character.DeleteTime = (ulong)Time.GetUnixTime();
character.IsDeleted = true;
DatabaseManager.Shard.SaveCharacter(character, new ReaderWriterLockSlim(), result =>
{
if (result)
{
var deleteOfflineChain = new ActionChain();
deleteOfflineChain.AddAction(WorldManager.ActionQueue, () => PlayerManager.HandlePlayerDelete(character.Id));
deleteOfflineChain.AddDelayForOneTick();
deleteOfflineChain.AddAction(WorldManager.ActionQueue, () =>
{
var success = PlayerManager.ProcessDeletedPlayer(character.Id);
if (success)
CommandHandlerHelper.WriteOutputInfo(session, $"Successfully {(isOnline ? "booted and " : "")}deleted character {foundPlayer.Name} (0x{foundPlayer.Guid}).", ChatMessageType.Broadcast);
else
CommandHandlerHelper.WriteOutputInfo(session, $"Unable to {(isOnline ? "boot and " : "")}delete character {foundPlayer.Name} (0x{foundPlayer.Guid}) due to PlayerManager failure.", ChatMessageType.Broadcast);
});
deleteOfflineChain.EnqueueChain();
}
else
CommandHandlerHelper.WriteOutputInfo(session, $"Unable to {(isOnline ? "boot and " : "")}delete character {foundPlayer.Name} (0x{foundPlayer.Guid}) due to shard database SaveCharacter failure.", ChatMessageType.Broadcast);
});
}
else
CommandHandlerHelper.WriteOutputInfo(session, $"Unable to {(isOnline ? "boot and " : "")}delete character {foundPlayer.Name} (0x{foundPlayer.Guid}) due to shard database GetCharacter failure.", ChatMessageType.Broadcast);
});
}
}
19
View Source File : Diagnostics.cs
License : MIT License
Project Creator : acidbubbles
License : MIT License
Project Creator : acidbubbles
public static string GetHierarchy(GameObject o)
{
if (o == null)
return "{null}";
var items = new List<string>(new[] { o.name });
GameObject parent = o;
for (int i = 0; i < 100; i++)
{
parent = parent.transform.parent?.gameObject;
if (parent == null || parent == o) break;
items.Insert(0, parent.gameObject.name);
}
return string.Join(" -> ", items.ToArray());
}
19
View Source File : Diagnostics.cs
License : MIT License
Project Creator : acidbubbles
License : MIT License
Project Creator : acidbubbles
public static void SimulateSave()
{
var j = new SimpleJSON.JSONArray();
foreach (var atom in SuperController.singleton.GetAtoms())
{
if (!atom.name.Contains("Mirror") && !atom.name.Contains("Glreplaced")) continue;
try
{
// atom.GetJSON(true, true, true);
foreach (var id in atom.GetStorableIDs())
{
var stor = atom.GetStorableByID(id);
if (stor.gameObject == null) throw new NullReferenceException("123");
try
{
if (stor == null) throw new Exception("Case 1");
if (stor.enabled == false) throw new Exception("Case 2");
SuperController.LogMessage("Storage" + atom.name + "/" + stor.name + " (" + stor.storeId + ")");
string[] value = stor.GetAllFloatAndColorParamNames().ToArray();
SuperController.LogMessage(" -" + string.Join(", ", value));
// var x = stor.name;
// stor.GetJSON();
}
catch (Exception se)
{
SuperController.LogMessage("Error with " + atom.name + "/" + stor.name + ": " + se);
}
}
// atom.Store(j);
}
catch (Exception je)
{
SuperController.LogMessage("Error with " + GetHierarchy(atom.gameObject) + " " + atom + ": " + je);
}
}
}
19
View Source File : Diagnostics.cs
License : MIT License
Project Creator : acidbubbles
License : MIT License
Project Creator : acidbubbles
internal static string GetList(IEnumerable<string> values)
{
return string.Join(", ", values.ToArray());
}
See More Examples