Here are the examples of the csharp api System.Text.RegularExpressions.Regex.Match(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2762 Examples
19
Source : GoPhishIntegration.cs
with GNU General Public License v3.0
from 0dteam
with GNU General Public License v3.0
from 0dteam
public static string setReportURL(string headers)
{
// Extract GoPhish Custom Header (X-GOPHISH-ASMN: USERID0123)
var match = new Regex(WebExpID).Match(headers);
foreach (var group in match.Groups)
{
if(group.ToString().Trim()!=string.Empty)
{
// Extract User ID from the header (USERID0123)
string user_id = group.ToString().Replace(WebExpPrefix, string.Empty);
// Build reporting URL, something like this -> https[:]//GOPHISHURL:PORT/report?rid=USERID
string report_url = URLrequest.Replace(@"USERID", user_id);
return report_url;
}
}
// else, no header was found -> No report tracking URL
return "NaN";
}
19
Source : MsSqlDbManager.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
public override DefaultValue? ParseDefaultValue(string? rawColumnDefaultValue)
{
if (string.IsNullOrEmpty(rawColumnDefaultValue))
{
return null;
}
if (TryGetDefaultValue(rawColumnDefaultValue, IntDefRegEx, DefaultValueType.Integer, out var result))
{
return result;
}
if (TryGetDefaultValue(rawColumnDefaultValue, StringDefRegEx, DefaultValueType.String, out result))
{
return result;
}
if (string.Equals(rawColumnDefaultValue, "(getutcdate())", StringComparison.InvariantCultureIgnoreCase))
{
return new DefaultValue(DefaultValueType.GetUtcDate, null);
}
if (string.Equals(rawColumnDefaultValue, "(NULL)", StringComparison.InvariantCultureIgnoreCase))
{
return new DefaultValue(DefaultValueType.Null, null);
}
return new DefaultValue(DefaultValueType.Raw, rawColumnDefaultValue);
static bool TryGetDefaultValue(string value, Regex regex, DefaultValueType defaultValueType, out DefaultValue? result)
{
var m = regex.Match(value);
if (m.Success)
{
result = new DefaultValue(defaultValueType, m.Result("$1"));
return true;
}
result = null;
return false;
}
}
19
Source : StringHelper.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
public static string AddNumberUntilUnique(string input, string delimiter, Predicate<string> test)
{
Regex regex = new Regex($"(.+?){delimiter}(\\d+)");
while (!test(input))
{
int nextNo = 2;
var m = regex.Match(input);
if (m.Success)
{
input = m.Result("$1");
nextNo = int.Parse(m.Result("$2")) + 1;
}
input = input + delimiter + nextNo;
}
return input;
}
19
Source : TextFindForm.cs
with Apache License 2.0
from 214175590
with Apache License 2.0
from 214175590
public bool FindStr()
{
bool finds = false;
string text = text_res.Text;
info.Text = "";
if (text != "")
{
string content = getContent();
bool caseDx = cb_case.Checked;
bool whole = cb_whole.Checked;
bool regex = cb_regex.Checked;
if (tempCont != content || text != tempStr)
{
string fmt = null;
if (whole)
{
fmt = "[^\u4e00-\u9fa50-9a-zA-Z]+{0}[^\u4e00-\u9fa50-9a-zA-Z]+";
}
reg1 = new Regex(fmt == null ? text : string.Format(fmt, text));
reg2 = null;
if (caseDx)
{
if (text.ToUpper() != text.ToLower())
{
reg1 = new Regex(fmt == null ? text.ToUpper() : string.Format(fmt, text.ToUpper()));
reg2 = new Regex(fmt == null ? text.ToLower() : string.Format(fmt, text.ToLower()));
}
}
match1 = reg1.Match(content);
match2 = null;
if (reg2 != null)
{
match2 = reg2.Match(content);
}
}
else
{
match1 = reg1.Match(content, match1.Index + match1.Length);
if (reg2 != null)
{
match2 = reg2.Match(content, match2.Index + match2.Length);
}
}
if (null != match1 && match1.Success) //当查找成功时候
{
tempCont = content;
tempStr = text;
addFindHisItem(text);
finds = true;
findCall(text, match1.Index);
}
else if (null != match2 && match2.Success) //当查找成功时候
{
tempCont = content;
tempStr = text;
addFindHisItem(text);
finds = true;
findCall(text, match2.Index);
}
else
{
info.Text = "没有找到结果";
}
}
return finds;
}
19
Source : TemplateEngin.cs
with MIT License
from 2881099
with MIT License
from 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
Source : ShareHandler.cs
with GNU General Public License v3.0
from 2dust
with GNU General Public License v3.0
from 2dust
private static VmessItem ResolveSSLegacy(string result)
{
var match = UrlFinder.Match(result);
if (!match.Success)
return null;
VmessItem server = new VmessItem();
var base64 = match.Groups["base64"].Value.TrimEnd('/');
var tag = match.Groups["tag"].Value;
if (!Utils.IsNullOrEmpty(tag))
{
server.remarks = Utils.UrlDecode(tag);
}
Match details;
try
{
details = DetailsParser.Match(Encoding.UTF8.GetString(Convert.FromBase64String(
base64.PadRight(base64.Length + (4 - base64.Length % 4) % 4, '='))));
}
catch (FormatException)
{
return null;
}
if (!details.Success)
return null;
server.security = details.Groups["method"].Value;
server.id = details.Groups["preplacedword"].Value;
server.address = details.Groups["hostname"].Value;
server.port = int.Parse(details.Groups["port"].Value);
return server;
}
19
Source : ShareHandler.cs
with GNU General Public License v3.0
from 2dust
with GNU General Public License v3.0
from 2dust
private static VmessItem ResolveStdVmess(string result)
{
VmessItem i = new VmessItem
{
configType = (int)EConfigType.Vmess,
security = "auto"
};
Uri u = new Uri(result);
i.address = u.IdnHost;
i.port = u.Port;
i.remarks = u.GetComponents(UriComponents.Fragment, UriFormat.Unescaped);
var q = HttpUtility.ParseQueryString(u.Query);
var m = StdVmessUserInfo.Match(u.UserInfo);
if (!m.Success) return null;
i.id = m.Groups["id"].Value;
if (!int.TryParse(m.Groups["alterId"].Value, out int aid))
{
return null;
}
i.alterId = aid;
if (m.Groups["streamSecurity"].Success)
{
i.streamSecurity = m.Groups["streamSecurity"].Value;
}
switch (i.streamSecurity)
{
case "tls":
// TODO tls config
break;
default:
if (!string.IsNullOrWhiteSpace(i.streamSecurity))
return null;
break;
}
i.network = m.Groups["network"].Value;
switch (i.network)
{
case "tcp":
string t1 = q["type"] ?? "none";
i.headerType = t1;
// TODO http option
break;
case "kcp":
i.headerType = q["type"] ?? "none";
// TODO kcp seed
break;
case "ws":
string p1 = q["path"] ?? "/";
string h1 = q["host"] ?? "";
i.requestHost = Utils.UrlDecode(h1);
i.path = p1;
break;
case "http":
case "h2":
i.network = "h2";
string p2 = q["path"] ?? "/";
string h2 = q["host"] ?? "";
i.requestHost = Utils.UrlDecode(h2);
i.path = p2;
break;
case "quic":
string s = q["security"] ?? "none";
string k = q["key"] ?? "";
string t3 = q["type"] ?? "none";
i.headerType = t3;
i.requestHost = Utils.UrlDecode(s);
i.path = k;
break;
default:
return null;
}
return i;
}
19
Source : GrblSettingsWindow.xaml.cs
with MIT License
from 3RD-Dimension
with MIT License
from 3RD-Dimension
public void LineReceived(string line)
{
// Recieve GRBL Controller Version number and display - $i
// Recieved in format [VER: ... and [OPT:
if (!line.StartsWith("$") && !line.StartsWith("[VER:") && !line.StartsWith("[OPT:"))
return;
if (line.StartsWith("$"))
{
try
{
Match m = settingParser.Match(line);
int number = int.Parse(m.Groups[1].Value);
double value = double.Parse(m.Groups[2].Value, Util.Constants.DecimalParseFormat);
// Value = Setting Value, Number = Setting Code
if (!CurrentSettings.ContainsKey(number))
{
RowDefinition rowDef = new RowDefinition();
rowDef.Height = new GridLength(25);
gridMain.RowDefinitions.Add(rowDef);
TextBox valBox = new TextBox // Value of Setting Textbox
{
Text = value.ToString(Util.Constants.DecimalOutputFormat),
VerticalAlignment = VerticalAlignment.Center
};
// Define Mouseclick for textbox to open GRBLStepsCalcWindow for setting $100, $101, $102
if (number == 100) { valBox.Name = "Set100"; valBox.MouseDoubleClick += openStepsCalc; }
else if (number == 101) { valBox.Name = "Set101"; valBox.MouseDoubleClick += openStepsCalc; }
else if (number == 102) { valBox.Name = "Set102"; valBox.MouseDoubleClick += openStepsCalc; }
Grid.SetRow(valBox, gridMain.RowDefinitions.Count - 1);
Grid.SetColumn(valBox, 1);
gridMain.Children.Add(valBox);
TextBlock num = new TextBlock
{
Text = $"${number}=",
HorizontalAlignment = HorizontalAlignment.Right,
VerticalAlignment = VerticalAlignment.Center
};
Grid.SetRow(num, gridMain.RowDefinitions.Count - 1);
Grid.SetColumn(num, 0);
gridMain.Children.Add(num);
if (Util.GrblCodeTranslator.Settings.ContainsKey(number))
{
Tuple<string, string, string> labels = Util.GrblCodeTranslator.Settings[number];
TextBlock name = new TextBlock
{
Text = labels.Item1,
VerticalAlignment = VerticalAlignment.Center
};
Grid.SetRow(name, gridMain.RowDefinitions.Count - 1);
Grid.SetColumn(name, 0);
gridMain.Children.Add(name);
TextBlock unit = new TextBlock
{
Text = labels.Item2,
VerticalAlignment = VerticalAlignment.Center
};
Grid.SetRow(unit, gridMain.RowDefinitions.Count - 1);
Grid.SetColumn(unit, 2);
gridMain.Children.Add(unit);
valBox.ToolTip = $"{labels.Item1} ({labels.Item2}):\n{labels.Item3}";
}
CurrentSettings.Add(number, value);
SettingsBoxes.Add(number, valBox);
}
else
{
SettingsBoxes[number].Text = value.ToString(Util.Constants.DecimalOutputFormat);
CurrentSettings[number] = value;
}
}
catch { }
}
// If the line starts with [VER: then we know we are getting the version and options
else if (line.StartsWith("[VER:") || line.StartsWith("[OPT:"))
{
// Frist need to remove front [ and rear ]
string VerOptInput; // Input string
string[] VerOptTrimmed;
VerOptInput = line.Remove(0, 1); // Remove [ from the start
VerOptInput = VerOptInput.Remove(VerOptInput.Length - 1);
// Next, split the values in half at the : - we only want VER/OPT and then the values
VerOptTrimmed = VerOptInput.Split(':');
// Now we fill in the boxes depending on which one
switch (VerOptTrimmed[0])
{
case "VER":
controllerInfo += "Version: " + VerOptTrimmed[1];
break;
case "OPT":
// First we have to split commas
string[] optSplit;
optSplit = VerOptTrimmed[1].Split(','); // Splits Options into 3. 0=Options, 1=blockBufferSize, 2=rxBufferSize
var individualChar = optSplit[0].ToCharArray();// Now split optSplit[0] into each option character
controllerInfo += " | Options: " + VerOptTrimmed[1]; // Full Options Non-Decoded String
foreach (char c in individualChar)
{
// Lookup what each code is and display.... buildCodes Dictionary
if (Util.GrblCodeTranslator.BuildCodes.ContainsKey(c.ToString()))
{
// Now lets try and create and append to a string and then bind it to a ToolTip? or some other way
controllerInfo += Environment.NewLine + Util.GrblCodeTranslator.BuildCodes[c.ToString()];
}
}
controllerInfo += Environment.NewLine + "Block Buffer Size: " + optSplit[1];
controllerInfo += Environment.NewLine + "RX Buffer Size: " + optSplit[2];
GRBL_Controller_Info.Text = controllerInfo.ToString();
break;
}
}
}
19
Source : LogConfigUtil.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
public static bool IsHotfix(string[] datas, out int index)
{
index = -1;
for (int i = datas.Length - 1; i > 0; i--)
{
Regex regex = new Regex(@"IL_[\s\S]*[\s\S]*[\s\S]*[\s\S]*: call");
Match match = regex.Match(datas[i]);
if (match.Success)
{
index = i + 1;
break;
}
}
//不是热更
if (index == -1)
{
for (int i = datas.Length - 1; i > 0; i--)
{
bool isLog = false;
foreach (LogConfig item in logConfigList)
{
if (datas[i].Contains(item.name))
{
isLog = true;
break;
}
}
if (isLog)
{
index = i + 1;
break;
}
}
return false;
}
return true;
}
19
Source : Machine.cs
with MIT License
from 3RD-Dimension
with MIT License
from 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
Source : Machine.cs
with MIT License
from 3RD-Dimension
with MIT License
from 3RD-Dimension
private void ParseStartup(string line)
{ // TODO Kinda Successfull, still need to find a way to ask for it just after recieving OK message on Connection
Match m = StartupRegex.Match(line);
int major, minor;
char rev;
if (!m.Success ||
!int.TryParse(m.Groups[1].Value, out major) ||
!int.TryParse(m.Groups[2].Value, out minor) ||
!char.TryParse(m.Groups[3].Value, out rev))
{
RaiseEvent(Info, "Could not read GRBL Version.");
return;
}
// TODO Display current GRBL version in the Connection or About box
Version v = new Version(major, minor, (int)rev);
GRBL_Version = v.ToString();
Console.WriteLine("GRBL Version is " + GRBL_Version);
if (v < Constants.MinimumGrblVersion)
{
ReportError("Outdated version of grbl detected!");
ReportError($"Please upgrade to at least grbl v{Constants.MinimumGrblVersion.Major}.{Constants.MinimumGrblVersion.Minor}{(char)Constants.MinimumGrblVersion.Build}");
}
}
19
Source : UnityARBuildPostprocessor.cs
with MIT License
from 734843327
with MIT License
from 734843327
internal static bool ReplaceCppMacro(string[] lines, string name, string newValue)
{
bool replaced = false;
Regex matchRegex = new Regex(@"^.*#\s*define\s+" + name);
Regex replaceRegex = new Regex(@"^.*#\s*define\s+" + name + @"(:?|\s|\s.*[^\\])$");
for (int i = 0; i < lines.Count(); i++)
{
if (matchRegex.Match (lines [i]).Success) {
lines [i] = replaceRegex.Replace (lines [i], "#define " + name + " " + newValue);
replaced = true;
}
}
return replaced;
}
19
Source : Utility.IP.cs
with MIT License
from 7Bytes-Studio
with MIT License
from 7Bytes-Studio
public static string GetPublicIP()
{
if (!string.IsNullOrEmpty(g_CachePublicIp))
{
return g_CachePublicIp;
}
var hostName = Dns.GetHostName();
var addresses = Dns.GetHostAddresses(hostName);
string ip = string.Empty;
for (int i = 0; i < addresses.Length; i++)
{
if (!string.IsNullOrEmpty(ip = g_IpRegex.Match(addresses[i].ToString()).Groups[0].Value))
{
return ip.Trim();
}
}
return string.Empty;
}
19
Source : Utility.IP.cs
with MIT License
from 7Bytes-Studio
with MIT License
from 7Bytes-Studio
public static string GetRealPublicIP()
{
var hostName = Dns.GetHostName();
var addresses = Dns.GetHostAddresses(hostName);
string ip = string.Empty;
for (int i = 0; i < addresses.Length; i++)
{
if (!string.IsNullOrEmpty(ip = g_IpRegex.Match(addresses[i].ToString()).Groups[0].Value))
{
return ip.Trim();
}
}
return string.Empty;
}
19
Source : ToolsService.cs
with Apache License 2.0
from 91270
with Apache License 2.0
from 91270
private string GetCustomValue(string customValue, string start, string end)
{
Regex r = new Regex("(?<=(" + start + "))[.\\s\\S]*?(?=(" + end + "))");
return r.Match(customValue).Value;
}
19
Source : MicroVM.Assembler.cs
with MIT License
from a-downing
with MIT License
from a-downing
bool TryParseIntegerLiteral(string str, out int value) {
Match decimalMatch = decimalRegex.Match(str);
Match hexMatch = hexRegex.Match(str);
Match binMatch = binRegex.Match(str);
if(decimalMatch.Success) {
value = Convert.ToInt32(decimalMatch.Groups[0].ToString(), 10);
return true;
} else if(hexMatch.Success) {
str = hexMatch.Groups[0].ToString();
value = Convert.ToInt32(hexMatch.Groups[2].ToString(), 16);
if(hexMatch.Groups[1].ToString() == "-") {
value *= -1;
}
return true;
} else if(binMatch.Success) {
str = binMatch.Groups[0].ToString();
value = Convert.ToInt32(binMatch.Groups[2].ToString(), 2);
if(binMatch.Groups[1].ToString() == "-") {
value *= -1;
}
return true;
}
value = 0;
return false;
}
19
Source : MicroVM.Assembler.cs
with MIT License
from a-downing
with MIT License
from a-downing
bool Tokenize() {
for(int i = 0; i < statements.Count; i++) {
var statement = statements[i];
for(int j = 0; j < statement.line.Length; j++) {
string arg = statement.line[j];
statement.tokens[j].offset = 0;
statement.tokens[j].type = Token.Type.NONE;
Match directiveMatch = directiveRegex.Match(arg);
Match labelMatch = labelRegex.Match(arg);
Match identifierMatch = identifierRegex.Match(arg);
Match instructionMatch = instructionRegex.Match(arg);
Match floatMatch = floatRegex.Match(arg);
if(directiveMatch.Success) {
statement.tokens[j].type = Token.Type.DIRECTIVE;
statement.tokens[j].stringValue = directiveMatch.Groups[1].ToString();
} else if(labelMatch.Success) {
statement.tokens[j].type = Token.Type.LABEL;
statement.tokens[j].stringValue = labelMatch.Groups[1].ToString();
} else if(identifierMatch.Success) {
statement.tokens[j].type = (j == 0) ? Token.Type.INSTRUCTION : Token.Type.IDENTIFIER;
statement.tokens[j].stringValue = identifierMatch.Groups[0].ToString();
if(statement.tokens[j].type == Token.Type.INSTRUCTION) {
statement.tokens[j].cond = "al";
}
} else if(instructionMatch.Success) {
statement.tokens[j].type = Token.Type.INSTRUCTION;
statement.tokens[j].stringValue = instructionMatch.Groups[1].ToString();
statement.tokens[j].cond = instructionMatch.Groups[2].ToString();
} else if(floatMatch.Success && floatMatch.Groups[0].ToString() != ".") {
statement.tokens[j].type = Token.Type.FLOAT;
statement.tokens[j].stringValue = floatMatch.Groups[0].ToString();
float.TryParse(statement.tokens[j].stringValue, out statement.tokens[j].var.val32.Float);
statement.tokens[j].var.type = Variable.Type.FLOAT;
} else if(TryParseIntegerLiteral(arg, out statement.tokens[j].var.val32.Int)) {
statement.tokens[j].type = Token.Type.INTEGER;
statement.tokens[j].stringValue = arg;
statement.tokens[j].var.type = Variable.Type.INT;
}
}
}
return true;
}
19
Source : PagingUtil.cs
with MIT License
from a34546
with MIT License
from a34546
public static PartedSql SplitSql(string sql)
{
var parts = new PartedSql { Raw = sql };
// Extract the sql from "SELECT <whatever> FROM"
var s = _rexSelect1.Match(sql);
if (s.Success)
{
parts.Select = s.Groups[1].Value;
sql = sql.Substring(s.Length);
s = _rexOrderBy.Match(sql);
if (s.Success)
{
sql = sql.Substring(0, s.Index);
parts.OrderBy = s.Groups[1].Value;
}
parts.Body = "(" + sql;
return parts;
}
var m = _rexSelect.Match(sql);
if (!m.Success)
throw new ArgumentException("Unable to parse SQL statement for select");
parts.Select = m.Groups[1].Value;
sql = sql.Substring(m.Length);
m = _rexOrderBy.Match(sql);
if (m.Success)
{
sql = sql.Substring(0, m.Index);
parts.OrderBy = m.Groups[1].Value;
}
parts.Body = sql;
return parts;
}
19
Source : MacroPatterns.cs
with Apache License 2.0
from aaaddress1
with Apache License 2.0
from aaaddress1
public static string ReplaceSelectActiveCellFormula(string cellFormula, string variableName = DefaultVariableName)
{
if (cellFormula.Contains("ACTIVE.CELL()"))
{
cellFormula = cellFormula.Replace("ACTIVE.CELL()", variableName);
}
string selectRegex = @"=SELECT\(.*?\)";
string selectRelativeRegex = @"=SELECT\(.*(R(\[\d+\]){0,1}C(\[\d+\]){0,1}).*?\)";
Regex sRegex = new Regex(selectRegex);
Regex srRegex = new Regex(selectRelativeRegex);
Match sRegexMatch = sRegex.Match(cellFormula);
if (sRegexMatch.Success)
{
Match srRegexMatch = srRegex.Match(cellFormula);
string selectStringMatch = sRegexMatch.Value;
//We have a line like =SELECT(,"R[1]C")
if (srRegexMatch.Success)
{
string relAddress = srRegexMatch.Groups[1].Value;
string relReplace = cellFormula.Replace(selectStringMatch,
string.Format("{0}=ABSREF(\"{1}\",{0})", variableName, relAddress));
return relReplace;
}
//We have a line like =SELECT(B1:B111,B1)
else
{
string targetCell = selectStringMatch.Split(",").Last().Split(')').First();
string varreplacedign = cellFormula.Replace(selectStringMatch,
string.Format("{0}={1}", variableName, targetCell));
return varreplacedign;
}
}
return cellFormula;
}
19
Source : obfuscator.cs
with MIT License
from aaaddress1
with MIT License
from aaaddress1
private static void obfuscatCode(string orginalCode, ref string currLineAddition, ref string extraCodeAddition, bool forceJunk = false)
{
currLineAddition = orginalCode + "\r\n";
extraCodeAddition = "";
if (!shouldGeneratJunk() && !forceJunk) return;
obfuscat_code_count++;
Match m = new Regex(@"mov[\x20\t]+([^,]+),(.+)").Match(orginalCode);
if (m.Success)
{
currLineAddition = string.Format(
"push {1} \r\n" +
"call obfusca_{2} \r\n" +
"pop {0} \r\n",
m.Groups[1].Value, m.Groups[2].Value, label_extra_count
);
extraCodeAddition = string.Format(
"obfusca_{0}: \r\n" +
"pushf \r\n" +
"push ecx \r\n" +
"mov ecx, {2} \r\n" +
"obfusca_{1}: \r\n" +
"loop obfusca_{1} \r\n" +
"pop ecx \r\n" +
"popf \r\n" +
"ret \r\n", label_extra_count, label_extra_count+1, rnd.Next(5, 128)
);
label_extra_count += 2;
return;
}
m = new Regex(@"call[\x20\t]+(.+)").Match(orginalCode);
if (m.Success)
{
currLineAddition = string.Format(
"push offset obfusca_{1} \r\n" +
"push offset {0} \r\n" +
"ret \r\n" +
"obfusca_{1}:",
m.Groups[1].Value, label_extra_count
);
extraCodeAddition = "";
label_extra_count += 1;
return;
}
currLineAddition = string.Format(
"obfusca_{1}: \r\n" +
"call obfusca_{2} \r\n" +
"loop obfusca_{1} \r\n" +
"obfusca_{2}: \r\n" +
"call obfusca_{3} \r\n"+
"loop obfusca_{1} \r\n" +
"obfusca_{3}: \r\n" +
"call obfusca_{4} \r\n" +
"loop obfusca_{2} \r\n" +
"obfusca_{4}: \r\n" +
"lea esp, [esp+12] \r\n" +
"{0} \r\n",
orginalCode, label_extra_count, label_extra_count + 1, label_extra_count + 2, label_extra_count + 3
);
label_extra_count += 4;
}
19
Source : obfuscator.cs
with MIT License
from aaaddress1
with MIT License
from aaaddress1
public static bool obfuscaAsm(string asmPath, string outObfAsmPath)
{
label_extra_count = 0;
junk_count = 0;
obfuscat_code_count = 0;
string asmCode = System.IO.File.ReadAllText(asmPath);
string[] gadgets = asmCode.Split('\n');
string fixCode = "";
string extCode = ".section .text$junk,\x22wx\x22\n";
string currFuncNameMatch = "";
for (int i = 0; i < gadgets.Length; i++)
{
Program.mainUi.BeginInvoke((MethodInvoker)delegate () { Program.mainUi.percntLB.Text = (i * 100 / gadgets.Length) + "%"; });
var currLine = gadgets[i];
Match m = new Regex(@"(.+):\r").Match(gadgets[i]);
if (m.Success && i < gadgets.Length - 2)
{
currFuncNameMatch = m.Groups[1].Value;
if (gadgets[i + 2].Contains("cfi_startproc"))
{
logMsg("found func::" + currFuncNameMatch + "() at #" + i, Color.Blue);
fixCode += gadgets[i] + "\n\r" + gadgets[i + 1] + "\n\r" + gadgets[i + 2] + "\n\r";
i += 2;
continue;
}
else currFuncNameMatch = "";
}
if (currFuncNameMatch != "")
{
string getJunk = "", getExtra = "";
if (Properties.Settings.Default.cnfseCode)
{
obfuscatCode(gadgets[i], ref getJunk, ref getExtra);
fixCode += getJunk;
extCode += getExtra;
}
else
fixCode += gadgets[i] + "\n\r";
getJunk = ""; getExtra = "";
if (Properties.Settings.Default.insrtJunk)
{
randJunk(ref getJunk, ref getExtra);
fixCode += getJunk;
extCode += getExtra;
if (gadgets[i].Contains("cfi_endproc")) currFuncNameMatch = "";
}
}
else
fixCode += gadgets[i] + "\n\r";
}
Program.mainUi.BeginInvoke((MethodInvoker)delegate () { Program.mainUi.percntLB.Text = "100%"; });
logMsg(string.Format(
"[\tOK\t] obfuscate result: \n" +
" - generate {0} junk codes \n" +
" - generate {1} obfuscated codes \n" +
" - generate {2} function pieces \n", junk_count, obfuscat_code_count, label_extra_count), Color.Green);
System.IO.File.WriteAllText(outObfAsmPath, fixCode + "\n" + extCode);
return true;
}
19
Source : GltfUtility.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
private static string GetJsonObject(string jsonString, string handle)
{
var regex = new Regex($"\"{handle}\"\\s*:\\s*\\{{");
var match = regex.Match(jsonString);
return match.Success ? GetJsonObject(jsonString, match.Index + match.Length) : null;
}
19
Source : AndroidVideoEditorUtil.cs
with MIT License
from absurd-joy
with MIT License
from 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
Source : StringExtensions.cs
with MIT License
from Accelerider
with MIT License
from Accelerider
public static string GetMatch(this string text, string p1, string p2)
{
var rg = new Regex("(?<=(" + p1 + "))[.\\s\\S]*?(?=(" + p2 + "))",
RegexOptions.Multiline | RegexOptions.Singleline);
return rg.Match(text).Value;
}
19
Source : GenericInterface.cs
with MIT License
from Accelerider
with MIT License
from Accelerider
private static DelegateType GetDelegateType<TDelegate>()
{
var actionMatch = ActionDelegateRegex.Match(typeof(TDelegate).FullName ?? throw new InvalidOperationException());
if (actionMatch.Success)
{
return actionMatch.Groups.Count > 1 ? DelegateType.ActionWithParams : DelegateType.Action;
}
var funcMatch = FuncDelegateRegex.Match(typeof(TDelegate).FullName ?? throw new InvalidOperationException());
if (funcMatch.Success)
{
return int.Parse(actionMatch.Groups[1].Value) > 1 ? DelegateType.FuncWithParams : DelegateType.Func;
}
return DelegateType.NotSupported;
}
19
Source : UpgradeTaskBase.cs
with MIT License
from Accelerider
with MIT License
from Accelerider
protected virtual IEnumerable<(Version Version, string Path)> GetLocalVersions()
{
return from folderPath in Directory.GetDirectories(InstallDirectory)
let folderName = Path.GetFileName(folderPath)
where !string.IsNullOrEmpty(folderName)
let match = _versionRegex.Match(folderName)
where match.Success
select (Version.Parse(match.Groups[1].Value), folderPath);
}
19
Source : Program.cs
with MIT License
from Accelerider
with MIT License
from Accelerider
private static IEnumerable<BinDirectory> GetBinDirectories(string path)
{
return from directory in Directory.GetDirectories(path)
let match = BinDirectoryRegex.Match(Path.GetFileName(directory) ?? string.Empty)
where match.Success
select new BinDirectory(Version.Parse(match.Groups[1].Value), directory);
}
19
Source : Extensions.cs
with MIT License
from Accelerider
with MIT License
from Accelerider
public static string ReplaceVersionPlaceholder(this string path, string sourcePath = null)
{
var match = VersionPlaceholderRegex.Match(path);
return match.Success
? path.Replace(match.Value, replacedemblyName
.GetreplacedemblyName(sourcePath == null
? match.Groups[1].Value
: Path.Combine(sourcePath, match.Groups[1].Value))
.Version
.ToString(3))
: path;
}
19
Source : DockerCommandManager.cs
with MIT License
from actions
with MIT License
from actions
public async Task<DockerVersion> DockerVersion(IExecutionContext context)
{
string serverVersionStr = (await ExecuteDockerCommandAsync(context, "version", "--format '{{.Server.APIVersion}}'")).FirstOrDefault();
ArgUtil.NotNullOrEmpty(serverVersionStr, "Docker.Server.Version");
context.Output($"Docker daemon API version: {serverVersionStr}");
string clientVersionStr = (await ExecuteDockerCommandAsync(context, "version", "--format '{{.Client.APIVersion}}'")).FirstOrDefault();
ArgUtil.NotNullOrEmpty(serverVersionStr, "Docker.Client.Version");
context.Output($"Docker client API version: {clientVersionStr}");
// we interested about major.minor.patch version
Regex verRegex = new Regex("\\d+\\.\\d+(\\.\\d+)?", RegexOptions.IgnoreCase);
Version serverVersion = null;
var serverVersionMatchResult = verRegex.Match(serverVersionStr);
if (serverVersionMatchResult.Success && !string.IsNullOrEmpty(serverVersionMatchResult.Value))
{
if (!Version.TryParse(serverVersionMatchResult.Value, out serverVersion))
{
serverVersion = null;
}
}
Version clientVersion = null;
var clientVersionMatchResult = verRegex.Match(serverVersionStr);
if (clientVersionMatchResult.Success && !string.IsNullOrEmpty(clientVersionMatchResult.Value))
{
if (!Version.TryParse(clientVersionMatchResult.Value, out clientVersion))
{
clientVersion = null;
}
}
return new DockerVersion(serverVersion, clientVersion);
}
19
Source : IssueMatcher.cs
with MIT License
from actions
with MIT License
from actions
public IssueMatch Match(string line)
{
// Single pattern
if (_patterns.Length == 1)
{
var pattern = _patterns[0];
var regexMatch = pattern.Regex.Match(line);
if (regexMatch.Success)
{
return new IssueMatch(null, pattern, regexMatch.Groups, DefaultSeverity);
}
return null;
}
// Multiple patterns
else
{
// Each pattern (iterate in reverse)
for (int i = _patterns.Length - 1; i >= 0; i--)
{
var runningMatch = i > 0 ? _state[i - 1] : null;
// First pattern or a running match
if (i == 0 || runningMatch != null)
{
var pattern = _patterns[i];
var isLast = i == _patterns.Length - 1;
var regexMatch = pattern.Regex.Match(line);
// Matched
if (regexMatch.Success)
{
// Last pattern
if (isLast)
{
// Loop
if (pattern.Loop)
{
// Clear most state, but preserve the running match
Reset();
_state[i - 1] = runningMatch;
}
// Not loop
else
{
// Clear the state
Reset();
}
// Return
return new IssueMatch(runningMatch, pattern, regexMatch.Groups, DefaultSeverity);
}
// Not the last pattern
else
{
// Store the match
_state[i] = new IssueMatch(runningMatch, pattern, regexMatch.Groups);
}
}
// Not matched
else
{
// Last pattern
if (isLast)
{
// Break the running match
_state[i - 1] = null;
}
// Not the last pattern
else
{
// Record not matched
_state[i] = null;
}
}
}
}
return null;
}
}
19
Source : ExpressionToken.cs
with MIT License
from actions
with MIT License
from actions
internal static Boolean IsValidExpression(
String expression,
String[] allowedContext,
out Exception ex)
{
// Create dummy named values and functions
var namedValues = new List<INamedValueInfo>();
var functions = new List<IFunctionInfo>();
if (allowedContext?.Length > 0)
{
foreach (var contexreplacedem in allowedContext)
{
var match = s_function.Match(contexreplacedem);
if (match.Success)
{
var functionName = match.Groups[1].Value;
var minParameters = Int32.Parse(match.Groups[2].Value, NumberStyles.None, CultureInfo.InvariantCulture);
var maxParametersRaw = match.Groups[3].Value;
var maxParameters = String.Equals(maxParametersRaw, TemplateConstants.MaxConstant, StringComparison.Ordinal)
? Int32.MaxValue
: Int32.Parse(maxParametersRaw, NumberStyles.None, CultureInfo.InvariantCulture);
functions.Add(new FunctionInfo<DummyFunction>(functionName, minParameters, maxParameters));
}
else
{
namedValues.Add(new NamedValueInfo<ContextValueNode>(contexreplacedem));
}
}
}
// Parse
Boolean result;
ExpressionNode root = null;
try
{
root = new ExpressionParser().CreateTree(expression, null, namedValues, functions) as ExpressionNode;
result = true;
ex = null;
}
catch (Exception exception)
{
result = false;
ex = exception;
}
return result;
}
19
Source : RegexUtility.cs
with MIT License
from actions
with MIT License
from actions
public static bool IsMatch(
String value,
String wellKnownRegexKey)
{
Lazy<Regex> lazyRegex = WellKnownRegularExpressions.GetRegex(wellKnownRegexKey);
if (lazyRegex == null)
{
return true;
}
Regex regex = lazyRegex.Value;
return IsSafeMatch(value, x => regex.Match(value));
}
19
Source : GitCliManager.cs
with MIT License
from actions
with MIT License
from actions
public async Task<Version> GitVersion(RunnerActionPluginExecutionContext context)
{
context.Debug("Get git version.");
string runnerWorkspace = context.GetRunnerContext("workspace");
ArgUtil.Directory(runnerWorkspace, "runnerWorkspace");
Version version = null;
List<string> outputStrings = new List<string>();
int exitCode = await ExecuteGitCommandAsync(context, runnerWorkspace, "version", null, outputStrings);
context.Output($"{string.Join(Environment.NewLine, outputStrings)}");
if (exitCode == 0)
{
// remove any empty line.
outputStrings = outputStrings.Where(o => !string.IsNullOrEmpty(o)).ToList();
if (outputStrings.Count == 1 && !string.IsNullOrEmpty(outputStrings.First()))
{
string verString = outputStrings.First();
// we interested about major.minor.patch version
Regex verRegex = new Regex("\\d+\\.\\d+(\\.\\d+)?", RegexOptions.IgnoreCase);
var matchResult = verRegex.Match(verString);
if (matchResult.Success && !string.IsNullOrEmpty(matchResult.Value))
{
if (!Version.TryParse(matchResult.Value, out version))
{
version = null;
}
}
}
}
return version;
}
19
Source : GitCliManager.cs
with MIT License
from actions
with MIT License
from actions
public async Task<Version> GitLfsVersion(RunnerActionPluginExecutionContext context)
{
context.Debug("Get git-lfs version.");
string runnerWorkspace = context.GetRunnerContext("workspace");
ArgUtil.Directory(runnerWorkspace, "runnerWorkspace");
Version version = null;
List<string> outputStrings = new List<string>();
int exitCode = await ExecuteGitCommandAsync(context, runnerWorkspace, "lfs version", null, outputStrings);
context.Output($"{string.Join(Environment.NewLine, outputStrings)}");
if (exitCode == 0)
{
// remove any empty line.
outputStrings = outputStrings.Where(o => !string.IsNullOrEmpty(o)).ToList();
if (outputStrings.Count == 1 && !string.IsNullOrEmpty(outputStrings.First()))
{
string verString = outputStrings.First();
// we interested about major.minor.patch version
Regex verRegex = new Regex("\\d+\\.\\d+(\\.\\d+)?", RegexOptions.IgnoreCase);
var matchResult = verRegex.Match(verString);
if (matchResult.Success && !string.IsNullOrEmpty(matchResult.Value))
{
if (!Version.TryParse(matchResult.Value, out version))
{
version = null;
}
}
}
}
return version;
}
19
Source : WordHighlightTagger.cs
with MIT License
from Actipro
with MIT License
from Actipro
private void UpdateCurrentWord() {
if ((view == null) || (view.Selection == null))
return;
// Save the old current word
string oldCurrentWord = currentWord;
// Get the current word and ensure it has only letter or number characters
currentWord = view.GetCurrentWordText().Trim();
Match match = wordCheck.Match(currentWord);
if ((match == null) || (match.Index != 0) || (match.Length != currentWord.Length))
currentWord = String.Empty;
// If the current word changed...
if (oldCurrentWord != currentWord) {
// Notify that tags changed
// NOTE: You generally want to minimize the range preplaceded to TagsChanged events, but in this case we don't know beforehand where word matches are made throughout the doreplacedent
this.OnTagsChanged(new TagsChangedEventArgs(new TextSnapshotRange(view.SyntaxEditor.Doreplacedent.CurrentSnapshot, view.SyntaxEditor.Doreplacedent.CurrentSnapshot.TextRange)));
}
}
19
Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence
static void Main(string[] args)
{
bool DonotLoadGrid = true;
var grid = new List<IList<double>>();
if (!DonotLoadGrid)
{
Console.WriteLine("Loading Stream: " + DateTime.Now.ToString());
var sr = new StreamReader(@"C:\data\table.csv");
while (!sr.EndOfStream)
{
var line = sr.ReadLine();
var fieldValues = line.Split(',');
var fields = new List<double>();
var rdm = new Random(100000);
foreach (var field in fieldValues)
{
var res = 0d;
var add = double.TryParse(field, out res) == true ? res : rdm.NextDouble();
fields.Add(add);
}
grid.Add(fields);
}
Console.WriteLine("Grid loaded successfully!! " + DateTime.Now.ToString());
}
var keepProcessing = true;
while (keepProcessing)
{
Console.WriteLine(DateTime.Now.ToString());
Console.WriteLine("Enter Expression:");
var expression = Console.ReadLine();
if (expression.ToLower() == "exit")
{
keepProcessing = false;
}
else
{
try
{
if(expression.Equals("zspread"))
{
var result = ConnectedInstruction.GetZSpread(grid,3,503);
}
if (expression.Substring(0, 19).ToLower().Equals("logisticregression "))
{
keepProcessing = true;
var paths = expression.Split(' ');
#region Python
var script =@"
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.cross_validation import train_test_split
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
creditData = pd.read_csv("+paths[1]+@")
print(creditData.head())
print(creditData.describe())
print(creditData.corr())
features = creditData[['income', 'age', 'loan']]
target = creditData.default
feature_train, feature_test, target_train, target_test = train_test_split(features, target, test_size = 0.3)
model = LogisticRegression()
model.fit = model.fit(feature_train, target_train)
predictions = model.fit.predict(feature_test)
print(confusion_matrix(target_test, predictions))
print(accuracy_score(target_test, predictions))
";
var sw = new StreamWriter(@"c:\data\logistic.py");
sw.Write(script);
sw.Close();
#endregion
ProcessStartInfo start = new ProcessStartInfo();
Console.WriteLine("Starting Python Engine...");
start.FileName = @"C:\Users\rajiyer\PycharmProjects\TestPlot\venv\Scripts\python.exe";
start.Arguments = string.Format("{0} {1}", @"c:\data\logistic.py", args);
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
Console.WriteLine("Starting Process..."+ DateTime.Now.ToString());
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
string result = reader.ReadToEnd();
Console.Write(result);
}
}
Console.WriteLine("Process Succeeded..." + DateTime.Now.ToString());
}
if(expression.Substring(0,12) == "videoreplacedyse")
{
#region python
var python = @"
from keras.preprocessing.image import img_to_array
import imutils
import cv2
from keras.models import load_model
import numpy as np
import geocoder
#import mysql.connector as con
#mydb = con.connect(
# host=""localhost"",
# user=""yourusername"",
# preplacedwd=""yourpreplacedword"",
# database=""mydatabase""
#)
#mycursor = mydb.cursor()
g = geocoder.ip('me')
# parameters for loading data and images
detection_model_path = 'C:\\Users\\rajiyer\\Doreplacedents\\Test Data\\Sentiment replacedysis\\Emotion-recognition-master\\haarcascade_files\\haarcascade_frontalface_default.xml'
emotion_model_path = 'C:\\Users\\rajiyer\\Doreplacedents\\Test Data\\Sentiment replacedysis\\Emotion-recognition-master\\models\\_mini_XCEPTION.102-0.66.hdf5'
# hyper-parameters for bounding boxes shape
# loading models
face_detection = cv2.CascadeClreplacedifier(detection_model_path)
emotion_clreplacedifier = load_model(emotion_model_path, compile = False)
EMOTIONS = [""angry"", ""disgust"", ""scared"", ""happy"", ""sad"", ""surprised"",
""neutral""]
# feelings_faces = []
# for index, emotion in enumerate(EMOTIONS):
# feelings_faces.append(cv2.imread('emojis/' + emotion + '.png', -1))
# starting video streaming
cv2.namedWindow('your_face')
camera = cv2.VideoCapture(0)
f = open(""C:\\Users\\rajiyer\\Doreplacedents\\Test Data\\Probability.txt"", ""a+"")
while True:
frame = camera.read()[1]
#reading the frame
frame = imutils.resize(frame, width = 300)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_detection.detectMultiScale(gray, scaleFactor = 1.1, minNeighbors = 5, minSize = (30, 30), flags = cv2.CASCADE_SCALE_IMAGE)
canvas = np.zeros((250, 300, 3), dtype = ""uint8"")
frameClone = frame.copy()
if len(faces) > 0:
faces = sorted(faces, reverse = True,
key = lambda x: (x[2] - x[0]) * (x[3] - x[1]))[0]
(fX, fY, fW, fH) = faces
# Extract the ROI of the face from the grayscale image, resize it to a fixed 28x28 pixels, and then prepare
# the ROI for clreplacedification via the CNN
roi = gray[fY: fY + fH, fX: fX + fW]
roi = cv2.resize(roi, (64, 64))
roi = roi.astype(""float"") / 255.0
roi = img_to_array(roi)
roi = np.expand_dims(roi, axis = 0)
preds = emotion_clreplacedifier.predict(roi)[0]
emotion_probability = np.max(preds)
label = EMOTIONS[preds.argmax()]
else: continue
for (i, (emotion, prob)) in enumerate(zip(EMOTIONS, preds)):
# construct the label text
text = ""{}: {:.2f}%"".format(emotion, prob * 100)
#sql = ""INSERT INTO predData (Metadata, Probability) VALUES (%s, %s)""
#val = (""Meta"", prob * 100)
f.write(text)
#str1 = ''.join(str(e) for e in g.latlng)
#f.write(str1)
#mycursor.execute(sql, val)
#mydb.commit()
# draw the label + probability bar on the canvas
# emoji_face = feelings_faces[np.argmax(preds)]
w = int(prob * 300)
cv2.rectangle(canvas, (7, (i * 35) + 5),
(w, (i * 35) + 35), (0, 0, 255), -1)
cv2.putText(canvas, text, (10, (i * 35) + 23),
cv2.FONT_HERSHEY_SIMPLEX, 0.45,
(255, 255, 255), 2)
cv2.putText(frameClone, label, (fX, fY - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 2)
cv2.rectangle(frameClone, (fX, fY), (fX + fW, fY + fH),
(0, 0, 255), 2)
# for c in range(0, 3):
# frame[200:320, 10:130, c] = emoji_face[:, :, c] * \
# (emoji_face[:, :, 3] / 255.0) + frame[200:320,
# 10:130, c] * (1.0 - emoji_face[:, :, 3] / 255.0)
cv2.imshow('your_face', frameClone)
cv2.imshow(""Probabilities"", canvas)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
camera.release()
cv2.destroyAllWindows()
";
var sw = new StreamWriter(@"c:\data\face.py");
sw.Write(python);
sw.Close();
#endregion
ProcessStartInfo start = new ProcessStartInfo();
Console.WriteLine("Starting Python Engine...");
start.FileName = @"C:\Users\rajiyer\PycharmProjects\TestPlot\venv\Scripts\python.exe";
start.Arguments = string.Format("{0} {1}", @"c:\data\face.py", args);
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
Console.WriteLine("Starting Process..." + DateTime.Now.ToString());
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
string result = reader.ReadToEnd();
Console.Write(result);
}
}
Console.WriteLine("Process Succeeded..." + DateTime.Now.ToString());
}
if (expression.Substring(0,12).ToLower().Equals("kaplanmeier "))
{
keepProcessing = true;
var columnsOfconcern = expression.Split(' ');
Console.WriteLine("Preparing...");
var observations = new List<PairedObservation>();
var ca = GetColumn(grid,int.Parse(columnsOfconcern[1]));
var cb = GetColumn(grid, int.Parse(columnsOfconcern[2]));
var cc = GetColumn(grid, int.Parse(columnsOfconcern[3]));
for(int i=0;i<ca.Count;i++)
{
observations.Add(new PairedObservation((decimal)ca[i], (decimal)cb[i], (decimal)cc[i]));
}
var kp = new KaplanMeier(observations);
}
if (expression.Equals("write"))
{
keepProcessing = true;
ConnectedInstruction.WritetoCsvu(grid, @"c:\data\temp.csv");
}
if (expression.Substring(0, 9) == "getvalue(")
{
keepProcessing = true;
Regex r = new Regex(@"\(([^()]+)\)*");
var res = r.Match(expression);
var val = res.Value.Split(',');
try
{
var gridVal = grid[int.Parse(val[0].Replace("(", "").Replace(")", ""))]
[int.Parse(val[1].Replace("(", "").Replace(")", ""))];
Console.WriteLine(gridVal.ToString() + "\n");
}
catch (ArgumentOutOfRangeException)
{
Console.WriteLine("Hmmm,... apologies, can't seem to find that within range...");
}
}
else
{
keepProcessing = true;
Console.WriteLine("Process Begin:" + DateTime.Now.ToString());
var result = ConnectedInstruction.ParseExpressionAndRunAgainstInMemmoryModel(grid, expression);
Console.WriteLine("Process Ended:" + DateTime.Now.ToString());
}
}
catch (ArgumentOutOfRangeException)
{
}
}
}
}
19
Source : ConformanceTests.cs
with MIT License
from adamant
with MIT License
from adamant
private static int ExpectedExitCode(string code)
{
var exitCode = ExitCodePattern.Match(code).Groups["exitCode"]?.Captures.SingleOrDefault()?.Value ?? "0";
return int.Parse(exitCode, CultureInfo.InvariantCulture);
}
19
Source : WebsiteManager.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static bool MatchSiteName(string bindingSiteName, string siteName)
{
// match a binding by site name and virtual path
// Azure Compute Emulator uses a format containing the role instance id and solution name
// example: deployment18(9).MasterPortalAzure.MasterPortal_IN_1_Adxstudio Portals
// Azure proper uses a format containing the role instance id but without the solution prefix
// example: MasterPortal_IN_1_Adxstudio Portals
// Creplacedini may append a numeric suffix which should be filtered out
// example: CommunityPortal(1)
if (string.IsNullOrWhiteSpace(bindingSiteName)) return false;
var match = siteNamePattern.Match(siteName);
var filteredSiteName = match.Success && match.Groups["site"].Success ? match.Groups["site"].Value : siteName;
var mask = new Mask(bindingSiteName, RegexOptions.IgnoreCase);
return mask.IsMatch(filteredSiteName);
}
19
Source : CrmChart.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private void ReplacePresentationDescriptionOptionSetPlaceholders(XElement element, string attributeName, OrganizationServiceContext serviceContext)
{
var attribute = element.Attribute(attributeName);
if (attribute == null)
{
return;
}
var placeholderMatch = OptionSetPatternRegex.Match(attribute.Value);
if (placeholderMatch.Success)
{
attribute.SetValue(this.ReplacePresentationDescriptionOptionSetPlaceholderMatch(placeholderMatch, serviceContext));
}
}
19
Source : Mask.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public virtual Match Match(string input)
{
return InnerRegex.Match(input);
}
19
Source : CmsEntityRelationshipHandler.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
protected override void ProcessRequest(HttpContext context, ICmsEnreplacedyServiceProvider serviceProvider, Guid portalScopeId, IPortalContext portal, OrganizationServiceContext serviceContext, Enreplacedy enreplacedy, CmsEnreplacedyMetadata enreplacedyMetadata, ICrmEnreplacedySecurityProvider security)
{
var relationshipSchemaName = string.IsNullOrWhiteSpace(RelationshipSchemaName) ? context.Request.Params["relationshipSchemaName"] : RelationshipSchemaName;
if (string.IsNullOrWhiteSpace(relationshipSchemaName))
{
throw new CmsEnreplacedyServiceException(HttpStatusCode.BadRequest, "Unable to determine enreplacedy relationship schema name from request.");
}
var match = _relationshipSchemaNameRegex.Match(relationshipSchemaName);
if (!match.Success)
{
throw new CmsEnreplacedyServiceException(HttpStatusCode.BadRequest, "Unable to determine enreplacedy relationship schema name from request.");
}
var schemaName = match.Groups["schemaName"].Value;
if (string.IsNullOrWhiteSpace(schemaName))
{
throw new CmsEnreplacedyServiceException(HttpStatusCode.BadRequest, "Unable to determine enreplacedy relationship schema name from request.");
}
var enreplacedyRole = match.Groups["enreplacedyRole"].Value;
EnreplacedyRole parsedRole;
var relationship = new Relationship(schemaName)
{
PrimaryEnreplacedyRole = Enum.TryParse(enreplacedyRole, true, out parsedRole) ? new EnreplacedyRole?(parsedRole) : null
};
CmsEnreplacedyRelationshipInfo relationshipInfo;
if (!enreplacedyMetadata.TryGetRelationshipInfo(relationship, out relationshipInfo))
{
throw new CmsEnreplacedyServiceException(HttpStatusCode.NotFound, "Enreplacedy relationship not found.");
}
// If the current request enreplacedy is the current website, do security handling here, since we skipped it earlier.
if (enreplacedy.ToEnreplacedyReference().Equals(portal.Website.ToEnreplacedyReference()))
{
replacedertRequestEnreplacedySecurity(portal, serviceContext, enreplacedy, security, CreateWebsiteAccessPermissionProvider(portal), relationshipInfo);
}
if (IsRequestMethod(context.Request, "GET"))
{
if (relationshipInfo.IsCollection)
{
var readableRelatedEnreplacedies = enreplacedy.GetRelatedEnreplacedies(serviceContext, relationship)
.Where(e => security.Tryreplacedert(serviceContext, e, CrmEnreplacedyRight.Read));
var enreplacedyMetadataLookup = new Dictionary<string, CmsEnreplacedyMetadata>();
var enreplacedyJsonObjects = readableRelatedEnreplacedies.Select(e =>
{
CmsEnreplacedyMetadata relatedEnreplacedyMetadata;
if (!enreplacedyMetadataLookup.TryGetValue(e.LogicalName, out relatedEnreplacedyMetadata))
{
relatedEnreplacedyMetadata = new CmsEnreplacedyMetadata(serviceContext, e.LogicalName);
enreplacedyMetadataLookup[e.LogicalName] = relatedEnreplacedyMetadata;
}
return GetEnreplacedyJson(context, serviceProvider, portalScopeId, portal, serviceContext, e, relatedEnreplacedyMetadata);
});
WriteResponse(context.Response, new JObject
{
{ "d", new JArray(enreplacedyJsonObjects) }
});
}
else
{
var relatedEnreplacedy = enreplacedy.GetRelatedEnreplacedy(serviceContext, relationship);
if (relatedEnreplacedy == null)
{
throw new CmsEnreplacedyServiceException(HttpStatusCode.NotFound, "Related enreplacedy not found.");
}
if (!security.Tryreplacedert(serviceContext, relatedEnreplacedy, CrmEnreplacedyRight.Read))
{
throw new CmsEnreplacedyServiceException(HttpStatusCode.Forbidden, "Related enreplacedy access denied.");
}
WriteResponse(context.Response, new JObject
{
{ "d", GetEnreplacedyJson(context, serviceProvider, portalScopeId, portal, serviceContext, relatedEnreplacedy, new CmsEnreplacedyMetadata(serviceContext, relatedEnreplacedy.LogicalName)) }
});
}
return;
}
if (IsRequestMethod(context.Request, "POST"))
{
if (relationshipInfo.IsCollection)
{
OneToManyRelationshipMetadata relationshipMetadata;
if (!enreplacedyMetadata.TryGetOneToManyRelationshipMetadata(relationship, out relationshipMetadata))
{
throw new CmsEnreplacedyServiceException(HttpStatusCode.BadRequest, "Unable to retrieve the one-to-many relationship metadata for relationship {0} on enreplacedy type".FormatWith(relationship.ToSchemaName("."), enreplacedy.LogicalName));
}
var relatedEnreplacedy = CreateEnreplacedyOfType(serviceContext, relationshipMetadata.ReferencingEnreplacedy);
var relatedEnreplacedyMetadata = new CmsEnreplacedyMetadata(serviceContext, relatedEnreplacedy.LogicalName);
var extensions = UpdateEnreplacedyFromJsonRequestBody(context.Request, serviceContext, relatedEnreplacedy, relatedEnreplacedyMetadata);
var preImage = relatedEnreplacedy.Clone(false);
// Ensure the reference to the target enreplacedy is set.
relatedEnreplacedy.SetAttributeValue(relationshipMetadata.ReferencingAttribute, new EnreplacedyReference(enreplacedy.LogicalName, enreplacedy.GetAttributeValue<Guid>(relationshipMetadata.ReferencedAttribute)));
serviceProvider.InterceptChange(context, portal, serviceContext, relatedEnreplacedy, relatedEnreplacedyMetadata, CmsEnreplacedyOperation.Create, preImage);
serviceContext.AddObject(relatedEnreplacedy);
serviceProvider.InterceptExtensionChange(context, portal, serviceContext, relatedEnreplacedy, relatedEnreplacedyMetadata, extensions, CmsEnreplacedyOperation.Create);
serviceContext.SaveChanges();
var refetchedEnreplacedy = serviceContext.CreateQuery(relatedEnreplacedy.LogicalName)
.FirstOrDefault(e => e.GetAttributeValue<Guid>(relatedEnreplacedyMetadata.PrimaryIdAttribute) == relatedEnreplacedy.Id);
if (refetchedEnreplacedy == null)
{
throw new CmsEnreplacedyServiceException(HttpStatusCode.InternalServerError, "Unable to retrieve the created enreplacedy.");
}
WriteResponse(context.Response, new JObject
{
{ "d", GetEnreplacedyJson(context, serviceProvider, portalScopeId, portal, serviceContext, refetchedEnreplacedy, relatedEnreplacedyMetadata) }
}, HttpStatusCode.Created);
}
else
{
OneToManyRelationshipMetadata relationshipMetadata;
if (!enreplacedyMetadata.TryGetManyToOneRelationshipMetadata(relationship, out relationshipMetadata))
{
throw new CmsEnreplacedyServiceException(HttpStatusCode.BadRequest, "Unable to retrieve the many-to-one relationship metadata for relationship {0} on enreplacedy type".FormatWith(relationship.ToSchemaName("."), enreplacedy.LogicalName));
}
var relatedEnreplacedy = CreateEnreplacedyOfType(serviceContext, relationshipMetadata.ReferencedEnreplacedy);
var relatedEnreplacedyMetadata = new CmsEnreplacedyMetadata(serviceContext, relatedEnreplacedy.LogicalName);
var extensions = UpdateEnreplacedyFromJsonRequestBody(context.Request, serviceContext, relatedEnreplacedy, relatedEnreplacedyMetadata);
serviceProvider.InterceptChange(context, portal, serviceContext, relatedEnreplacedy, relatedEnreplacedyMetadata, CmsEnreplacedyOperation.Create);
serviceContext.AddObject(relatedEnreplacedy);
serviceContext.AddLink(relatedEnreplacedy, relationship, enreplacedy);
serviceProvider.InterceptExtensionChange(context, portal, serviceContext, relatedEnreplacedy, relatedEnreplacedyMetadata, extensions, CmsEnreplacedyOperation.Create);
serviceContext.SaveChanges();
var refetchedEnreplacedy = serviceContext.CreateQuery(relatedEnreplacedy.LogicalName)
.FirstOrDefault(e => e.GetAttributeValue<Guid>(relatedEnreplacedyMetadata.PrimaryIdAttribute) == relatedEnreplacedy.Id);
if (refetchedEnreplacedy == null)
{
throw new CmsEnreplacedyServiceException(HttpStatusCode.InternalServerError, "Unable to retrieve the created enreplacedy.");
}
WriteResponse(context.Response, new JObject
{
{ "d", GetEnreplacedyJson(context, serviceProvider, portalScopeId, portal, serviceContext, refetchedEnreplacedy, relatedEnreplacedyMetadata) }
}, HttpStatusCode.Created);
}
return;
}
throw new CmsEnreplacedyServiceException(HttpStatusCode.MethodNotAllowed, "Request method {0} not allowed for this resource.".FormatWith(context.Request.HttpMethod));
}
19
Source : KnowledgeArticleDataAdapter.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private KeyValuePair<ReferrerType, string> GetReferrerTypeAndHost(Uri urlReferrer)
{
var portalHostName = string.Empty;
var url = GetPortalUrl("Search");
if (urlReferrer == null)
{
if (url != null)
{
portalHostName = url.Host;
}
return new KeyValuePair<ReferrerType, string>(ReferrerType.DirectLink, portalHostName);
}
// GetPortalUrl(...) will return URL without language code prefix, so in order to make comparison work, need to (if necessary) strip out
// language code prefix from urlReferrer as well.
string absoluteUri;
var contextLanguageInfo = HttpContext.Current.GetContextLanguageInfo();
if (contextLanguageInfo.IsCrmMultiLanguageEnabled)
{
absoluteUri = contextLanguageInfo.StripLanguageCodeFromAbsolutePath(urlReferrer.PathAndQuery);
}
else
{
absoluteUri = urlReferrer.AbsoluteUri;
}
if (url != null)
{
portalHostName = url.Host;
if (absoluteUri.Contains(url.Uri.ToString()))
{
return new KeyValuePair<ReferrerType, string>(ReferrerType.PortalSearch, url.Host);
}
}
url = GetPortalUrl("Create Case");
if (url != null)
{
portalHostName = url.Host;
if (absoluteUri.Contains(url.Uri.ToString()))
{
return new KeyValuePair<ReferrerType, string>(ReferrerType.PortalCaseDeflectionSearch, url.Host);
}
}
if (!string.IsNullOrEmpty(portalHostName))
{
if (absoluteUri.Contains(portalHostName))
{
return new KeyValuePair<ReferrerType, string>(ReferrerType.Browse, portalHostName);
}
}
var regEx = new Regex(ExternalSearchEngineString, RegexOptions.IgnoreCase);
var isSearch = regEx.Match(absoluteUri).Success;
return isSearch ? new KeyValuePair<ReferrerType, string>(ReferrerType.ExternalSearchEngine, portalHostName) : new KeyValuePair<ReferrerType, string>(ReferrerType.ExternalWebsite, portalHostName);
}
19
Source : LocalizedScripts.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static string GetLocalizedBundleName(string input, int cultureLcid)
{
if (string.IsNullOrEmpty(input))
{
return input;
}
// Adding lcid before .bundle.XXX because otherwise routing rule will be not satisfied
var match = BundleNameRegex.Match(input);
if (!match.Success)
{
throw new InvalidOperationException("Invalid name template. Should ends with .bundle.XXX");
}
var name = match.Groups[1];
var postfix = match.Groups[2];
return string.Format("{0}-{1}{2}", name, cultureLcid, postfix);
}
19
Source : FetchXml.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public override void Initialize(string tagName, string markup, List<string> tokens)
{
var syntaxMatch = Syntax.Match(markup);
if (syntaxMatch.Success)
{
_variableName = syntaxMatch.Groups["variable"].Value.Trim();
_attributes = new Dictionary<string, string>(Template.NamingConvention.StringComparer);
R.Scan(markup, DotLiquid.Liquid.TagAttributes, (key, value) => _attributes[key] = value);
}
else
{
throw new SyntaxException("Syntax Error in '{0}' tag - Valid syntax: {0} [var] (right:[string])", tagName);
}
base.Initialize(tagName, markup, tokens);
}
19
Source : Rating.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public override void Initialize(string tagName, string markup, List<string> tokens)
{
var syntaxMatch = Syntax.Match(markup);
if (syntaxMatch.Success)
{
this.attributes = new Dictionary<string, string>(Template.NamingConvention.StringComparer);
R.Scan(markup, DotLiquid.Liquid.TagAttributes, (key, value) => this.attributes[key] = value);
}
else
{
throw new SyntaxException("Syntax Error in '{0}' tag - Valid syntax: {0} [[var] =] (id:[string]) (enreplacedy:[string]) (readonly:[boolean]) (panel:[boolean]) (snippet:[string]) (step:[string]) (min:[string]) (max:[string]) (round:[boolean])", tagName);
}
base.Initialize(tagName, markup, tokens);
}
19
Source : SearchIndex.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public override void Initialize(string tagName, string markup, List<string> tokens)
{
var syntaxMatch = Syntax.Match(markup);
if (syntaxMatch.Success)
{
_variableName = syntaxMatch.Groups["variable"].Value.Trim();
_attributes = new Dictionary<string, string>(Template.NamingConvention.StringComparer);
R.Scan(markup, DotLiquid.Liquid.TagAttributes, (key, value) => _attributes[key] = value);
}
else
{
throw new SyntaxException(
ResourceManager.GetString("Syntax_Error_In_Tag_And_Valid_Syntax_Is") + "[[var] =] query:[string] (filter:[string]) (logical_names:[string]|[array]) (page:[integer]) (pagesize:[integer]) (provider:[string])",
tagName);
}
base.Initialize(tagName, markup, tokens);
}
19
Source : Chart.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public override void Initialize(string tagName, string markup, List<string> tokens)
{
var syntaxMatch = Syntax.Match(markup);
if (syntaxMatch.Success)
{
this.attributes = new Dictionary<string, string>(Template.NamingConvention.StringComparer);
R.Scan(markup, DotLiquid.Liquid.TagAttributes, (key, value) => this.attributes[key] = value);
}
else
{
throw new SyntaxException("Syntax Error in '{0}' tag - Valid syntax: {0} [[var] =] (id:[string]) (viewid:[string]) (serviceurl:[string])", tagName);
}
base.Initialize(tagName, markup, tokens);
}
19
Source : Editable.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public override void Initialize(string tagName, string markup, List<string> tokens)
{
var syntaxMatch = Syntax.Match(markup);
if (syntaxMatch.Success)
{
_editable = syntaxMatch.Groups["editable"].Value;
_key = syntaxMatch.Groups["key"].Value;
_attributes = new Dictionary<string, string>(Template.NamingConvention.StringComparer);
R.Scan(markup, DotLiquid.Liquid.TagAttributes, (key, value) => _attributes[key] = value);
}
else
{
throw new SyntaxException("Syntax Error in '{0}' tag - Valid syntax: {0} [editable] ([key]) (type:[type])", tagName);
}
base.Initialize(tagName, markup, tokens);
}
19
Source : EntityForm.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public override void Initialize(string tagName, string markup, List<string> tokens)
{
var syntaxMatch = Syntax.Match(markup);
if (syntaxMatch.Success)
{
_attributes = new Dictionary<string, string>(Template.NamingConvention.StringComparer);
R.Scan(markup, DotLiquid.Liquid.TagAttributes, (key, value) => _attributes[key] = value);
}
else
{
throw new SyntaxException("Syntax Error in '{0}' tag - Valid syntax: {0} [[var] =] (name:[string] | id:[string] | key:[string]) (languagecode:[integer])", tagName);
}
base.Initialize(tagName, markup, tokens);
}
19
Source : EntityList.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public override void Initialize(string tagName, string markup, List<string> tokens)
{
var syntaxMatch = Syntax.Match(markup);
if (syntaxMatch.Success)
{
_variableName = syntaxMatch.Groups["variable"].Value.Trim();
_attributes = new Dictionary<string, string>(Template.NamingConvention.StringComparer);
R.Scan(markup, DotLiquid.Liquid.TagAttributes, (key, value) => _attributes[key] = value);
}
else
{
throw new SyntaxException("Syntax Error in '{0}' tag - Valid syntax: {0} [[var] =] (name:[string] | id:[string] | key:[string]) (languagecode:[integer])", tagName);
}
base.Initialize(tagName, markup, tokens);
}
See More Examples