Here are the examples of the csharp api string.TrimStart(params char[]) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2337 Examples
19
View Source File : SQLite.cs
License : GNU General Public License v3.0
Project Creator : 0xfd3
License : GNU General Public License v3.0
Project Creator : 0xfd3
public bool ReadTable(string TableName)
{
int index = -1;
int length = this.master_table_entries.Length - 1;
for (int i = 0; i <= length; i++)
{
if (this.master_table_entries[i].item_name.ToLower().CompareTo(TableName.ToLower()) == 0)
{
index = i;
break;
}
}
if (index == -1)
{
return false;
}
string[] strArray = this.master_table_entries[index].sql_statement.Substring(this.master_table_entries[index].sql_statement.IndexOf("(") + 1).Split(new char[] { ',' });
int num6 = strArray.Length - 1;
for (int j = 0; j <= num6; j++)
{
strArray[j] = (strArray[j]).TrimStart();
int num4 = strArray[j].IndexOf(" ");
if (num4 > 0)
{
strArray[j] = strArray[j].Substring(0, num4);
}
if (strArray[j].IndexOf("UNIQUE") == 0)
{
break;
}
this.field_names = (string[])Utils.CopyArray((Array)this.field_names, new string[j + 1]);
this.field_names[j] = strArray[j];
}
return this.ReadTableFromOffset((ulong)((this.master_table_entries[index].root_num - 1L) * this.page_size));
}
19
View Source File : IsoHeaderParser.cs
License : MIT License
Project Creator : 13xforever
License : MIT License
Project Creator : 13xforever
public static (List<FileRecord> files, List<string> dirs) GetFilesystemStructure(this CDReader reader)
{
var fsObjects = reader.GetFileSystemEntries(reader.Root.FullName).ToList();
var nextLevel = new List<string>();
var filePaths = new List<string>();
var dirPaths = new List<string>();
while (fsObjects.Any())
{
foreach (var path in fsObjects)
{
if (reader.FileExists(path))
filePaths.Add(path);
else if (reader.DirectoryExists(path))
{
dirPaths.Add(path);
nextLevel.AddRange(reader.GetFileSystemEntries(path));
}
else
Log.Warn($"Unknown filesystem object: {path}");
}
(fsObjects, nextLevel) = (nextLevel, fsObjects);
nextLevel.Clear();
}
var filenames = filePaths.Distinct().Select(n => n.TrimStart('\\')).ToList();
var dirnames = dirPaths.Distinct().Select(n => n.TrimStart('\\')).OrderByDescending(n => n.Length).ToList();
var deepestDirnames = new List<string>();
foreach (var dirname in dirnames)
{
var tmp = dirname + "\\";
if (deepestDirnames.Any(n => n.StartsWith(tmp)))
continue;
deepestDirnames.Add(dirname);
}
dirnames = deepestDirnames.OrderBy(n => n).ToList();
var dirnamesWithFiles = filenames.Select(Path.GetDirectoryName).Distinct().ToList();
var emptydirs = dirnames.Except(dirnamesWithFiles).ToList();
var fileList = new List<FileRecord>();
foreach (var filename in filenames)
{
var clusterRange = reader.PathToClusters(filename);
if (clusterRange.Length != 1)
Log.Warn($"{filename} is split in {clusterRange.Length} ranges");
if (filename.EndsWith("."))
Log.Warn($"Fixing potential mastering error in {filename}");
fileList.Add(new FileRecord(filename.TrimEnd('.'), clusterRange.Min(r => r.Offset), reader.GetFileLength(filename)));
}
fileList = fileList.OrderBy(r => r.StartSector).ToList();
return (files: fileList, dirs: emptydirs);
}
19
View Source File : EnvironmentVariableReader.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
public static T Get<T>(string variable, T defaultValue = default)
{
var value = Environment.GetEnvironmentVariable(variable);
if (string.IsNullOrWhiteSpace(value))
return defaultValue;
value = value.ReplaceIpPlaceholder();
var matches = Regex.Matches(value, "[{](.*?)[}]");
if (matches.Count > 0)
{
foreach (var match in matches)
{
value = value.Replace(match.ToString(), Environment.GetEnvironmentVariable(match.ToString().TrimStart('{').TrimEnd('}')));
}
}
return (T)Convert.ChangeType(value, typeof(T));
}
19
View Source File : ProxyGenerator.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
private static SyntaxList<MemberDeclarationSyntax> GenerateClreplaced(NamespaceDeclarationSyntax namespaceDeclaration, Type type, string serviceName)
{
var clreplacedName = type.Name.TrimStart('I') + "_____UraganoClientProxy";
//var serviceProviderProperty = SyntaxFactory.PropertyDeclaration(SyntaxFactory.ParseTypeName("IServiceProvider"), " ServiceProvider")
// .AddModifiers(SyntaxFactory.Token(SyntaxKind.PrivateKeyword))
// .AddAccessorListAccessors(
// SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)));
var clreplacedDeclaration = SyntaxFactory.ClreplacedDeclaration(clreplacedName)
.AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword))
.AddBaseListTypes(
SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseTypeName("DynamicProxyAbstract")),
SyntaxFactory.SimpleBaseType(GenerateQualifiedNameSyntax(type)))
//.AddMembers(serviceProviderProperty)
.AddMembers(GenerateMethods(type, clreplacedName, serviceName));
return SyntaxFactory.SingletonList<MemberDeclarationSyntax>(namespaceDeclaration.WithMembers(SyntaxFactory.SingletonList<MemberDeclarationSyntax>(clreplacedDeclaration)));
}
19
View Source File : Form1.cs
License : MIT License
Project Creator : 1y0n
License : MIT License
Project Creator : 1y0n
private string Handle_Payload()
{
//对用户输入的payload进行一些转换处理,方便下一步的加密
string raw_input = textBox1.Text.Trim().Replace("\r\n", "").Replace("\n", "").Replace("\r", ""); //支持多种linux win换行符
string payload_pattern_csharp = @"\{(.+?)\}";
string payload_pattern_c = @"=.*"";$";
string[] raw_payload_array;
if (Regex.IsMatch(raw_input, payload_pattern_c))
{
//c语言格式的shellcode,转成 csharp 格式
raw_input = raw_input.Replace("\"", "").Replace("\\", ",0").Replace(";", "").Replace("=", "{").Replace("{,", "{ ") + " }";
}
string raw_payload = Regex.Matches(raw_input, payload_pattern_csharp)[0].Value.Replace("{", "").Replace("}", "").Trim();
raw_payload = raw_payload.TrimStart(',');
raw_payload_array = raw_payload.Split(',');
List<byte> byte_payload_list = new List<byte>();
foreach (string i in raw_payload_array)
{
byte_payload_list.Add(string_to_int(i));
}
byte[] payload_result = byte_payload_list.ToArray();
//加密payload并转换为字符串,准备写入文件
byte[] encrypted_payload = Encrypter.Encrypt(KEY, payload_result);
string string_encrypted_payload = string.Join(",", encrypted_payload);
//MessageBox.Show(string_encrypted_payload);
return string_encrypted_payload;
}
19
View Source File : Core.cs
License : MIT License
Project Creator : 1y0n
License : MIT License
Project Creator : 1y0n
public static string Shellcode_Handle(string raw)
{
string result = "";
//去掉所有换行 → 匹配出shellcode → 去掉所有空格 → 去掉引号、分号、括号 → 转换格式
raw = raw.Replace("\r\n", "").Replace("\r", "").Replace("\n", "");
if (raw.Contains(@"\x"))
{
//c 类型的shellcode
string pattern = @"=.*$";
string temp = Regex.Match(raw, pattern).Value;
result = temp.Replace(@"""", "").Replace(" ", "").Replace("=", "").Replace(";", "");
}
else if ((raw.Contains(@",0x")) || (raw.Contains(@", 0x")))
{
//c# 类型的shellcode
string pattern = @"{.*}";
string temp = Regex.Match(raw, pattern).Value;
result = temp.Replace("{", "").Replace(" ", "").Replace("}", "").Replace(";", "");
}
else
{
return "";
}
//转换成 c# 格式
if (result.Contains(@"\x"))
{
result = result.Replace(@"\x", ",0x").TrimStart(',');
}
return result;
}
19
View Source File : YmlFormatUtil.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
public static List<YmlLine> FormatYml(string content, bool beautify = false)
{
List<YmlLine> list = new List<YmlLine>();
string[] lines = content.Split('\n');
YmlLine ylText = null;
int index1 = -1, index2 = -1, count = 0, num = 0;
string startStr = null, endStr = null, line = "";
string key = null, value = null, mh = ":";
List<int> levels = new List<int>();
for(int i = 0, k = lines.Length; i < k; i++){
line = lines[i];
if(line.TrimStart().StartsWith("#")){
ylText = new YmlLine()
{
Text = line + "\n",
Color = Color.Gray
};
list.Add(ylText);
}
else
{
// 非整行注释
// 美化
if (beautify)
{
count = StartSpaceCount(line);
if (count == 0)
{
levels.Clear();
}
// level
if (!levels.Contains(count))
{
levels.Add(count);
levels.Sort();
}
num = levels.IndexOf(count) * 4;
if (num > count)
{
line = GetSpace(num - count) + line;
}
}
// 行中有井号,但不是首位#
index2 = line.IndexOf("#");
if(index2 > 0){
startStr = line.Substring(0, index2);
index1 = startStr.IndexOf(":");
if (index1 > 0)
{
// key
key = startStr.Substring(0, index1);
ylText = new YmlLine()
{
Text = key,
Color = Color.OrangeRed
};
list.Add(ylText);
// :
ylText = new YmlLine()
{
Text = mh,
Color = Color.Violet
};
list.Add(ylText);
// value
value = startStr.Substring(index1 + 1);
ylText = new YmlLine()
{
Text = value,
Color = getTextColor(value)
};
list.Add(ylText);
}
else
{
ylText = new YmlLine()
{
Text = "#" + startStr,
Color = Color.Gray
};
list.Add(ylText);
}
// 注释掉的部分
endStr = line.Substring(index2);
ylText = new YmlLine()
{
Text = endStr + "\n",
Color = Color.Gray
};
list.Add(ylText);
}
else
{
// 行中无井号
startStr = line;
index1 = startStr.IndexOf(":");
if (index1 > 0)
{
// key
key = startStr.Substring(0, index1);
ylText = new YmlLine()
{
Text = key,
Color = Color.OrangeRed
};
list.Add(ylText);
// :
ylText = new YmlLine()
{
Text = mh,
Color = Color.Violet
};
list.Add(ylText);
// value
value = startStr.Substring(index1 + 1);
ylText = new YmlLine()
{
Text = value + "\n",
Color = getTextColor(value)
};
list.Add(ylText);
}
else
{
// 行中无井号,且是不合规的配置值
if (string.IsNullOrWhiteSpace(line))
{
ylText = new YmlLine()
{
Text = line + "\n",
Color = Color.OrangeRed
};
}
else
{
ylText = new YmlLine()
{
Text = "#" + line + "\n",
Color = Color.Gray
};
}
list.Add(ylText);
}
}
}
}
return list;
}
19
View Source File : YmlFormatUtil.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
public static List<YmlItem> FormatYmlToTree(string content)
{
List<YmlItem> lists = new List<YmlItem>();
string[] lines = content.Split('\n');
YmlItem item = null;
string startStr = "";
List<YmlItem> levels = new List<YmlItem>();
int index1 = -1, index2 = -1, index = 0;
foreach(string line in lines){
if(string.IsNullOrWhiteSpace(line)){
item = new YmlItem();
item.Uuid = "T" + (index++);
item.ImageIndex = 2;
item.Key = "#" + line;
item.Value = "";
item.Level = 0;
item.Common = "";
lists.Add(item);
continue;
}
if(line.TrimStart().StartsWith("#")){
item = new YmlItem();
item.Uuid = "T" + (index++);
item.ImageIndex = 2;
item.Key = line;
item.Value = "";
item.Level = 0;
item.Common = "";
lists.Add(item);
}
else
{
item = new YmlItem();
item.Uuid = "T" + (index++);
item.ImageIndex = 0;
item.Key = "";
item.Value = "";
item.Level = 0;
item.Common = "";
item.SpcCount = StartSpaceCount(line);
if (item.SpcCount == 0)
{
levels.Clear();
item.Level = 0;
}
else
{
// level
for (int i = levels.Count - 1; i >= 0; i-- )
{
if (levels[i].SpcCount < item.SpcCount)
{
item.Level = levels[i].Level + 1;
item.Parent = levels[i];
break;
}
}
}
levels.Add(item);
index2 = line.IndexOf("#");
if (index2 > 0)
{
startStr = line.Substring(0, index2);
item.Common = line.Substring(index2);
}
else
{
startStr = line;
}
index1 = startStr.IndexOf(":");
if (index1 > 0)
{
item.Key = startStr.Substring(0, index1).TrimStart();
item.Value = startStr.Substring(index1 + 1).Trim();
}
else
{
item.Key = startStr.TrimStart();
item.Common = "--格式错误--";
}
if (!string.IsNullOrWhiteSpace(item.Value))
{
item.ImageIndex = 1;
}
lists.Add(item);
}
}
return lists;
}
19
View Source File : YmlFormatUtil.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
public static YmlError ValidateYml(string content)
{
YmlError result = null;
string[] lines = content.Split('\n');
int index1 = -1, index2 = -1, lineIndex = 1, index = 0;
string startStr = null;
foreach (string line in lines)
{
if (!line.TrimStart().StartsWith("#"))
{
if (line.IndexOf(" ") != -1 && line.Substring(0, line.IndexOf(" ")).IndexOf("#") == -1)
{
result = new YmlError();
result.line = lineIndex;
result.index = content.IndexOf(" ", index);
result.msg = string.Format("第{0}行,位置{1}包含Tab符", lineIndex, line.IndexOf(" "));
break;
}
else if (!string.IsNullOrWhiteSpace(line))
{
index2 = line.IndexOf("#");
if (index2 > 0)
{
startStr = line.Substring(0, index2);
index1 = startStr.IndexOf(":");
if (index1 <= 0)
{
result = new YmlError();
result.line = lineIndex;
result.index = index;
result.msg = string.Format("第{0}行,格式不正确,缺少冒号", lineIndex);
break;
}
}
else
{
index1 = line.IndexOf(":");
if (index1 <= 0)
{
result = new YmlError();
result.line = lineIndex;
result.index = index;
result.msg = string.Format("第{0}行,格式不正确,缺少冒号", lineIndex);
break;
}
}
}
}
lineIndex++;
index += line.Length;
}
return result;
}
19
View Source File : CentralServerConfigForm.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
private void 行注释ToolStripMenuItem_Click(object sender, EventArgs e)
{
int index = ymlEditor.GetFirstCharIndexOfCurrentLine();
int line = ymlEditor.GetLineFromCharIndex(index);
int start = ymlEditor.SelectionStart;
string lineStr = ymlEditor.Lines[line];
if(lineStr.TrimStart().StartsWith("#")){
ymlEditor.SelectionStart = index + lineStr.IndexOf("#");
ymlEditor.SelectionLength = 1;
ymlEditor.SelectedText = "";
}
else
{
ymlEditor.SelectionStart = start;
ymlEditor.SelectionLength = 0;
ymlEditor.SelectedText = "#";
}
ymlEditor.Focus();
}
19
View Source File : CentralServerConfigForm.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
private void 校验ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count > 0)
{
ListViewItem item = listView1.SelectedItems[0];
string content = "";
if (tabControl1.SelectedIndex == 0)
{
string line = "";
StringBuilder sb = new StringBuilder();
foreach(TreeListViewItem treeNode in _treeView.Items){
line = treeNode.Text;
if(!line.TrimStart().StartsWith("#")){
line += ": " + treeNode.SubItems[0].Text;
line += treeNode.SubItems[2].Text;
}
sb.AppendLine(treeNode.Text);
}
content = sb.ToString();
}
else
{
content = ymlEditor.Text;
}
Validate(item, content);
}
}
19
View Source File : CentralServerConfigForm.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
private List<string> getTreeNodeContent(TreeListViewItemCollection items)
{
List<string> list = new List<string>();
string line = "";
int level = 0;
foreach (TreeListViewItem treeNode in items)
{
line = treeNode.Text;
if (!line.TrimStart().StartsWith("#"))
{
line += ": ";
level = Convert.ToInt32(treeNode.SubItems[2].Text);
line = YmlFormatUtil.GetSpace(level * 4) + line;
line += treeNode.SubItems[1].Text;
line += treeNode.SubItems[3].Text;
}
if (!string.IsNullOrWhiteSpace(line))
{
list.Add(line);
}
list.AddRange(getTreeNodeContent(treeNode.Items));
}
return list;
}
19
View Source File : CommandFlagsTests.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
[Fact]
public void Command()
{
string UFString(string text)
{
if (text.Length <= 1) return text.ToUpper();
else return text.Substring(0, 1).ToUpper() + text.Substring(1, text.Length - 1);
}
var rt = cli.Command();
//var rt = cli.CommandInfo("mset", "mget", "set", "get", "rename");
var flags = new List<string>();
var flags7 = new List<string>();
var diccmd = new Dictionary<string, (string[], string[])>();
var sb = string.Join("\r\n\r\n", (rt).OrderBy(a1 => (a1 as object[])[0].ToString()).Select(a1 =>
{
var a = a1 as object[];
var cmd = a[0].ToString();
var plen = int.Parse(a[1].ToString());
var firstKey = int.Parse(a[3].ToString());
var lastKey = int.Parse(a[4].ToString());
var stepCount = int.Parse(a[5].ToString());
var aflags = (a[2] as object[]).Select(a => a.ToString()).ToArray();
var fopts = (a[6] as object[]).Select(a => a.ToString()).ToArray();
flags.AddRange(aflags);
flags7.AddRange(fopts);
diccmd.Add(cmd.ToUpper(), (aflags, fopts));
var parms = "";
if (plen > 1)
{
for (var x = 1; x < plen; x++)
{
if (x == firstKey) parms += "string key, ";
else parms += $"string arg{x}, ";
}
parms = parms.Remove(parms.Length - 2);
}
if (plen < 0)
{
for (var x = 1; x < -plen; x++)
{
if (x == firstKey)
{
if (firstKey != lastKey) parms += "string[] keys, ";
else parms += "string key, ";
}
else
{
if (firstKey != lastKey) parms += $"string[] arg{x}, ";
else parms += $"string arg{x}, ";
}
}
if (parms.Length > 0)
parms = parms.Remove(parms.Length - 2);
}
return $@"
//{string.Join(", ", a[2] as object[])}
//{string.Join(", ", a[6] as object[])}
public void {UFString(cmd)}({parms}) {{ }}";
}));
flags = flags.Distinct().ToList();
flags7 = flags7.Distinct().ToList();
var sboptions = new StringBuilder();
foreach (var cmd in CommandSets._allCommands)
{
if (diccmd.TryGetValue(cmd, out var tryv))
{
sboptions.Append($@"
[""{cmd}""] = new CommandSets(");
for (var x = 0; x < tryv.Item1.Length; x++)
{
if (x > 0) sboptions.Append(" | ");
sboptions.Append($"ServerFlag.{tryv.Item1[x].Replace("readonly", "@readonly")}");
}
sboptions.Append(", ");
for (var x = 0; x < tryv.Item2.Length; x++)
{
if (x > 0) sboptions.Append(" | ");
sboptions.Append($"ServerTag.{tryv.Item2[x].TrimStart('@').Replace("string", "@string")}");
}
sboptions.Append(", LocalStatus.none),");
}
else
{
sboptions.Append($@"
[""{cmd}""] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none), ");
}
}
var optioncode = sboptions.ToString();
}
19
View Source File : TemplateEngin.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public static string TranslateUrl(string url, string baseDir) {
if (string.IsNullOrEmpty(baseDir))
{
baseDir = AppContext.BaseDirectory + "/";
if (url.StartsWith(AppContext.BaseDirectory)) url = url.Substring(AppContext.BaseDirectory.Length).TrimStart('/');
}
if (string.IsNullOrEmpty(url)) return Path.GetDirectoryName(baseDir);
if (url.StartsWith("~/")) url = url.Substring(1);
if (url.StartsWith("/")) return Path.GetFullPath(Path.Combine(Path.GetDirectoryName(baseDir), url.TrimStart('/')));
if (url.StartsWith("\\")) return Path.GetFullPath(Path.Combine(Path.GetDirectoryName(baseDir), url.TrimStart('\\')));
if (url.IndexOf(":\\") != -1) return url;
return Path.GetFullPath(Path.Combine(Path.GetDirectoryName(baseDir), url));
}
19
View Source File : RazorModel.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public string GetCsName(string name) {
name = Regex.Replace(name.TrimStart('@', '.'), @"[^\w]", "_");
name = char.IsLetter(name, 0) ? name : string.Concat("_", name);
if (task.OptionsEnreplacedy01) name = UFString(name);
if (task.OptionsEnreplacedy02) name = UFString(name.ToLower());
if (task.OptionsEnreplacedy03) name = name.ToLower();
if (task.OptionsEnreplacedy04) name = string.Join("", name.Split('_').Select(a => UFString(a)));
return name;
}
19
View Source File : RazorModel.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public string GetMySqlEnumSetDefine() {
if (fsql.Ado.DataType != FreeSql.DataType.MySql) return null;
var sb = new StringBuilder();
foreach (var col in table.Columns) {
if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Enum || col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Set) {
if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Set) sb.Append("\r\n\t[Flags]");
sb.Append($"\r\n\tpublic enum {this.GetCsName(this.FullTableName)}{this.GetCsName(col.Name).ToUpper()}");
if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Set) sb.Append(" : long");
sb.Append(" {\r\n\t\t");
string slkdgjlksdjg = "";
int field_idx = 0;
int unknow_idx = 0;
string exp2 = string.Concat(col.DbTypeTextFull);
int quote_pos = -1;
while (true) {
int first_pos = quote_pos = exp2.IndexOf('\'', quote_pos + 1);
if (quote_pos == -1) break;
while (true) {
quote_pos = exp2.IndexOf('\'', quote_pos + 1);
if (quote_pos == -1) break;
int r_cout = 0;
//for (int p = 1; true; p++) {
// if (exp2[quote_pos - p] == '\\') r_cout++;
// else break;
//}
while (exp2[++quote_pos] == '\'') r_cout++;
if (r_cout % 2 == 0/* && quote_pos - first_pos > 2*/) {
string str2 = exp2.Substring(first_pos + 1, quote_pos - first_pos - 2).Replace("''", "'");
if (Regex.IsMatch(str2, @"^[\u0391-\uFFE5a-zA-Z_\$][\u0391-\uFFE5a-zA-Z_\$\d]*$"))
slkdgjlksdjg += ", " + str2;
else
slkdgjlksdjg += string.Format(@",
/// <summary>
/// {0}
/// </summary>
[Description(""{0}"")]
Unknow{1}", str2.Replace("\"", "\\\""), ++unknow_idx);
if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Set)
slkdgjlksdjg += " = " + Math.Pow(2, field_idx++);
if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Enum && field_idx++ == 0)
slkdgjlksdjg += " = 1";
break;
}
}
if (quote_pos == -1) break;
}
sb.Append(slkdgjlksdjg.Substring(2).TrimStart('\r', '\n', '\t'));
sb.Append("\r\n\t}");
}
}
return sb.ToString();
}
19
View Source File : TemplateEngin.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public static string ReadTextFile(string path) {
byte[] bytes = ReadFile(path);
return Encoding.UTF8.GetString(bytes).TrimStart((char)65279);
}
19
View Source File : RazorModel.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public string GetCsName(string name)
{
name = Regex.Replace(name.TrimStart('@', '.'), @"[^\w]", "_");
name = char.IsLetter(name, 0) ? name : string.Concat("_", name);
if (task.OptionsEnreplacedy01) name = UFString(name);
if (task.OptionsEnreplacedy02) name = UFString(name.ToLower());
if (task.OptionsEnreplacedy03) name = name.ToLower();
if (task.OptionsEnreplacedy04) name = string.Join("", name.Split('_').Select(a => UFString(a)));
return name;
}
19
View Source File : RazorModel.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public string GetMySqlEnumSetDefine()
{
if (fsql.Ado.DataType != FreeSql.DataType.MySql && fsql.Ado.DataType != FreeSql.DataType.OdbcMySql) return null;
var sb = new StringBuilder();
foreach (var col in table.Columns)
{
if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Enum || col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Set)
{
if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Set) sb.Append("\r\n\t[Flags]");
sb.Append($"\r\n\tpublic enum {this.GetCsName(this.FullTableName)}{this.GetCsName(col.Name).ToUpper()}");
if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Set) sb.Append(" : long");
sb.Append(" {\r\n\t\t");
string slkdgjlksdjg = "";
int field_idx = 0;
int unknow_idx = 0;
string exp2 = string.Concat(col.DbTypeTextFull);
int quote_pos = -1;
while (true)
{
int first_pos = quote_pos = exp2.IndexOf('\'', quote_pos + 1);
if (quote_pos == -1) break;
while (true)
{
quote_pos = exp2.IndexOf('\'', quote_pos + 1);
if (quote_pos == -1) break;
int r_cout = 0;
//for (int p = 1; true; p++) {
// if (exp2[quote_pos - p] == '\\') r_cout++;
// else break;
//}
while (exp2[++quote_pos] == '\'') r_cout++;
if (r_cout % 2 == 0/* && quote_pos - first_pos > 2*/)
{
string str2 = exp2.Substring(first_pos + 1, quote_pos - first_pos - 2).Replace("''", "'");
if (Regex.IsMatch(str2, @"^[\u0391-\uFFE5a-zA-Z_\$][\u0391-\uFFE5a-zA-Z_\$\d]*$"))
slkdgjlksdjg += ", " + str2;
else
slkdgjlksdjg += string.Format(@",
/// <summary>
/// {0}
/// </summary>
[Description(""{0}"")]
Unknow{1}", str2.Replace("\"", "\\\""), ++unknow_idx);
if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Set)
slkdgjlksdjg += " = " + Math.Pow(2, field_idx++);
if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Enum && field_idx++ == 0)
slkdgjlksdjg += " = 1";
break;
}
}
if (quote_pos == -1) break;
}
sb.Append(slkdgjlksdjg.Substring(2).TrimStart('\r', '\n', '\t'));
sb.Append("\r\n\t}");
}
}
return sb.ToString();
}
19
View Source File : Board.cs
License : MIT License
Project Creator : 3583Bytes
License : MIT License
Project Creator : 3583Bytes
internal static string Fen(bool boardOnly, Board board)
{
string output = String.Empty;
byte blankSquares = 0;
for (byte x = 0; x < 64; x++)
{
byte index = x;
if (board.Squares[index].Piece != null)
{
if (blankSquares > 0)
{
output += blankSquares.ToString();
blankSquares = 0;
}
if (board.Squares[index].Piece.PieceColor == ChessPieceColor.Black)
{
output += Piece.GetPieceTypeShort(board.Squares[index].Piece.PieceType).ToLower();
}
else
{
output += Piece.GetPieceTypeShort(board.Squares[index].Piece.PieceType);
}
}
else
{
blankSquares++;
}
if (x % 8 == 7)
{
if (blankSquares > 0)
{
output += blankSquares.ToString();
output += "/";
blankSquares = 0;
}
else
{
if (x > 0 && x != 63)
{
output += "/";
}
}
}
}
if (output.EndsWith("/"))
{
output = output.TrimEnd('/');
}
if (board.WhoseMove == ChessPieceColor.White)
{
output += " w ";
}
else
{
output += " b ";
}
string castle = "-";
if (board.WhiteCastled == false)
{
if (board.Squares[60].Piece != null)
{
if (board.Squares[60].Piece.Moved == false)
{
if (board.Squares[63].Piece != null)
{
if (board.Squares[63].Piece.Moved == false)
{
castle += "K";
}
}
if (board.Squares[56].Piece != null)
{
if (board.Squares[56].Piece.Moved == false)
{
castle += "Q";
}
}
}
}
}
if (board.BlackCastled == false)
{
if (board.Squares[4].Piece != null)
{
if (board.Squares[4].Piece.Moved == false)
{
if (board.Squares[7].Piece != null)
{
if (board.Squares[7].Piece.Moved == false)
{
castle += "k";
}
}
if (board.Squares[0].Piece != null)
{
if (board.Squares[0].Piece.Moved == false)
{
castle += "q";
}
}
}
}
}
if (castle != "-")
{
castle = castle.TrimStart('-');
}
output += castle;
if (board.EnPreplacedantPosition != 0)
{
output += " " + GetColumnFromByte((byte)(board.EnPreplacedantPosition % 8)) + "" + (byte)(8 - (byte)(board.EnPreplacedantPosition / 8)) + " ";
}
else
{
output += " - ";
}
if (!boardOnly)
{
output += board.HalfMoveClock + " ";
output += board.MoveCount;
}
return output.Trim();
}
19
View Source File : Server.cs
License : MIT License
Project Creator : 5minlab
License : MIT License
Project Creator : 5minlab
static void FindFileType(RequestContext context, bool download, out string path, out string type) {
path = Path.Combine(fileRoot, context.match.Groups[1].Value);
string ext = Path.GetExtension(path).ToLower().TrimStart(new char[] { '.' });
if (download || !fileTypes.TryGetValue(ext, out type))
type = "application/octet-stream";
}
19
View Source File : StringExtension.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826
License : GNU Lesser General Public License v3.0
Project Creator : 8720826
public static string JoinString(this IEnumerable<string> values, string split)
{
var result = values.Aggregate(string.Empty, (current, value) => current + (split + value));
result = result.TrimStart(split.ToCharArray());
return result;
}
19
View Source File : BTCChinaAPI.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
public int PlaceOrder(double price, double amount, MarketType market)
{
string regPrice = "", regAmount = "", method = "", mParams = "";
switch (market)
{
case MarketType.BTCCNY:
regPrice = price.ToString("F2", CultureInfo.InvariantCulture);
regAmount = amount.ToString("F4", CultureInfo.InvariantCulture);
break;
case MarketType.LTCCNY:
regPrice = price.ToString("F2", CultureInfo.InvariantCulture);
regAmount = amount.ToString("F3", CultureInfo.InvariantCulture);
break;
case MarketType.LTCBTC:
regPrice = price.ToString("F4", CultureInfo.InvariantCulture);
regAmount = amount.ToString("F3", CultureInfo.InvariantCulture);
break;
default://"ALL" is not supported
throw new BTCChinaException("PlaceOrder", "N/A", "Market not supported.");
}
if (regPrice.StartsWith("-", StringComparison.Ordinal))
regPrice = "null";
if (regAmount.StartsWith("-", StringComparison.Ordinal))
{
regAmount = regAmount.TrimStart('-');
method = "sellOrder2";
}
else
{
method = "buyOrder2";
}
// mParams = regPrice + "," + regAmount;
mParams = "\"" + regPrice + "\",\"" + regAmount + "\"";
//not default market
if (market != MarketType.BTCCNY)
mParams += ",\"" + System.Enum.GetName(typeof(MarketType), market) + "\"";
var response = DoMethod(BuildParams(method, mParams));
var jsonObject = JObject.Parse(response);
var orderId = jsonObject.Value<int>("result");
return orderId;
}
19
View Source File : IndentationReformatter.cs
License : MIT License
Project Creator : Abdesol
License : MIT License
Project Creator : Abdesol
public void Step(IDoreplacedentAccessor doc, IndentationSettings set)
{
string line = doc.Text;
if (set.LeaveEmptyLines && line.Length == 0) return; // leave empty lines empty
line = line.TrimStart();
StringBuilder indent = new StringBuilder();
if (line.Length == 0) {
// Special treatment for empty lines:
if (blockComment || (inString && verbatim))
return;
indent.Append(block.InnerIndent);
indent.Append(Repeat(set.IndentString, block.OneLineBlock));
if (block.Continuation)
indent.Append(set.IndentString);
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
}
if (TrimEnd(doc))
line = doc.Text.TrimStart();
Block oldBlock = block;
bool startInComment = blockComment;
bool startInString = (inString && verbatim);
#region Parse char by char
lineComment = false;
inChar = false;
escape = false;
if (!verbatim) inString = false;
lastRealChar = '\n';
char lastchar = ' ';
char c = ' ';
char nextchar = line[0];
for (int i = 0; i < line.Length; i++) {
if (lineComment) break; // cancel parsing current line
lastchar = c;
c = nextchar;
if (i + 1 < line.Length)
nextchar = line[i + 1];
else
nextchar = '\n';
if (escape) {
escape = false;
continue;
}
#region Check for comment/string chars
switch (c) {
case '/':
if (blockComment && lastchar == '*')
blockComment = false;
if (!inString && !inChar) {
if (!blockComment && nextchar == '/')
lineComment = true;
if (!lineComment && nextchar == '*')
blockComment = true;
}
break;
case '#':
if (!(inChar || blockComment || inString))
lineComment = true;
break;
case '"':
if (!(inChar || lineComment || blockComment)) {
inString = !inString;
if (!inString && verbatim) {
if (nextchar == '"') {
escape = true; // skip escaped quote
inString = true;
} else {
verbatim = false;
}
} else if (inString && lastchar == '@') {
verbatim = true;
}
}
break;
case '\'':
if (!(inString || lineComment || blockComment)) {
inChar = !inChar;
}
break;
case '\\':
if ((inString && !verbatim) || inChar)
escape = true; // skip next character
break;
}
#endregion
if (lineComment || blockComment || inString || inChar) {
if (wordBuilder.Length > 0)
block.LastWord = wordBuilder.ToString();
wordBuilder.Length = 0;
continue;
}
if (!Char.IsWhiteSpace(c) && c != '[' && c != '/') {
if (block.Bracket == '{')
block.Continuation = true;
}
if (Char.IsLetterOrDigit(c)) {
wordBuilder.Append(c);
} else {
if (wordBuilder.Length > 0)
block.LastWord = wordBuilder.ToString();
wordBuilder.Length = 0;
}
#region Push/Pop the blocks
switch (c) {
case '{':
block.ResetOneLineBlock();
blocks.Push(block);
block.StartLine = doc.LineNumber;
if (block.LastWord == "switch") {
block.Indent(set.IndentString + set.IndentString);
/* oldBlock refers to the previous line, not the previous block
* The block we want is not available anymore because it was never pushed.
* } else if (oldBlock.OneLineBlock) {
// Inside a one-line-block is another statement
// with a full block: indent the inner full block
// by one additional level
block.Indent(set, set.IndentString + set.IndentString);
block.OuterIndent += set.IndentString;
// Indent current line if it starts with the '{' character
if (i == 0) {
oldBlock.InnerIndent += set.IndentString;
}*/
} else {
block.Indent(set);
}
block.Bracket = '{';
break;
case '}':
while (block.Bracket != '{') {
if (blocks.Count == 0) break;
block = blocks.Pop();
}
if (blocks.Count == 0) break;
block = blocks.Pop();
block.Continuation = false;
block.ResetOneLineBlock();
break;
case '(':
case '[':
blocks.Push(block);
if (block.StartLine == doc.LineNumber)
block.InnerIndent = block.OuterIndent;
else
block.StartLine = doc.LineNumber;
block.Indent(Repeat(set.IndentString, oldBlock.OneLineBlock) +
(oldBlock.Continuation ? set.IndentString : "") +
(i == line.Length - 1 ? set.IndentString : new String(' ', i + 1)));
block.Bracket = c;
break;
case ')':
if (blocks.Count == 0) break;
if (block.Bracket == '(') {
block = blocks.Pop();
if (IsSingleStatementKeyword(block.LastWord))
block.Continuation = false;
}
break;
case ']':
if (blocks.Count == 0) break;
if (block.Bracket == '[')
block = blocks.Pop();
break;
case ';':
case ',':
block.Continuation = false;
block.ResetOneLineBlock();
break;
case ':':
if (block.LastWord == "case"
|| line.StartsWith("case ", StringComparison.Ordinal)
|| line.StartsWith(block.LastWord + ":", StringComparison.Ordinal)) {
block.Continuation = false;
block.ResetOneLineBlock();
}
break;
}
if (!Char.IsWhiteSpace(c)) {
// register this char as last char
lastRealChar = c;
}
#endregion
}
#endregion
if (wordBuilder.Length > 0)
block.LastWord = wordBuilder.ToString();
wordBuilder.Length = 0;
if (startInString) return;
if (startInComment && line[0] != '*') return;
if (doc.Text.StartsWith("//\t", StringComparison.Ordinal) || doc.Text == "//")
return;
if (line[0] == '}') {
indent.Append(oldBlock.OuterIndent);
oldBlock.ResetOneLineBlock();
oldBlock.Continuation = false;
} else {
indent.Append(oldBlock.InnerIndent);
}
if (indent.Length > 0 && oldBlock.Bracket == '(' && line[0] == ')') {
indent.Remove(indent.Length - 1, 1);
} else if (indent.Length > 0 && oldBlock.Bracket == '[' && line[0] == ']') {
indent.Remove(indent.Length - 1, 1);
}
if (line[0] == ':') {
oldBlock.Continuation = true;
} else if (lastRealChar == ':' && indent.Length >= set.IndentString.Length) {
if (block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(block.LastWord + ":", StringComparison.Ordinal))
indent.Remove(indent.Length - set.IndentString.Length, set.IndentString.Length);
} else if (lastRealChar == ')') {
if (IsSingleStatementKeyword(block.LastWord)) {
block.OneLineBlock++;
}
} else if (lastRealChar == 'e' && block.LastWord == "else") {
block.OneLineBlock = Math.Max(1, block.PreviousOneLineBlock);
block.Continuation = false;
oldBlock.OneLineBlock = block.OneLineBlock - 1;
}
if (doc.IsReadOnly) {
// We can't change the current line, but we should accept the existing
// indentation if possible (=if the current statement is not a multiline
// statement).
if (!oldBlock.Continuation && oldBlock.OneLineBlock == 0 &&
oldBlock.StartLine == block.StartLine &&
block.StartLine < doc.LineNumber && lastRealChar != ':') {
// use indent StringBuilder to get the indentation of the current line
indent.Length = 0;
line = doc.Text; // get untrimmed line
for (int i = 0; i < line.Length; ++i) {
if (!Char.IsWhiteSpace(line[i]))
break;
indent.Append(line[i]);
}
// /* */ multiline comments have an extra space - do not count it
// for the block's indentation.
if (startInComment && indent.Length > 0 && indent[indent.Length - 1] == ' ') {
indent.Length -= 1;
}
block.InnerIndent = indent.ToString();
}
return;
}
if (line[0] != '{') {
if (line[0] != ')' && oldBlock.Continuation && oldBlock.Bracket == '{')
indent.Append(set.IndentString);
indent.Append(Repeat(set.IndentString, oldBlock.OneLineBlock));
}
// this is only for blockcomment lines starting with *,
// all others keep their old indentation
if (startInComment)
indent.Append(' ');
if (indent.Length != (doc.Text.Length - line.Length) ||
!doc.Text.StartsWith(indent.ToString(), StringComparison.Ordinal) ||
Char.IsWhiteSpace(doc.Text[indent.Length])) {
doc.Text = indent.ToString() + line;
}
}
19
View Source File : DevReloadMiddleware.cs
License : GNU General Public License v3.0
Project Creator : abiosoft
License : GNU General Public License v3.0
Project Creator : abiosoft
private void OnChanged(object source, FileSystemEventArgs e)
{
// return if it's an ignored directory
foreach (string ignoredDirectory in _options.IgnoredSubDirectories)
{
var sep = Path.DirectorySeparatorChar;
if (e.FullPath.Contains($"{sep}{ignoredDirectory}{sep}")) return;
}
FileInfo fileInfo = new FileInfo(e.FullPath);
if (_options.StaticFileExtensions.Length > 0)
{
foreach (string extension in _options.StaticFileExtensions)
{
if (fileInfo.Extension.Equals($".{extension.TrimStart('.')}"))
{
_time = System.DateTime.Now.ToString();
break;
}
}
}
else
{
_time = System.DateTime.Now.ToString();
}
// Specify what is done when a file is changed, created, or deleted.
Console.WriteLine($"File: {e.FullPath} {e.ChangeType}");
}
19
View Source File : CommandManager.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
public static string[] StuffRawIntoParameters(string raw, string command, string[] parameters)
{
List<string> parametersRehash = new List<string>();
var regex = new Regex(Regex.Escape(command));
var newCmdLine = regex.Replace(raw, "", 1).TrimStart();
parametersRehash.Add(newCmdLine);
parametersRehash.AddRange(parameters);
parameters = parametersRehash.ToArray();
return parameters;
}
19
View Source File : CommandParameterHelpers.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
public static bool ResolveACEParameters(Session session, IEnumerable<string> aceParsedParameters, IEnumerable<ACECommandParameter> parameters, bool rawIncluded = false)
{
string parameterBlob = "";
if (rawIncluded)
{
parameterBlob = aceParsedParameters.First();
}
else
{
parameterBlob = aceParsedParameters.Count() > 0 ? aceParsedParameters.Aggregate((a, b) => a + " " + b).Trim(new char[] { ' ', ',' }) : string.Empty;
}
int commaCount = parameterBlob.Count(x => x == ',');
List<ACECommandParameter> acps = parameters.ToList();
for (int i = acps.Count - 1; i > -1; i--)
{
ACECommandParameter acp = acps[i];
acp.ParameterNo = i + 1;
if (parameterBlob.Length > 0)
{
try
{
switch (acp.Type)
{
case ACECommandParameterType.PositiveLong:
Match match4 = Regex.Match(parameterBlob, @"(-?\d+)$", RegexOptions.IgnoreCase);
if (match4.Success)
{
if (!long.TryParse(match4.Groups[1].Value, out long val))
{
return false;
}
if (val <= 0)
{
return false;
}
acp.Value = val;
acp.Defaulted = false;
parameterBlob = (match4.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match4.Groups[1].Index).Trim(new char[] { ' ' });
}
break;
case ACECommandParameterType.Long:
Match match3 = Regex.Match(parameterBlob, @"(-?\d+)$", RegexOptions.IgnoreCase);
if (match3.Success)
{
if (!long.TryParse(match3.Groups[1].Value, out long val))
{
return false;
}
acp.Value = val;
acp.Defaulted = false;
parameterBlob = (match3.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match3.Groups[1].Index).Trim(new char[] { ' ', ',' });
}
break;
case ACECommandParameterType.ULong:
Match match2 = Regex.Match(parameterBlob, @"(-?\d+)$", RegexOptions.IgnoreCase);
if (match2.Success)
{
if (!ulong.TryParse(match2.Groups[1].Value, out ulong val))
{
return false;
}
acp.Value = val;
acp.Defaulted = false;
parameterBlob = (match2.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match2.Groups[1].Index).Trim(new char[] { ' ', ',' });
}
break;
case ACECommandParameterType.Location:
Position position = null;
Match match = Regex.Match(parameterBlob, @"([\d\.]+[ns])[^\d\.]*([\d\.]+[ew])$", RegexOptions.IgnoreCase);
if (match.Success)
{
string ns = match.Groups[1].Value;
string ew = match.Groups[2].Value;
if (!TryParsePosition(new string[] { ns, ew }, out string errorMessage, out position))
{
if (session != null)
{
ChatPacket.SendServerMessage(session, errorMessage, ChatMessageType.Broadcast);
}
else
{
Console.WriteLine(errorMessage);
}
return false;
}
else
{
acp.Value = position;
acp.Defaulted = false;
int coordsStartPos = Math.Min(match.Groups[1].Index, match.Groups[2].Index);
parameterBlob = (coordsStartPos == 0) ? string.Empty : parameterBlob.Substring(0, coordsStartPos).Trim(new char[] { ' ', ',' });
}
}
break;
case ACECommandParameterType.OnlinePlayerName:
if (i != 0)
{
throw new Exception("Player parameter must be the first parameter, since it can contain spaces.");
}
parameterBlob = parameterBlob.TrimEnd(new char[] { ' ', ',' });
Player targetPlayer = PlayerManager.GetOnlinePlayer(parameterBlob);
if (targetPlayer == null)
{
string errorMsg = $"Unable to find player {parameterBlob}";
if (session != null)
{
ChatPacket.SendServerMessage(session, errorMsg, ChatMessageType.Broadcast);
}
else
{
Console.WriteLine(errorMsg);
}
return false;
}
else
{
acp.Value = targetPlayer;
acp.Defaulted = false;
}
break;
case ACECommandParameterType.OnlinePlayerNameOrIid:
if (i != 0)
{
throw new Exception("Player parameter must be the first parameter, since it can contain spaces.");
}
if (!parameterBlob.Contains(' '))
{
if (uint.TryParse(parameterBlob, out uint iid))
{
Player targetPlayer2 = PlayerManager.GetOnlinePlayer(iid);
if (targetPlayer2 == null)
{
string logMsg = $"Unable to find player with iid {iid}";
if (session != null)
{
ChatPacket.SendServerMessage(session, logMsg, ChatMessageType.Broadcast);
}
else
{
Console.WriteLine(logMsg);
}
return false;
}
else
{
acp.Value = targetPlayer2;
acp.Defaulted = false;
break;
}
}
}
Player targetPlayer3 = PlayerManager.GetOnlinePlayer(parameterBlob);
if (targetPlayer3 == null)
{
string logMsg = $"Unable to find player {parameterBlob}";
if (session != null)
{
ChatPacket.SendServerMessage(session, logMsg, ChatMessageType.Broadcast);
}
else
{
Console.WriteLine(logMsg);
}
return false;
}
else
{
acp.Value = targetPlayer3;
acp.Defaulted = false;
}
break;
case ACECommandParameterType.OnlinePlayerIid:
Match matcha5 = Regex.Match(parameterBlob, /*((i == 0) ? "" : @"\s+") +*/ @"(\d{10})$|(0x[0-9a-f]{8})$", RegexOptions.IgnoreCase);
if (matcha5.Success)
{
string strIid = "";
if (matcha5.Groups[2].Success)
{
strIid = matcha5.Groups[2].Value;
}
else if (matcha5.Groups[1].Success)
{
strIid = matcha5.Groups[1].Value;
}
try
{
uint iid = 0;
if (strIid.StartsWith("0x"))
{
iid = Convert.ToUInt32(strIid, 16);
}
else
{
iid = uint.Parse(strIid);
}
Player targetPlayer2 = PlayerManager.GetOnlinePlayer(iid);
if (targetPlayer2 == null)
{
string logMsg = $"Unable to find player with iid {strIid}";
if (session != null)
{
ChatPacket.SendServerMessage(session, logMsg, ChatMessageType.Broadcast);
}
else
{
Console.WriteLine(logMsg);
}
return false;
}
else
{
acp.Value = targetPlayer2;
acp.Defaulted = false;
parameterBlob = (matcha5.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, matcha5.Groups[1].Index).Trim(new char[] { ' ', ',' });
}
}
catch (Exception)
{
string errorMsg = $"Unable to parse {strIid} into a player iid";
if (session != null)
{
ChatPacket.SendServerMessage(session, errorMsg, ChatMessageType.Broadcast);
}
else
{
Console.WriteLine(errorMsg);
}
return false;
}
}
break;
case ACECommandParameterType.PlayerName:
if (i != 0)
{
throw new Exception("Player name parameter must be the first parameter, since it can contain spaces.");
}
parameterBlob = parameterBlob.TrimEnd(new char[] { ' ', ',' });
if (string.IsNullOrWhiteSpace(parameterBlob))
{
break;
}
else
{
acp.Value = parameterBlob;
acp.Defaulted = false;
}
break;
case ACECommandParameterType.Uri:
Match match5 = Regex.Match(parameterBlob, @"(https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*))$", RegexOptions.IgnoreCase);
if (match5.Success)
{
string strUri = match5.Groups[1].Value;
try
{
Uri url = new Uri(strUri);
acp.Value = url;
acp.Defaulted = false;
parameterBlob = (match5.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match5.Groups[1].Index).Trim(new char[] { ' ', ',' });
}
catch (Exception)
{
return false;
}
}
break;
case ACECommandParameterType.DoubleQuoteEnclosedText:
Match match6 = Regex.Match(parameterBlob.TrimEnd(), @"(\"".*\"")$", RegexOptions.IgnoreCase);
if (match6.Success)
{
string txt = match6.Groups[1].Value;
try
{
acp.Value = txt.Trim('"');
acp.Defaulted = false;
parameterBlob = (match6.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match6.Groups[1].Index).Trim(new char[] { ' ', ',' });
}
catch (Exception)
{
return false;
}
}
break;
case ACECommandParameterType.CommaPrefixedText:
if (i == 0)
{
throw new Exception("this parameter type is not appropriate as the first parameter");
}
if (i == acps.Count - 1 && !acp.Required && commaCount < acps.Count - 1)
{
break;
}
Match match7 = Regex.Match(parameterBlob.TrimEnd(), @"\,\s*([^,]*)$", RegexOptions.IgnoreCase);
if (match7.Success)
{
string txt = match7.Groups[1].Value;
try
{
acp.Value = txt.TrimStart(new char[] { ' ', ',' });
acp.Defaulted = false;
parameterBlob = (match7.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match7.Groups[1].Index).Trim(new char[] { ' ', ',' });
}
catch (Exception)
{
return false;
}
}
break;
case ACECommandParameterType.SimpleWord:
Match match8 = Regex.Match(parameterBlob.TrimEnd(), @"([a-zA-Z1-9_]+)\s*$", RegexOptions.IgnoreCase);
if (match8.Success)
{
string txt = match8.Groups[1].Value;
try
{
acp.Value = txt.TrimStart(' ');
acp.Defaulted = false;
parameterBlob = (match8.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match8.Groups[1].Index).Trim(new char[] { ' ', ',' });
}
catch (Exception)
{
return false;
}
}
break;
case ACECommandParameterType.Enum:
if (acp.PossibleValues == null)
{
throw new Exception("The enum parameter type must be accompanied by the PossibleValues");
}
if (!acp.PossibleValues.IsEnum)
{
throw new Exception("PossibleValues must be an enum type");
}
Match match9 = Regex.Match(parameterBlob.TrimEnd(), @"([a-zA-Z1-9_]+)\s*$", RegexOptions.IgnoreCase);
if (match9.Success)
{
string txt = match9.Groups[1].Value;
try
{
txt = txt.Trim(new char[] { ' ', ',' });
Array etvs = Enum.GetValues(acp.PossibleValues);
foreach (object etv in etvs)
{
if (etv.ToString().ToLower() == txt.ToLower())
{
acp.Value = etv;
acp.Defaulted = false;
parameterBlob = (match9.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match9.Groups[1].Index).Trim(new char[] { ' ' });
break;
}
}
}
catch (Exception)
{
return false;
}
}
break;
}
}
catch
{
return false;
}
}
if (acp.Defaulted)
{
acp.Value = acp.DefaultValue;
}
if (acp.Required && acp.Defaulted)
{
if (!string.IsNullOrWhiteSpace(acp.ErrorMessage))
{
if (session != null)
{
ChatPacket.SendServerMessage(session, acp.ErrorMessage, ChatMessageType.Broadcast);
}
else
{
Console.WriteLine(acp.ErrorMessage);
}
}
return false;
}
}
return true;
}
19
View Source File : PlayerManager.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
public static IPlayer FindByName(string name, out bool isOnline)
{
playersLock.EnterReadLock();
try
{
var onlinePlayer = onlinePlayers.Values.FirstOrDefault(p => p.Name.TrimStart('+').Equals(name.TrimStart('+'), StringComparison.OrdinalIgnoreCase));
if (onlinePlayer != null)
{
isOnline = true;
return onlinePlayer;
}
isOnline = false;
var offlinePlayer = offlinePlayers.Values.FirstOrDefault(p => p.Name.TrimStart('+').Equals(name.TrimStart('+'), StringComparison.OrdinalIgnoreCase) && !p.IsPendingDeletion);
if (offlinePlayer != null)
return offlinePlayer;
}
finally
{
playersLock.ExitReadLock();
}
return null;
}
19
View Source File : ActionCommand.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public static bool TryParseV2(string message, HashSet<string> registeredCommands, out ActionCommand command)
{
command = null;
if (string.IsNullOrEmpty(message))
{
return false;
}
try
{
// the message needs to start with the keyword after trim leading space.
message = message.TrimStart();
if (!message.StartsWith(_commandKey))
{
return false;
}
// Get the index of the separator between the command info and the data.
int endIndex = message.IndexOf(_commandKey, _commandKey.Length);
if (endIndex < 0)
{
return false;
}
// Get the command info (command and properties).
int cmdIndex = _commandKey.Length;
string cmdInfo = message.Substring(cmdIndex, endIndex - cmdIndex);
// Get the command name
int spaceIndex = cmdInfo.IndexOf(' ');
string commandName =
spaceIndex < 0
? cmdInfo
: cmdInfo.Substring(0, spaceIndex);
if (registeredCommands.Contains(commandName))
{
// Initialize the command.
command = new ActionCommand(commandName);
}
else
{
return false;
}
// Set the properties.
if (spaceIndex > 0)
{
string propertiesStr = cmdInfo.Substring(spaceIndex + 1).Trim();
string[] splitProperties = propertiesStr.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string propertyStr in splitProperties)
{
string[] pair = propertyStr.Split(new[] { '=' }, count: 2, options: StringSplitOptions.RemoveEmptyEntries);
if (pair.Length == 2)
{
command.Properties[pair[0]] = UnescapeProperty(pair[1]);
}
}
}
command.Data = UnescapeData(message.Substring(endIndex + _commandKey.Length));
return true;
}
catch
{
command = null;
return false;
}
}
19
View Source File : Validators.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public static bool NTAccountValidator(string arg)
{
if (string.IsNullOrEmpty(arg) || String.IsNullOrEmpty(arg.TrimStart('.', '\\')))
{
return false;
}
try
{
var logonAccount = arg.TrimStart('.');
NTAccount ntaccount = new NTAccount(logonAccount);
SecurityIdentifier sid = (SecurityIdentifier)ntaccount.Translate(typeof(SecurityIdentifier));
}
catch (IdenreplacedyNotMappedException)
{
return false;
}
return true;
}
19
View Source File : RunnerService.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
private RunnerUpdateResult HandleRunnerUpdate()
{
// sleep 5 seconds wait for upgrade script to finish
Thread.Sleep(5000);
// looking update result record under _diag folder (the log file itself will indicate the result)
// SelfUpdate-20160711-160300.log.succeed or SelfUpdate-20160711-160300.log.fail
// Find the latest upgrade log, make sure the log is created less than 15 seconds.
// When log file named as SelfUpdate-20160711-160300.log.succeedneedrestart, Exit(int.max), during Exit() throw Exception, this will trigger SCM to recovery the service by restart it
// since SCM cache the ServiceHost in memory, sometime we need update the servicehost as well, in this way we can upgrade the ServiceHost as well.
DirectoryInfo dirInfo = new DirectoryInfo(GetDiagnosticFolderPath());
FileInfo[] updateLogs = dirInfo.GetFiles("SelfUpdate-*-*.log.*") ?? new FileInfo[0];
if (updateLogs.Length == 0)
{
// totally wrong, we are not even get a update log.
return RunnerUpdateResult.Failed;
}
else
{
FileInfo latestLogFile = null;
DateTime latestLogTimestamp = DateTime.MinValue;
foreach (var logFile in updateLogs)
{
int timestampStartIndex = logFile.Name.IndexOf("-") + 1;
int timestampEndIndex = logFile.Name.LastIndexOf(".log") - 1;
string timestamp = logFile.Name.Substring(timestampStartIndex, timestampEndIndex - timestampStartIndex + 1);
DateTime updateTime;
if (DateTime.TryParseExact(timestamp, "yyyyMMdd-HHmmss", null, DateTimeStyles.None, out updateTime) &&
updateTime > latestLogTimestamp)
{
latestLogFile = logFile;
latestLogTimestamp = updateTime;
}
}
if (latestLogFile == null || latestLogTimestamp == DateTime.MinValue)
{
// we can't find update log with expected naming convention.
return RunnerUpdateResult.Failed;
}
latestLogFile.Refresh();
if (DateTime.UtcNow - latestLogFile.LastWriteTimeUtc > TimeSpan.FromSeconds(15))
{
// the latest update log we find is more than 15 sec old, the update process is busted.
return RunnerUpdateResult.Failed;
}
else
{
string resultString = Path.GetExtension(latestLogFile.Name).TrimStart('.');
RunnerUpdateResult result;
if (Enum.TryParse<RunnerUpdateResult>(resultString, true, out result))
{
// return the result indicated by the update log.
return result;
}
else
{
// can't convert the result string, return failed to stop the service.
return RunnerUpdateResult.Failed;
}
}
}
}
19
View Source File : PathUtility.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public static String Combine(String path1, String path2)
{
if (String.IsNullOrEmpty(path1))
{
return path2;
}
if (String.IsNullOrEmpty(path2))
{
return path1;
}
Char separator = path1.Contains("/") ? '/' : '\\';
Char[] trimChars = new Char[] { '\\', '/' };
return path1.TrimEnd(trimChars) + separator.ToString() + path2.TrimStart(trimChars);
}
19
View Source File : ScriptHandler.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public override void PrintActionDetails(ActionRunStage stage)
{
if (stage == ActionRunStage.Post)
{
throw new NotSupportedException("Script action should not have 'Post' job action.");
}
Inputs.TryGetValue("script", out string contents);
contents = contents ?? string.Empty;
if (Action.Type == Pipelines.ActionSourceType.Script)
{
var firstLine = contents.TrimStart(' ', '\t', '\r', '\n');
var firstNewLine = firstLine.IndexOfAny(new[] { '\r', '\n' });
if (firstNewLine >= 0)
{
firstLine = firstLine.Substring(0, firstNewLine);
}
ExecutionContext.Output($"##[group]Run {firstLine}");
}
else
{
throw new InvalidOperationException($"Invalid action type {Action.Type} for {nameof(ScriptHandler)}");
}
var multiLines = contents.Replace("\r\n", "\n").TrimEnd('\n').Split('\n');
foreach (var line in multiLines)
{
// Bright Cyan color
ExecutionContext.Output($"\x1b[36;1m{line}\x1b[0m");
}
string argFormat;
string shellCommand;
string shellCommandPath = null;
bool validateShellOnHost = !(StepHost is ContainerStepHost);
string prependPath = string.Join(Path.PathSeparator.ToString(), ExecutionContext.Global.PrependPath.Reverse<string>());
string shell = null;
if (!Inputs.TryGetValue("shell", out shell) || string.IsNullOrEmpty(shell))
{
// TODO: figure out how defaults interact with template later
// for now, we won't check job.defaults if we are inside a template.
if (string.IsNullOrEmpty(ExecutionContext.ScopeName) && ExecutionContext.Global.JobDefaults.TryGetValue("run", out var runDefaults))
{
runDefaults.TryGetValue("shell", out shell);
}
}
if (string.IsNullOrEmpty(shell))
{
#if OS_WINDOWS
shellCommand = "pwsh";
if (validateShellOnHost)
{
shellCommandPath = WhichUtil.Which(shellCommand, require: false, Trace, prependPath);
if (string.IsNullOrEmpty(shellCommandPath))
{
shellCommand = "powershell";
Trace.Info($"Defaulting to {shellCommand}");
shellCommandPath = WhichUtil.Which(shellCommand, require: true, Trace, prependPath);
}
}
#else
shellCommand = "sh";
if (validateShellOnHost)
{
shellCommandPath = WhichUtil.Which("bash", false, Trace, prependPath) ?? WhichUtil.Which("sh", true, Trace, prependPath);
}
#endif
argFormat = ScriptHandlerHelpers.GetScriptArgumentsFormat(shellCommand);
}
else
{
var parsed = ScriptHandlerHelpers.ParseShellOptionString(shell);
shellCommand = parsed.shellCommand;
if (validateShellOnHost)
{
shellCommandPath = WhichUtil.Which(parsed.shellCommand, true, Trace, prependPath);
}
argFormat = $"{parsed.shellArgs}".TrimStart();
if (string.IsNullOrEmpty(argFormat))
{
argFormat = ScriptHandlerHelpers.GetScriptArgumentsFormat(shellCommand);
}
}
if (!string.IsNullOrEmpty(shellCommandPath))
{
ExecutionContext.Output($"shell: {shellCommandPath} {argFormat}");
}
else
{
ExecutionContext.Output($"shell: {shellCommand} {argFormat}");
}
if (this.Environment?.Count > 0)
{
ExecutionContext.Output("env:");
foreach (var env in this.Environment)
{
ExecutionContext.Output($" {env.Key}: {env.Value}");
}
}
ExecutionContext.Output("##[endgroup]");
}
19
View Source File : ScriptHandler.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public async Task RunAsync(ActionRunStage stage)
{
if (stage == ActionRunStage.Post)
{
throw new NotSupportedException("Script action should not have 'Post' job action.");
}
// Validate args
Trace.Entering();
ArgUtil.NotNull(ExecutionContext, nameof(ExecutionContext));
ArgUtil.NotNull(Inputs, nameof(Inputs));
var githubContext = ExecutionContext.ExpressionValues["github"] as GitHubContext;
ArgUtil.NotNull(githubContext, nameof(githubContext));
// Add Telemetry to JobContext to send with JobCompleteMessage
if (stage == ActionRunStage.Main)
{
var telemetry = new ActionsStepTelemetry
{
IsEmbedded = ExecutionContext.IsEmbedded,
Type = "run",
};
ExecutionContext.Root.ActionsStepsTelemetry.Add(telemetry);
}
var tempDirectory = HostContext.GetDirectory(WellKnownDirectory.Temp);
Inputs.TryGetValue("script", out var contents);
contents = contents ?? string.Empty;
string workingDirectory = null;
if (!Inputs.TryGetValue("workingDirectory", out workingDirectory))
{
if (string.IsNullOrEmpty(ExecutionContext.ScopeName) && ExecutionContext.Global.JobDefaults.TryGetValue("run", out var runDefaults))
{
if (runDefaults.TryGetValue("working-directory", out workingDirectory))
{
ExecutionContext.Debug("Overwrite 'working-directory' base on job defaults.");
}
}
}
var workspaceDir = githubContext["workspace"] as StringContextData;
workingDirectory = Path.Combine(workspaceDir, workingDirectory ?? string.Empty);
string shell = null;
if (!Inputs.TryGetValue("shell", out shell) || string.IsNullOrEmpty(shell))
{
if (string.IsNullOrEmpty(ExecutionContext.ScopeName) && ExecutionContext.Global.JobDefaults.TryGetValue("run", out var runDefaults))
{
if (runDefaults.TryGetValue("shell", out shell))
{
ExecutionContext.Debug("Overwrite 'shell' base on job defaults.");
}
}
}
var isContainerStepHost = StepHost is ContainerStepHost;
string prependPath = string.Join(Path.PathSeparator.ToString(), ExecutionContext.Global.PrependPath.Reverse<string>());
string commandPath, argFormat, shellCommand;
// Set up default command and arguments
if (string.IsNullOrEmpty(shell))
{
#if OS_WINDOWS
shellCommand = "pwsh";
commandPath = WhichUtil.Which(shellCommand, require: false, Trace, prependPath);
if (string.IsNullOrEmpty(commandPath))
{
shellCommand = "powershell";
Trace.Info($"Defaulting to {shellCommand}");
commandPath = WhichUtil.Which(shellCommand, require: true, Trace, prependPath);
}
ArgUtil.NotNullOrEmpty(commandPath, "Default Shell");
#else
shellCommand = "sh";
commandPath = WhichUtil.Which("bash", false, Trace, prependPath) ?? WhichUtil.Which("sh", true, Trace, prependPath);
#endif
argFormat = ScriptHandlerHelpers.GetScriptArgumentsFormat(shellCommand);
}
else
{
var parsed = ScriptHandlerHelpers.ParseShellOptionString(shell);
shellCommand = parsed.shellCommand;
// For non-ContainerStepHost, the command must be located on the host by Which
commandPath = WhichUtil.Which(parsed.shellCommand, !isContainerStepHost, Trace, prependPath);
argFormat = $"{parsed.shellArgs}".TrimStart();
if (string.IsNullOrEmpty(argFormat))
{
argFormat = ScriptHandlerHelpers.GetScriptArgumentsFormat(shellCommand);
}
}
// No arg format was given, shell must be a built-in
if (string.IsNullOrEmpty(argFormat) || !argFormat.Contains("{0}"))
{
throw new ArgumentException("Invalid shell option. Shell must be a valid built-in (bash, sh, cmd, powershell, pwsh) or a format string containing '{0}'");
}
// We do not not the full path until we know what shell is being used, so that we can determine the file extension
var scriptFilePath = Path.Combine(tempDirectory, $"{Guid.NewGuid()}{ScriptHandlerHelpers.GetScriptFileExtension(shellCommand)}");
var resolvedScriptPath = $"{StepHost.ResolvePathForStepHost(scriptFilePath).Replace("\"", "\\\"")}";
// Format arg string with script path
var arguments = string.Format(argFormat, resolvedScriptPath);
// Fix up and write the script
contents = ScriptHandlerHelpers.FixUpScriptContents(shellCommand, contents);
#if OS_WINDOWS
// Normalize Windows line endings
contents = contents.Replace("\r\n", "\n").Replace("\n", "\r\n");
var encoding = ExecutionContext.Global.Variables.Retain_Default_Encoding && Console.InputEncoding.CodePage != 65001
? Console.InputEncoding
: new UTF8Encoding(false);
#else
// Don't add a BOM. It causes the script to fail on some operating systems (e.g. on Ubuntu 14).
var encoding = new UTF8Encoding(false);
#endif
// Script is written to local path (ie host) but executed relative to the StepHost, which may be a container
File.WriteAllText(scriptFilePath, contents, encoding);
// Prepend PATH
AddPrependPathToEnvironment();
// expose context to environment
foreach (var context in ExecutionContext.ExpressionValues)
{
if (context.Value is IEnvironmentContextData runtimeContext && runtimeContext != null)
{
foreach (var env in runtimeContext.GetRuntimeEnvironmentVariables())
{
Environment[env.Key] = env.Value;
}
}
}
// dump out the command
var fileName = isContainerStepHost ? shellCommand : commandPath;
#if OS_OSX
if (Environment.ContainsKey("DYLD_INSERT_LIBRARIES")) // We don't check `isContainerStepHost` because we don't support container on macOS
{
// launch `node macOSRunInvoker.js shell args` instead of `shell args` to avoid macOS SIP remove `DYLD_INSERT_LIBRARIES` when launch process
string node12 = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Externals), "node12", "bin", $"node{IOUtil.ExeExtension}");
string macOSRunInvoker = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Bin), "macos-run-invoker.js");
arguments = $"\"{macOSRunInvoker.Replace("\"", "\\\"")}\" \"{fileName.Replace("\"", "\\\"")}\" {arguments}";
fileName = node12;
}
#endif
var systemConnection = ExecutionContext.Global.Endpoints.Single(x => string.Equals(x.Name, WellKnownServiceEndpointNames.SystemVssConnection, StringComparison.OrdinalIgnoreCase));
if (systemConnection.Data.TryGetValue("GenerateIdTokenUrl", out var generateIdTokenUrl) && !string.IsNullOrEmpty(generateIdTokenUrl))
{
Environment["ACTIONS_ID_TOKEN_REQUEST_URL"] = generateIdTokenUrl;
Environment["ACTIONS_ID_TOKEN_REQUEST_TOKEN"] = systemConnection.Authorization.Parameters[EndpointAuthorizationParameters.AccessToken];
}
ExecutionContext.Debug($"{fileName} {arguments}");
using (var stdoutManager = new OutputManager(ExecutionContext, ActionCommandManager))
using (var stderrManager = new OutputManager(ExecutionContext, ActionCommandManager))
{
StepHost.OutputDataReceived += stdoutManager.OnDataReceived;
StepHost.ErrorDataReceived += stderrManager.OnDataReceived;
// Execute
int exitCode = await StepHost.ExecuteAsync(workingDirectory: StepHost.ResolvePathForStepHost(workingDirectory),
fileName: fileName,
arguments: arguments,
environment: Environment,
requireExitCodeZero: false,
outputEncoding: null,
killProcessOnCancel: false,
inheritConsoleHandler: !ExecutionContext.Global.Variables.Retain_Default_Encoding,
cancellationToken: ExecutionContext.CancellationToken);
// Error
if (exitCode != 0)
{
ExecutionContext.Error($"Process completed with exit code {exitCode}.");
ExecutionContext.Result = TaskResult.Failed;
}
}
}
19
View Source File : ScalarToken.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
protected String TrimDisplayString(String displayString)
{
var firstLine = displayString.TrimStart(' ', '\t', '\r', '\n');
var firstNewLine = firstLine.IndexOfAny(new[] { '\r', '\n' });
if (firstNewLine >= 0)
{
firstLine = firstLine.Substring(0, firstNewLine);
}
return firstLine;
}
19
View Source File : UriExtensions.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public static Uri AppendQuery(this Uri uri, String name, String value)
{
ArgumentUtility.CheckForNull(uri, "uri");
ArgumentUtility.CheckStringForNullOrEmpty(name, "name");
ArgumentUtility.CheckStringForNullOrEmpty(value, "value");
StringBuilder stringBuilder = new StringBuilder(uri.Query.TrimStart('?'));
AppendSingleQueryValue(stringBuilder, name, value);
UriBuilder uriBuilder = new UriBuilder(uri);
uriBuilder.Query = stringBuilder.ToString();
return uriBuilder.Uri;
}
19
View Source File : ActionRunner.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
private static string FormatStepName(string prefix, string stepName)
{
if (string.IsNullOrEmpty(stepName))
{
return string.Empty;
}
var result = stepName.TrimStart(' ', '\t', '\r', '\n');
var firstNewLine = result.IndexOfAny(new[] { '\r', '\n' });
if (firstNewLine >= 0)
{
result = result.Substring(0, firstNewLine);
}
return $"{prefix}{result}";
}
19
View Source File : UriExtensions.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public static Uri AppendQuery(this Uri uri, IEnumerable<KeyValuePair<String, String>> queryValues)
{
ArgumentUtility.CheckForNull(uri, "uri");
ArgumentUtility.CheckForNull(queryValues, "queryValues");
StringBuilder stringBuilder = new StringBuilder(uri.Query.TrimStart('?'));
foreach (KeyValuePair<String, String> kvp in queryValues)
{
AppendSingleQueryValue(stringBuilder, kvp.Key, kvp.Value);
}
UriBuilder uriBuilder = new UriBuilder(uri);
uriBuilder.Query = stringBuilder.ToString();
return uriBuilder.Uri;
}
19
View Source File : UriExtensions.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public static Uri AppendQuery(this Uri uri, NameValueCollection queryValues)
{
ArgumentUtility.CheckForNull(uri, "uri");
ArgumentUtility.CheckForNull(queryValues, "queryValues");
StringBuilder stringBuilder = new StringBuilder(uri.Query.TrimStart('?'));
foreach (String name in queryValues)
{
AppendSingleQueryValue(stringBuilder, name, queryValues[name]);
}
UriBuilder uriBuilder = new UriBuilder(uri);
uriBuilder.Query = stringBuilder.ToString();
return uriBuilder.Uri;
}
19
View Source File : VssHttpUriUtility.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public static Uri ConcatUri(Uri baseUri, String relativeUri)
{
StringBuilder sbCombined = new StringBuilder(baseUri.GetLeftPart(UriPartial.Path).TrimEnd('/'));
sbCombined.Append('/');
sbCombined.Append(relativeUri.TrimStart('/'));
sbCombined.Append(baseUri.Query);
return new Uri(sbCombined.ToString());
}
19
View Source File : VssApiResourceVersion.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
private void FromVersionString(String apiVersionString)
{
if (String.IsNullOrEmpty(apiVersionString))
{
throw new VssInvalidApiResourceVersionException(apiVersionString);
}
// Check for a stage/resourceVersion string
int dashIndex = apiVersionString.IndexOf('-');
if (dashIndex >= 0)
{
String stageName;
// Check for a '.' which separate stage from resource version
int dotIndex = apiVersionString.IndexOf('.', dashIndex);
if (dotIndex > 0)
{
stageName = apiVersionString.Substring(dashIndex + 1, dotIndex - dashIndex - 1);
int resourceVersion;
String resourceVersionString = apiVersionString.Substring(dotIndex + 1);
if (!int.TryParse(resourceVersionString, out resourceVersion))
{
throw new VssInvalidApiResourceVersionException(apiVersionString);
}
else
{
this.ResourceVersion = resourceVersion;
}
}
else
{
stageName = apiVersionString.Substring(dashIndex + 1);
}
// Check for supported stage names
if (String.Equals(stageName, c_PreviewStageName, StringComparison.OrdinalIgnoreCase))
{
IsPreview = true;
}
else
{
throw new VssInvalidApiResourceVersionException(apiVersionString);
}
// Api version is the string before the dash
apiVersionString = apiVersionString.Substring(0, dashIndex);
}
// Trim a leading "v" for version
apiVersionString = apiVersionString.TrimStart('v');
double apiVersionValue;
if (!double.TryParse(apiVersionString, NumberStyles.Any, NumberFormatInfo.InvariantInfo, out apiVersionValue))
{
throw new VssInvalidApiResourceVersionException(apiVersionString);
}
// Store the api version
this.ApiVersion = new Version(apiVersionValue.ToString("0.0", CultureInfo.InvariantCulture));
}
19
View Source File : PXRegexColorizerTagger.cs
License : GNU General Public License v3.0
Project Creator : Acumatica
License : GNU General Public License v3.0
Project Creator : Acumatica
private void GetDacTag(ITextSnapshot newSnapshot, Match match, int offset, string[] dacParts)
{
string dacPart = dacParts[0].TrimStart(',', '<');
CreateTag(newSnapshot, match, offset, dacPart, Provider[PXCodeType.Dac]);
}
19
View Source File : ParamsHelper.cs
License : MIT License
Project Creator : ad313
License : MIT License
Project Creator : ad313
private static List<string> GetKeyParamtersInternal(string source)
{
var keyArray = new List<string>();
//获取key中附带的参数,格式:用 {} 包裹
var matchs = Regex.Matches(source, @"\{\w*\" + Separator + @"?\w*\}", RegexOptions.None);
foreach (Match match in matchs)
{
if (!match.Success)
{
continue;
}
keyArray.Add(match.Value.TrimStart('{').TrimEnd('}'));
}
return keyArray;
}
19
View Source File : POComment.cs
License : MIT License
Project Creator : adams85
License : MIT License
Project Creator : adams85
internal static bool TryParse(string value, string keyStringNewLine, out POPreviousValueComment result)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
string idKindToken = null;
value = value.Trim();
var index = value.FindIndex(char.IsWhiteSpace);
if (index >= 0)
{
idKindToken = value.Remove(index);
value = value.Substring(index + 1).TrimStart();
}
int length;
POIdKind idKind;
StringBuilder sb;
if (index < 0 ||
(length = value.Length) < 2 || value[0] != '"' || value[length - 1] != '"' ||
(idKind = POKey.GetIdKind(idKindToken)) == POIdKind.Unknown ||
POString.Decode(sb = new StringBuilder(), value, 1, length - 2, keyStringNewLine) >= 0)
{
result = null;
return false;
}
result = new POPreviousValueComment { IdKind = idKind, Value = sb.ToString() };
return true;
}
19
View Source File : BigDecimal.cs
License : MIT License
Project Creator : AdamWhiteHat
License : MIT License
Project Creator : AdamWhiteHat
public BigDecimal GetFractionalPart()
{
if (this == null)
{
throw new TypeInitializationException(nameof(BigDecimal), new NullReferenceException());
}
if (Mantissa == null) return BigInteger.Zero;
string resultString = string.Empty;
string decimalString = this.ToString();
string[] valueSplit = decimalString.Split('.');
if (valueSplit.Length == 1)
{
return new BigDecimal();
}
else if (valueSplit.Length == 2)
{
resultString = valueSplit[1];
}
BigInteger newMantessa = BigInteger.Parse(resultString.TrimStart(new char[] { '0' }));
BigDecimal result = new BigDecimal(newMantessa, (0 - resultString.Length));
return result;
}
19
View Source File : Utilities.cs
License : MIT License
Project Creator : ADeltaX
License : MIT License
Project Creator : ADeltaX
public static string CombinePaths(string a, string b)
{
if (string.IsNullOrEmpty(a) || (b.Length > 0 && b[0] == '\\'))
{
return b;
}
if (string.IsNullOrEmpty(b))
{
return a;
}
return a.TrimEnd('\\') + '\\' + b.TrimStart('\\');
}
19
View Source File : SalesAttachment.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static string FormatAbstract(string abstractText)
{
return abstractText == null ? null : abstractText.TrimStart();
}
19
View Source File : OrganizationServiceContextExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static string Combine(string baseUrl, string relativePath)
{
if (string.IsNullOrWhiteSpace(relativePath)) return baseUrl;
var url = "{0}/{1}".FormatWith(baseUrl.TrimEnd('/'), relativePath.TrimStart('/'));
return url;
}
19
View Source File : AdxEntityUrlProvider.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
internal static ApplicationPath JoinApplicationPath(string basePath, string extendedPath)
{
if (basePath.Contains("?")
|| basePath.Contains(":")
|| basePath.Contains("//")
|| basePath.Contains("&")
|| basePath.Contains("%3f")
|| basePath.Contains("%2f%2f")
|| basePath.Contains("%26"))
{
throw new ApplicationException("Invalid base path");
}
if (extendedPath.Contains("?")
|| extendedPath.Contains("&")
|| extendedPath.Contains("//")
|| extendedPath.Contains(":")
|| extendedPath.Contains("%3f")
|| extendedPath.Contains("%2f%2f")
|| extendedPath.Contains("%26"))
{
throw new ApplicationException("Invalid extendedPath");
}
var path = "{0}/{1}".FormatWith(basePath.TrimEnd('/'), extendedPath.TrimStart('/'));
return ApplicationPath.FromPartialPath(path);
}
19
View Source File : ContentMapEntityUrlProvider.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private new ApplicationPath JoinApplicationPath(string basePath, string extendedPath)
{
if (string.IsNullOrWhiteSpace(basePath) || basePath.Contains("?") || basePath.Contains(":") || basePath.Contains("//") || basePath.Contains("&")
|| basePath.Contains("%3f") || basePath.Contains("%2f%2f") || basePath.Contains("%26"))
{
ADXTrace.Instance.TraceError(TraceCategory.Application, "The basePath is invalid.");
return null;
}
if (string.IsNullOrWhiteSpace(extendedPath) || extendedPath.Contains("?") || extendedPath.Contains("&") || extendedPath.Contains("//")
|| extendedPath.Contains(":") || extendedPath.Contains("%3f") || extendedPath.Contains("%2f%2f") || extendedPath.Contains("%26"))
{
ADXTrace.Instance.TraceError(TraceCategory.Application, "The extendedPath is invalid.");
return null;
}
var path = "{0}/{1}".FormatWith(basePath.TrimEnd('/'), extendedPath.TrimStart('/'));
return ApplicationPath.FromPartialPath(path);
}
See More Examples