Here are the examples of the csharp api string.LastIndexOf(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1137 Examples
19
Source : IrdClient.cs
with MIT License
from 13xforever
with MIT License
from 13xforever
private static string Getreplacedle(string html)
{
if (string.IsNullOrEmpty(html))
return null;
var idx = html.LastIndexOf("</span>");
var result = html.Substring(idx + 7).Trim();
if (string.IsNullOrEmpty(result))
return null;
return result;
}
19
Source : Utils.cs
with Apache License 2.0
from 214175590
with Apache License 2.0
from 214175590
public static string getLinuxPathDir(string remotePath)
{
string dir = "/";
int index = remotePath.LastIndexOf("/");
if (index > 0)
{
dir = remotePath.Substring(0, index);
}
return dir;
}
19
Source : FileAttrForm.cs
with Apache License 2.0
from 214175590
with Apache License 2.0
from 214175590
private string getFileExt(string filename)
{
string ext = "";
if (null != filename && filename.IndexOf(".") != -1)
{
ext = filename.Substring(filename.LastIndexOf(".") + 1).ToUpper() + "文件";
}
return ext;
}
19
Source : StringExtensionMethods.cs
with MIT License
from 1ZouLTReX1
with MIT License
from 1ZouLTReX1
public static string AfterLast(this string str, string sub)
{
var idx = str.LastIndexOf(sub);
return idx < 0 ? "" : str.Substring(idx + sub.Length);
}
19
Source : StringExtensionMethods.cs
with MIT License
from 1ZouLTReX1
with MIT License
from 1ZouLTReX1
public static string BeforeLast(this string str, string sub)
{
var idx = str.LastIndexOf(sub);
return idx < 0 ? "" : str.Substring(0, idx);
}
19
Source : MonitorItemForm.cs
with Apache License 2.0
from 214175590
with Apache License 2.0
from 214175590
void Tomcat_TextChanged(object sender, EventArgs e)
{
string path = stb_tomcat_path.Text;
if (!string.IsNullOrWhiteSpace(path))
{
if (string.IsNullOrWhiteSpace(tomcat_name))
{
try
{
stb_tomcat_name.Text = path.Substring(path.LastIndexOf("/") + 1);
}
catch { }
}
if (string.IsNullOrWhiteSpace(stb_tomcat_port.Text))
{
try
{
if (get_tomcat_port_run)
{
return;
}
get_tomcat_port_run = true;
if (!path.EndsWith("/"))
{
path += "/";
}
string serverxml = path + "conf/server.xml";
string targetxml = MainForm.TEMP_DIR + string.Format("server-{0}.xml", DateTime.Now.ToString("MMddHHmmss"));
targetxml = targetxml.Replace("\\", "/");
parentForm.RunSftpShell(string.Format("get {0} {1}", serverxml, targetxml), false, false);
ThreadPool.QueueUserWorkItem((a) => {
Thread.Sleep(500);
List<Hashtable> list = YSTools.YSXml.readXml(targetxml, "Server");
if(list != null && list.Count > 0){
List<Hashtable> serviceList = null;
string port = null;
foreach(Hashtable one in list){
if (one["NodeName"].ToString() == "Service")
{
serviceList = (List<Hashtable>) one["ChildList"];
foreach (Hashtable two in serviceList)
{
if (two["NodeName"].ToString() == "Connector")
{
port = two["port"].ToString();
break;
}
}
if(port != null){
break;
}
}
}
stb_tomcat_port.BeginInvoke((MethodInvoker)delegate()
{
stb_tomcat_port.Text = port == null ? "8080" : port;
});
}
get_tomcat_port_run = false;
File.Delete(targetxml);
});
}
catch { }
}
}
}
19
Source : NginxMonitorForm.cs
with Apache License 2.0
from 214175590
with Apache License 2.0
from 214175590
public void runTaskShell(CmdShell cmds, TaskShell task)
{
ThreadPool.QueueUserWorkItem((a) =>
{
string shdir = itemConfig.nginx.NginxPath;
if (null != shdir)
{
if (shdir.EndsWith("/"))
{
shdir = shdir.Substring(0, shdir.Length - 1);
}
shdir = shdir.Substring(0, shdir.LastIndexOf("/") + 1);
}
string shell = task.Shell;
if (shell.Contains("{nginx_dir}"))
{
shell = shell.Replace("{nginx_dir}", shdir);
}
if (shell.Contains("{nginx}"))
{
shell = shell.Replace("{nginx}", itemConfig.nginx.NginxPath);
}
shell = shell.Replace("//", "/");
monitorForm.RunShell(shell, false);
});
}
19
Source : SftpLinuxForm.cs
with Apache License 2.0
from 214175590
with Apache License 2.0
from 214175590
public void OpenUpDir()
{
if(dir != "/" && dir.Length > 1){
if(dir.EndsWith("/")){
dir = dir.Substring(0, dir.Length - 1);
}
string dirpath = dir;
int index = dirpath.LastIndexOf("/");
if(index > 0){
dirpath = dirpath.Substring(0, index);
} else if(index == 0){
dirpath = "/";
}
LoadDirFilesToListView(dirpath, () =>
{
dir = dirpath;
text_adress.Text = dir;
});
}
}
19
Source : TsCreator.cs
with MIT License
from 279328316
with MIT License
from 279328316
private string GetTsType(string typeName)
{
string tsTypeStr = "";
List<string> numberTypeList =
("int,int?,int16,int16?,int32,int32?,int64,int64?,decimal,decimal?," +
"double,double?,byte,byte?,long,long?,single,single?").Split(',').ToList();
List<string> boolTypeList = ("bool,bool?,boolean,boolean?").Split(',').ToList();
List<string> stringTypeList =
("string,guid,guid?").Split(',').ToList();
List<string> dateTimeTypeList =
("datetime,datetime?").Split(',').ToList();
if (boolTypeList.Contains(typeName.ToLower()))
{
tsTypeStr = "boolean";
}
else if (stringTypeList.Contains(typeName.ToLower()))
{
tsTypeStr = "string";
}
else if (dateTimeTypeList.Contains(typeName.ToLower()))
{
tsTypeStr = "Date";
}
else if (numberTypeList.Contains(typeName.ToLower()))
{
tsTypeStr = "number";
}
else
{
tsTypeStr = typeName;
#region 去掉Dto,Model命名
if (tsTypeStr.EndsWith("Dto"))
{ //参数类型名称 去掉末尾Dto,Model命名
tsTypeStr = tsTypeStr.Substring(0, tsTypeStr.LastIndexOf("Dto"));
}
else if (tsTypeStr.EndsWith("Dto>"))
{
tsTypeStr = tsTypeStr.Substring(0, tsTypeStr.LastIndexOf("Dto")) + ">";
}
else if (tsTypeStr.EndsWith("Model"))
{
tsTypeStr = tsTypeStr.Substring(0, tsTypeStr.LastIndexOf("Model"));
}
else if (tsTypeStr.EndsWith("Model>"))
{
tsTypeStr = tsTypeStr.Substring(0, tsTypeStr.LastIndexOf("Model")) + ">";
}
#endregion
}
return tsTypeStr;
}
19
Source : ConsoleApp.cs
with MIT License
from 2881099
with MIT License
from 2881099
public static (string info, string warn, string err) ShellRun(string cddir, params string[] bat) {
if (bat == null || bat.Any() == false) return ("", "", "");
if (string.IsNullOrEmpty(cddir)) cddir = Directory.GetCurrentDirectory();
var proc = new System.Diagnostics.Process();
proc.StartInfo = new System.Diagnostics.ProcessStartInfo {
CreateNoWindow = true,
FileName = "cmd.exe",
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardInput = true,
RedirectStandardOutput = true,
WorkingDirectory = cddir
};
proc.Start();
foreach (var cmd in bat)
proc.StandardInput.WriteLine(cmd);
proc.StandardInput.WriteLine("exit");
var outStr = proc.StandardOutput.ReadToEnd();
var errStr = proc.StandardError.ReadToEnd();
proc.Close();
var idx = outStr.IndexOf($">{bat[0]}");
if (idx != -1) {
idx = outStr.IndexOf("\n", idx);
if (idx != -1) outStr = outStr.Substring(idx + 1);
}
idx = outStr.LastIndexOf(">exit");
if (idx != -1) {
idx = outStr.LastIndexOf("\n", idx);
if (idx != -1) outStr = outStr.Remove(idx);
}
outStr = outStr.Trim();
if (outStr == "") outStr = null;
if (errStr == "") errStr = null;
return (outStr, string.IsNullOrEmpty(outStr) ? null : errStr, string.IsNullOrEmpty(outStr) ? errStr : null);
}
19
Source : RazorModel.cs
with MIT License
from 2881099
with MIT License
from 2881099
public string GetColumnDefaultValue(DbColumnInfo col, bool isInsertValueSql)
{
var defval = col.DefaultValue?.Trim();
if (string.IsNullOrEmpty(defval)) return null;
var cstype = col.CsType.NullableTypeOrThis();
if (fsql.Ado.DataType == DataType.SqlServer || fsql.Ado.DataType == DataType.OdbcSqlServer)
{
if (defval.StartsWith("((") && defval.EndsWith("))")) defval = defval.Substring(2, defval.Length - 4);
else if (defval.StartsWith("('") && defval.EndsWith("')")) defval = defval.Substring(2, defval.Length - 4).Replace("''", "'");
else if(defval.StartsWith("(") && defval.EndsWith(")")) defval = defval.Substring(1, defval.Length - 2);
else return null;
}
else if ((cstype == typeof(string) && defval.StartsWith("'") && defval.EndsWith("'::character varying") ||
cstype == typeof(Guid) && defval.StartsWith("'") && defval.EndsWith("'::uuid")
) && (fsql.Ado.DataType == DataType.PostgreSQL || fsql.Ado.DataType == DataType.OdbcPostgreSQL ||
fsql.Ado.DataType == DataType.OdbcKingbaseES ||
fsql.Ado.DataType == DataType.ShenTong))
{
defval = defval.Substring(1, defval.LastIndexOf("'::") - 1).Replace("''", "'");
}
else if (defval.StartsWith("'") && defval.EndsWith("'"))
{
defval = defval.Substring(1, defval.Length - 2).Replace("''", "'");
if (fsql.Ado.DataType == DataType.MySql || fsql.Ado.DataType == DataType.OdbcMySql) defval = defval.Replace("\\\\", "\\");
}
if (cstype.IsNumberType() && decimal.TryParse(defval, out var trydec))
{
if (isInsertValueSql) return defval;
if (cstype == typeof(float)) return defval + "f";
if (cstype == typeof(double)) return defval + "d";
if (cstype == typeof(decimal)) return defval + "M";
return defval;
}
if (cstype == typeof(Guid) && Guid.TryParse(defval, out var tryguid)) return isInsertValueSql ? (fsql.Select<TestTb>() as Select0Provider)._commonUtils.FormatSql("{0}", defval) : $"Guid.Parse(\"{defval.Replace("\r\n", "\\r\\n").Replace("\"", "\\\"")}\")";
if (cstype == typeof(DateTime) && DateTime.TryParse(defval, out var trydt)) return isInsertValueSql ? (fsql.Select<TestTb>() as Select0Provider)._commonUtils.FormatSql("{0}", defval) : $"DateTime.Parse(\"{defval.Replace("\r\n", "\\r\\n").Replace("\"", "\\\"")}\")";
if (cstype == typeof(TimeSpan) && TimeSpan.TryParse(defval, out var tryts)) return isInsertValueSql ? (fsql.Select<TestTb>() as Select0Provider)._commonUtils.FormatSql("{0}", defval) : $"TimeSpan.Parse(\"{defval.Replace("\r\n", "\\r\\n").Replace("\"", "\\\"")}\")";
if (cstype == typeof(string)) return isInsertValueSql ? (fsql.Select<TestTb>() as Select0Provider)._commonUtils.FormatSql("{0}", defval) : $"\"{defval.Replace("\r\n", "\\r\\n").Replace("\"", "\\\"")}\"";
if (cstype == typeof(bool)) return isInsertValueSql ? defval : (defval == "1" || defval == "t" ? "true" : "false");
if (fsql.Ado.DataType == DataType.MySql || fsql.Ado.DataType == DataType.OdbcMySql)
if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Enum || col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Set)
if (isInsertValueSql) return (fsql.Select<TestTb>() as Select0Provider)._commonUtils.FormatSql("{0}", defval);
return isInsertValueSql ? defval : null; //sql function or exp
}
19
Source : ShareHandler.cs
with GNU General Public License v3.0
from 2dust
with GNU General Public License v3.0
from 2dust
public static VmessItem ImportFromClipboardConfig(string clipboardData, out string msg)
{
msg = string.Empty;
VmessItem vmessItem = new VmessItem();
try
{
//载入配置文件
string result = clipboardData.TrimEx();// Utils.GetClipboardData();
if (Utils.IsNullOrEmpty(result))
{
msg = UIRes.I18N("FailedReadConfiguration");
return null;
}
if (result.StartsWith(Global.vmessProtocol))
{
int indexSplit = result.IndexOf("?");
if (indexSplit > 0)
{
vmessItem = ResolveStdVmess(result) ?? ResolveVmess4Kitsunebi(result);
}
else
{
vmessItem.configType = (int)EConfigType.Vmess;
result = result.Substring(Global.vmessProtocol.Length);
result = Utils.Base64Decode(result);
//转成Json
VmessQRCode vmessQRCode = Utils.FromJson<VmessQRCode>(result);
if (vmessQRCode == null)
{
msg = UIRes.I18N("FailedConversionConfiguration");
return null;
}
vmessItem.network = Global.DefaultNetwork;
vmessItem.headerType = Global.None;
vmessItem.configVersion = Utils.ToInt(vmessQRCode.v);
vmessItem.remarks = Utils.ToString(vmessQRCode.ps);
vmessItem.address = Utils.ToString(vmessQRCode.add);
vmessItem.port = Utils.ToInt(vmessQRCode.port);
vmessItem.id = Utils.ToString(vmessQRCode.id);
vmessItem.alterId = Utils.ToInt(vmessQRCode.aid);
vmessItem.security = Utils.ToString(vmessQRCode.scy);
if (!Utils.IsNullOrEmpty(vmessQRCode.scy))
{
vmessItem.security = vmessQRCode.scy;
}
else
{
vmessItem.security = Global.DefaultSecurity;
}
if (!Utils.IsNullOrEmpty(vmessQRCode.net))
{
vmessItem.network = vmessQRCode.net;
}
if (!Utils.IsNullOrEmpty(vmessQRCode.type))
{
vmessItem.headerType = vmessQRCode.type;
}
vmessItem.requestHost = Utils.ToString(vmessQRCode.host);
vmessItem.path = Utils.ToString(vmessQRCode.path);
vmessItem.streamSecurity = Utils.ToString(vmessQRCode.tls);
vmessItem.sni = Utils.ToString(vmessQRCode.sni);
}
ConfigHandler.UpgradeServerVersion(ref vmessItem);
}
else if (result.StartsWith(Global.ssProtocol))
{
msg = UIRes.I18N("ConfigurationFormatIncorrect");
vmessItem = ResolveSSLegacy(result);
if (vmessItem == null)
{
vmessItem = ResolveSip002(result);
}
if (vmessItem == null)
{
return null;
}
if (vmessItem.address.Length == 0 || vmessItem.port == 0 || vmessItem.security.Length == 0 || vmessItem.id.Length == 0)
{
return null;
}
vmessItem.configType = (int)EConfigType.Shadowsocks;
}
else if (result.StartsWith(Global.socksProtocol))
{
msg = UIRes.I18N("ConfigurationFormatIncorrect");
vmessItem.configType = (int)EConfigType.Socks;
result = result.Substring(Global.socksProtocol.Length);
//remark
int indexRemark = result.IndexOf("#");
if (indexRemark > 0)
{
try
{
vmessItem.remarks = Utils.UrlDecode(result.Substring(indexRemark + 1, result.Length - indexRemark - 1));
}
catch { }
result = result.Substring(0, indexRemark);
}
//part decode
int indexS = result.IndexOf("@");
if (indexS > 0)
{
}
else
{
result = Utils.Base64Decode(result);
}
string[] arr1 = result.Split('@');
if (arr1.Length != 2)
{
return null;
}
string[] arr21 = arr1[0].Split(':');
//string[] arr22 = arr1[1].Split(':');
int indexPort = arr1[1].LastIndexOf(":");
if (arr21.Length != 2 || indexPort < 0)
{
return null;
}
vmessItem.address = arr1[1].Substring(0, indexPort);
vmessItem.port = Utils.ToInt(arr1[1].Substring(indexPort + 1, arr1[1].Length - (indexPort + 1)));
vmessItem.security = arr21[0];
vmessItem.id = arr21[1];
}
else if (result.StartsWith(Global.trojanProtocol))
{
msg = UIRes.I18N("ConfigurationFormatIncorrect");
vmessItem.configType = (int)EConfigType.Trojan;
Uri uri = new Uri(result);
vmessItem.address = uri.IdnHost;
vmessItem.port = uri.Port;
vmessItem.id = uri.UserInfo;
var qurery = HttpUtility.ParseQueryString(uri.Query);
vmessItem.sni = qurery["sni"] ?? "";
var remarks = uri.Fragment.Replace("#", "");
if (Utils.IsNullOrEmpty(remarks))
{
vmessItem.remarks = "NONE";
}
else
{
vmessItem.remarks = Utils.UrlDecode(remarks);
}
}
else if (result.StartsWith(Global.vlessProtocol))
{
vmessItem = ResolveStdVLESS(result);
ConfigHandler.UpgradeServerVersion(ref vmessItem);
}
else
{
msg = UIRes.I18N("NonvmessOrssProtocol");
return null;
}
}
catch
{
msg = UIRes.I18N("Incorrectconfiguration");
return null;
}
return vmessItem;
}
19
Source : DOTweenAnimation.cs
with MIT License
from 39M
with MIT License
from 39M
public static TargetType TypeToDOTargetType(Type t)
{
string str = t.ToString();
int dotIndex = str.LastIndexOf(".");
if (dotIndex != -1) str = str.Substring(dotIndex + 1);
if (str.IndexOf("Renderer") != -1 && (str != "SpriteRenderer")) str = "Renderer";
return (TargetType)Enum.Parse(typeof(TargetType), str);
}
19
Source : CustomMusicManager.cs
with MIT License
from 39M
with MIT License
from 39M
void InitMusicGroup()
{
musicUIItemList = new List<CustomMusicUIItem>();
string[] fileList = Directory.GetFiles(Application.streamingreplacedetsPath, "*.mp3");
Debug.Log(string.Format("{0} files found.", fileList.Length));
foreach (var filePath in fileList)
{
Debug.Log("Found music: " + filePath);
string fileName = filePath.Substring(filePath.LastIndexOf(@"\") + 1);
CustomMusicUIItem item = CreateMusicUIItem(fileName);
musicUIItemList.Add(item);
}
}
19
Source : ModelManager.cs
with GNU Affero General Public License v3.0
from 3drepo
with GNU Affero General Public License v3.0
from 3drepo
private string ExtractRevisionIdFromURI(string uri)
{
string revId = null;
int index;
if((index = uri.LastIndexOf("/revision/")) != -1)
{
index += "/revision/".Length;
string substring = uri.Substring(index);
string rev = substring.Split('/')[0];
if(rev != "master")
{
revId = rev;
}
}
return revId;
}
19
Source : SendPacket.cs
with MIT License
from 499116344
with MIT License
from 499116344
[Obsolete("请使用BinaryWriter.Write(Richtext)方法。")]
public static byte[] ConstructMessage(string message)
{
var bw = new BinaryWriter(new MemoryStream());
var r = new Regex(@"([^\[]+)*(\[face\d+\.gif\])([^\[]+)*");
if (r.IsMatch(message))
{
var faces = r.Matches(message);
for (var i = 0; i < faces.Count; i++)
{
var face = faces[i];
for (var j = 1; j < face.Groups.Count; j++)
{
var group = face.Groups[j].Value;
if (group.Contains("[face") && group.Contains(".gif]"))
{
var faceIndex =
Convert.ToByte(group.Substring(5, group.Length - group.LastIndexOf(".") - 4));
if (faceIndex > 199)
{
faceIndex = 0;
}
//表情
bw.Write(new byte[] { 0x02, 0x00, 0x14, 0x01, 0x00, 0x01 });
bw.Write(faceIndex);
bw.Write(new byte[] { 0xFF, 0x00, 0x02, 0x14 });
bw.Write((byte) (faceIndex + 65));
bw.Write(new byte[] { 0x0B, 0x00, 0x08, 0x00, 0x01, 0x00, 0x04, 0x52, 0xCC, 0x85, 0x50 });
}
else if (!string.IsNullOrEmpty(group))
{
var groupMsg = Encoding.UTF8.GetBytes(group);
//普通消息
ConstructMessage(bw, groupMsg);
}
}
}
}
return bw.BaseStream.ToBytesArray();
}
19
Source : LccViewEditor.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
LccView lccView = (LccView)target;
if (GUILayout.Button(lccView.clreplacedName))
{
string directoryName = string.Empty;
switch (Path.GetFileNameWithoutExtension(lccView.type.GetType().replacedembly.ManifestModule.Name))
{
case "Unity.Model":
directoryName = "Scripts";
break;
case "Unity.Hotfix":
directoryName = "Hotfix";
break;
case "ILRuntime":
directoryName = "Hotfix";
break;
}
string fileName = lccView.clreplacedName;
string[] filePaths = Directory.GetFiles($"replacedets/{directoryName}", "*.cs", SearchOption.AllDirectories);
foreach (string item in filePaths)
{
if (item.Substring(item.LastIndexOf(@"\") + 1) == $"{fileName}.cs")
{
EditorGUIUtility.PingObject(replacedetDatabase.LoadreplacedetAtPath<Textreplacedet>(item));
replacedetDatabase.Openreplacedet(replacedetDatabase.LoadreplacedetAtPath<Object>(item), 0);
}
}
}
ObjectTypeUtil.Draw(lccView.type, 0);
}
19
Source : HolidayUtil.cs
with MIT License
from 6tail
with MIT License
from 6tail
private static string findBackward(string key)
{
int start = DATA_IN_USE.LastIndexOf(key);
if (start < 0)
{
return null;
}
string left = DATA_IN_USE.Substring(0, start + key.Length);
int size = left.Length;
int n = size % SIZE;
if (n > 0)
{
left = left.Substring(0, size - n);
}
size = left.Length;
while ((!left.EndsWith(key)) && size >= SIZE)
{
left = left.Substring(0, size - SIZE);
size = left.Length;
}
return left;
}
19
Source : Repository.cs
with Apache License 2.0
from AantCoder
with Apache License 2.0
from AantCoder
public static bool CheckIsBanIP(string IP)
{
if ((DateTime.UtcNow - BlockipUpdate).TotalSeconds > 30)
{
var fileName = Loger.PathLog + "blockip.txt";
BlockipUpdate = DateTime.UtcNow;
if (!File.Exists(fileName)) Blockip = new HashSet<string>();
else
try
{
var listBlock = File.ReadAllLines(fileName, Encoding.UTF8);
if (listBlock.Any(b => b.Contains("/")))
{
listBlock = listBlock
.SelectMany(b =>
{
var bb = b.Trim();
var comment = "";
var ic = bb.IndexOf(" ");
if (ic > 0)
{
comment = bb.Substring(ic);
bb = bb.Substring(0, ic);
}
if (bb.Any(c => !char.IsDigit(c) && c != '.' && c != '/')) return new List<string>();
var ls = bb.LastIndexOf("/");
if (ls < 0) return new List<string>() { bb + comment };
var lp = bb.LastIndexOf(".");
if (lp <= 0) return new List<string>();
var ib = int.Parse(bb.Substring(lp + 1, ls - (lp + 1)));
var ie = int.Parse(bb.Substring(ls + 1));
var res = new List<string>();
var s = bb.Substring(0, lp + 1);
for (int i = ib; i <= ie; i++)
res.Add(s + i.ToString() + comment);
return res;
})
.ToArray();
File.WriteAllLines(fileName, listBlock, Encoding.Default);
}
Blockip = new HashSet<string>(listBlock
.Select(b => b.Contains(" ") ? b.Substring(0, b.IndexOf(" ")) : b));
}
catch (Exception exp)
{
Loger.Log("CheckIsBanIP error " + exp.Message);
Blockip = new HashSet<string>();
return false;
}
}
return Blockip.Contains(IP.Trim());
}
19
Source : RunnerService.cs
with MIT License
from actions
with MIT License
from 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
Source : ValueEncoders.cs
with MIT License
from actions
with MIT License
from actions
public static String PowerShellPostAmpersandEscape(String value)
{
var trimmed = string.Empty;
if (!string.IsNullOrEmpty(value) && value.Contains("&"))
{
var secretSection = string.Empty;
if (value.Contains("&+"))
{
// +1 to skip the letter that got colored
secretSection = value.Substring(value.IndexOf("&+") + "&+".Length + 1);
}
else
{
secretSection = value.Substring(value.LastIndexOf("&") + "&".Length);
}
if (secretSection.Length >= 6)
{
trimmed = secretSection;
}
}
return trimmed;
}
19
Source : ValueEncoders.cs
with MIT License
from actions
with MIT License
from actions
public static String PowerShellPreAmpersandEscape(String value)
{
// if the secret is preplaceded to PS as a command and it causes an error, sections of it can be surrounded by color codes
// or printed individually.
// The secret secretpart1&secretpart2&secretpart3 would be split into 2 sections:
// 'secretpart1&secretpart2&' and 'secretpart3'. This method masks for the first section.
// The secret secretpart1&+secretpart2&secretpart3 would be split into 2 sections:
// 'secretpart1&+' and (no 's') 'ecretpart2&secretpart3'. This method masks for the first section.
var trimmed = string.Empty;
if (!string.IsNullOrEmpty(value) && value.Contains("&"))
{
var secretSection = string.Empty;
if (value.Contains("&+"))
{
secretSection = value.Substring(0, value.IndexOf("&+") + "&+".Length);
}
else
{
secretSection = value.Substring(0, value.LastIndexOf("&") + "&".Length);
}
// Don't mask short secrets
if (secretSection.Length >= 6)
{
trimmed = secretSection;
}
}
return trimmed;
}
19
Source : Share.cs
with MIT License
from adamped
with MIT License
from adamped
public Task Show( string replacedle, string message, string filePath)
{
var extension = filePath.Substring(filePath.LastIndexOf(".") + 1).ToLower();
var contentType = string.Empty;
switch (extension)
{
case "pdf":
contentType = "application/pdf";
break;
case "png":
contentType = "image/png";
break;
default:
contentType = "application/octetstream";
break;
}
var intent = new Intent(Intent.ActionSend);
intent.SetType(contentType);
intent.PutExtra(Intent.ExtraStream, Android.Net.Uri.Parse("file://" + filePath));
intent.PutExtra(Intent.ExtraText, message ?? string.Empty);
intent.PutExtra(Intent.ExtraSubject, replacedle ?? string.Empty);
var chooserIntent = Intent.CreateChooser(intent, replacedle ?? string.Empty);
chooserIntent.SetFlags(ActivityFlags.ClearTop);
chooserIntent.SetFlags(ActivityFlags.NewTask);
_context.StartActivity(chooserIntent);
return Task.FromResult(true);
}
19
Source : OrganizationServiceContextExtensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static string EnsureValidFileName(string fileName)
{
return fileName.IndexOf("\\") >= 0 ? fileName.Substring(fileName.LastIndexOf("\\") + 1) : fileName;
}
19
Source : ClonesManager.cs
with MIT License
from adrenak
with MIT License
from adrenak
public static string GetOriginalProjectPath()
{
if (IsClone())
{
/// If this is a clone...
/// Original project path can be deduced by removing the suffix from the clone's path.
string cloneProjectPath = ClonesManager.GetCurrentProject().projectPath;
int index = cloneProjectPath.LastIndexOf(ClonesManager.CloneNameSuffix);
if (index > 0)
{
string originalProjectPath = cloneProjectPath.Substring(0, index);
if (Directory.Exists(originalProjectPath)) return originalProjectPath;
}
return string.Empty;
}
else
{
/// If this is the original, we return its own path.
return ClonesManager.GetCurrentProjectPath();
}
}
19
Source : EditorResources.cs
with MIT License
from AdultLink
with MIT License
from AdultLink
static bool SearchForEditorResourcesPath(out string path)
{
path = string.Empty;
string searchStr = "/PostProcessing/Editor Resources/";
string str = null;
foreach (var replacedetPath in replacedetDatabase.GetAllreplacedetPaths())
{
if (replacedetPath.Contains(searchStr))
{
str = replacedetPath;
break;
}
}
if (str == null)
return false;
path = str.Substring(0, str.LastIndexOf(searchStr) + searchStr.Length);
return true;
}
19
Source : MaterialFactory.cs
with MIT License
from AdultLink
with MIT License
from AdultLink
public Material Get(string shaderName)
{
Material material;
if (!m_Materials.TryGetValue(shaderName, out material))
{
var shader = Shader.Find(shaderName);
if (shader == null)
throw new ArgumentException(string.Format("Shader not found ({0})", shaderName));
material = new Material(shader)
{
name = string.Format("PostFX - {0}", shaderName.Substring(shaderName.LastIndexOf("/") + 1)),
hideFlags = HideFlags.DontSave
};
m_Materials.Add(shaderName, material);
}
return material;
}
19
Source : FolderRegPickerWindow.xaml.cs
with MIT License
from advancedmonitoring
with MIT License
from advancedmonitoring
private void folder_OnExpanded(object sender, RoutedEventArgs e)
{
var item = (TreeViewItem) sender;
try
{
if (item.Items.Count == 1 && (item.Items[0] is TreeViewItem) && ( string.IsNullOrWhiteSpace((string)((TreeViewItem)item.Items[0]).Header)))
{
EdtPath.Text = item.Tag.ToString().Trim();
item.Items.Clear();
try
{
foreach (var s in Directory.GetDirectories(item.Tag.ToString()))
{
var subitem = new TreeViewItem
{
Header = s.Substring(s.LastIndexOf("\\") + 1),
Tag = s
};
try
{
if (Directory.GetDirectories(s).Length != 0)
subitem.Items.Add(new TreeViewItem {Header = ""});
}
catch { /* ignore */ }
subitem.Expanded += folder_OnExpanded;
subitem.Selected += element_OnSelected;
item.Items.Add(subitem);
}
}
catch { /* ignore */ }
}
}
catch { /* ignore */ }
}
19
Source : Resource.cs
with The Unlicense
from aeroson
with The Unlicense
from aeroson
public static bool ResourceInFolderExists(Resource folder, string childName)
{
var lastSlash = folder.originalPath.LastIndexOf("/");
if (lastSlash == -1) lastSlash = 0;
var originalPath = folder.originalPath.Substring(0, lastSlash) + childName;
return File.Exists(MakeRealPath(originalPath));
}
19
Source : Resource.cs
with The Unlicense
from aeroson
with The Unlicense
from aeroson
public static Resource GetResourceInFolder(Resource folder, string childName)
{
var lastSlash = folder.originalPath.LastIndexOf("/");
if (lastSlash == -1) lastSlash = 0;
var originalPath = folder.originalPath.Substring(0, lastSlash) + childName;
return MakeResource(originalPath);
}
19
Source : DatabaseEngine.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
private static string MakeGroup(string[] columns, int group)
{
string sql = string.Empty;
if (group > 0 && group <= columns.Length)
{
List<string> cols = new List<string>();
for (int i = 0; i < group; ++i)
{
var c = columns[i];
if (c.ToLower().Contains(" as "))
cols.Add(c.Substring(c.ToLower().LastIndexOf(" as ") + 4));
else if (c.Contains(" "))
cols.Add(c.Substring(c.LastIndexOf(" ") + 1));
else
cols.Add(c);
}
sql = "GROUP BY " + string.Join(",", cols.ToArray());
}
return sql;
}
19
Source : DatabaseEngine.cs
with GNU General Public License v3.0
from aiportal
with GNU General Public License v3.0
from aiportal
private static string MakeGroup(string[] columns, int group)
{
string sql = string.Empty;
if (group > 0 && group <= columns.Length)
{
StringBuilder cols = new StringBuilder();
for (int i = 0; i < group; ++i)
{
cols.Append(cols.Length > 0? "," : null);
var c = columns[i];
if (c.ToLower().Contains(" as "))
cols.Append(c.Substring(c.ToLower().LastIndexOf(" as ") + 4));
else if (c.Contains(" "))
cols.Append(c.Substring(c.LastIndexOf(" ") + 1));
else
cols.Append(c);
}
sql = cols.Insert(0, " GROUP BY ").Append(" ").ToString();
}
return sql;
}
19
Source : GeneratorTools.cs
with GNU General Public License v3.0
from akaAgar
with GNU General Public License v3.0
from akaAgar
internal static string ParseRandomString(string randomString)
{
while (randomString.Contains("{") && randomString.Contains("{"))
{
int start = randomString.LastIndexOf("{");
string stringLeft = randomString.Substring(start);
if (!stringLeft.Contains("}")) break;
int end = stringLeft.IndexOf("}") + 1;
string segment = randomString.Substring(start, end);
string parsedSegment = segment.Replace("{", "").Replace("}", "").Trim();
string[] items = parsedSegment.Split('|');
string selItem = Toolbox.RandomFrom(items);
randomString = randomString.Replace(segment, selItem);
}
return randomString.Replace("{", "").Replace("}", "").Trim();
}
19
Source : StringExtensions.cs
with MIT License
from akinix
with MIT License
from akinix
public static string Rtrim(this string str, string strchar)
{
return str.Substring(0, str.LastIndexOf(strchar));
}
19
Source : NodeGraphEditor.cs
with MIT License
from aksyr
with MIT License
from aksyr
public virtual void CreateNode(Type type, Vector2 position) {
XNode.Node node = target.AddNode(type);
node.position = position;
if (string.IsNullOrEmpty(node.name)) {
// Automatically remove redundant 'Node' postfix
string typeName = type.Name;
if (typeName.EndsWith("Node")) typeName = typeName.Substring(0, typeName.LastIndexOf("Node"));
node.name = UnityEditor.ObjectNames.NicifyVariableName(typeName);
}
replacedetDatabase.AddObjectToreplacedet(node, target);
if (NodeEditorPreferences.GetSettings().autoSave) replacedetDatabase.Savereplacedets();
NodeEditorWindow.RepaintAll();
}
19
Source : MicroSplatUtilities.cs
with MIT License
from alelievr
with MIT License
from alelievr
public static string RelativePathFromreplacedet(UnityEngine.Object o)
{
string path = null;
if (o != null)
{
path = replacedetDatabase.GetreplacedetPath(o);
}
if (string.IsNullOrEmpty(path))
{
string selectionPath = replacedetDatabase.GetreplacedetPath (Selection.activeObject);
if (!string.IsNullOrEmpty(selectionPath))
{
path = selectionPath;
}
}
if (string.IsNullOrEmpty(path))
{
path = UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene().path;
}
if (string.IsNullOrEmpty(path))
{
path = "replacedets";
}
path = path.Replace("\\", "/");
if (path.Contains("/"))
{
path = path.Substring(0, path.LastIndexOf("/"));
}
path += "/MicroSplatData";
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(path);
}
return path;
}
19
Source : MicroSplatShaderGUI_Compiler.cs
with MIT License
from alelievr
with MIT License
from alelievr
[MenuItem ("replacedets/Create/MicroSplat/MicroSplat Shader")]
public static Shader NewShader()
{
string path = "replacedets";
foreach (UnityEngine.Object obj in Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.replacedets))
{
path = replacedetDatabase.GetreplacedetPath(obj);
if (System.IO.File.Exists(path))
{
path = System.IO.Path.GetDirectoryName(path);
}
break;
}
path = path.Replace("\\", "/");
path = replacedetDatabase.GenerateUniquereplacedetPath(path + "/MicroSplat.shader");
string name = path.Substring(path.LastIndexOf("/"));
name = name.Substring(0, name.IndexOf("."));
MicroSplatCompiler compiler = new MicroSplatCompiler();
compiler.Init();
string ret = compiler.Compile(new string[0], name, name);
System.IO.File.WriteAllText(path, ret);
replacedetDatabase.Refresh();
return replacedetDatabase.LoadreplacedetAtPath<Shader>(path);
}
19
Source : ViewLocator.cs
with GNU General Public License v3.0
from alexdillon
with GNU General Public License v3.0
from alexdillon
public IControl Build(object data)
{
var name = data.GetType().FullName.Replace("ViewModel", "View");
var type = Type.GetType(name);
if (type != null)
{
var control = (Control)Activator.CreateInstance(type);
return control;
}
type = Type.GetType(name.Substring(0, name.LastIndexOf("View")));
if (type != null)
{
var control = (Control)Activator.CreateInstance(type);
return control;
}
return new TextBlock { Text = "Not Found: " + name };
}
19
Source : WpfThemeService.cs
with GNU General Public License v3.0
from alexdillon
with GNU General Public License v3.0
from alexdillon
public void Initialize()
{
// Add default theme style
this.ThemeStyles.Add(this.DefaultThemeStyle, (null, null));
// Load custom theme style
if (Directory.Exists(App.ThemesPath))
{
var files = Directory.GetFiles(App.ThemesPath, "*.xaml");
var themes = files
.Select(f => Path.GetFileNameWithoutExtension(f))
.Where(f => f.EndsWith(".Light", StringComparison.OrdinalIgnoreCase) || f.EndsWith(".Dark", StringComparison.OrdinalIgnoreCase))
.Select(f => f.Substring(0, f.LastIndexOf(".")))
.Distinct();
foreach (var theme in themes)
{
var lightThemePath = Path.Combine(App.ThemesPath, $"{theme}.Light.xaml");
var darkThemePath = Path.Combine(App.ThemesPath, $"{theme}.Dark.xaml");
ResourceDictionary lightDictionary = null;
ResourceDictionary darkDictionary = null;
if (File.Exists(lightThemePath))
{
lightDictionary = new ResourceDictionary() { Source = new Uri(lightThemePath) };
}
if (File.Exists(darkThemePath))
{
darkDictionary = new ResourceDictionary() { Source = new Uri(darkThemePath) };
}
if (!this.ThemeStyles.ContainsKey(theme))
{
this.ThemeStyles.Add(theme, (lightDictionary, darkDictionary));
}
}
}
}
19
Source : HttpServer.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
private string GenerateJSON(Node n) {
string JSON = "{\"id\": " + nodeCount + ", \"Text\": \"" + n.Text
+ "\", \"Children\": [";
nodeCount++;
foreach (Node child in n.Nodes)
JSON += GenerateJSON(child) + ", ";
if (JSON.EndsWith(", "))
JSON = JSON.Remove(JSON.LastIndexOf(","));
JSON += "]";
if (n is SensorNode) {
JSON += ", \"Min\": \"" + ((SensorNode)n).Min + "\"";
JSON += ", \"Value\": \"" + ((SensorNode)n).Value + "\"";
JSON += ", \"Max\": \"" + ((SensorNode)n).Max + "\"";
JSON += ", \"ImageURL\": \"images/transparent.png\"";
} else if (n is HardwareNode) {
JSON += ", \"Min\": \"\"";
JSON += ", \"Value\": \"\"";
JSON += ", \"Max\": \"\"";
JSON += ", \"ImageURL\": \"images_icon/" +
GetHardwareImageFile((HardwareNode)n) + "\"";
} else if (n is TypeNode) {
JSON += ", \"Min\": \"\"";
JSON += ", \"Value\": \"\"";
JSON += ", \"Max\": \"\"";
JSON += ", \"ImageURL\": \"images_icon/" +
GetTypeImageFile((TypeNode)n) + "\"";
} else {
JSON += ", \"Min\": \"\"";
JSON += ", \"Value\": \"\"";
JSON += ", \"Max\": \"\"";
JSON += ", \"ImageURL\": \"images_icon/computer.png\"";
}
JSON += "}";
return JSON;
}
19
Source : VersionInfo.cs
with Apache License 2.0
from Algoryx
with Apache License 2.0
from Algoryx
private static int ParsePreRelease( ref string versionStr, string preReleaseId )
{
var preReleaseIndex = versionStr.LastIndexOf( preReleaseId );
var preReleaseVersion = -1;
if ( preReleaseIndex > 0 ) {
if ( !int.TryParse( versionStr.Substring( preReleaseIndex +
preReleaseId.Length ),
out preReleaseVersion ) ) {
throw new AGXUnity.Exception( $"Unable to parse pre-release id {preReleaseId} with " +
$"version {versionStr.Substring( preReleaseIndex + preReleaseId.Length )}" );
}
versionStr = versionStr.Substring( 0, preReleaseIndex );
}
return preReleaseVersion;
}
19
Source : SmallFunctions.cs
with MIT License
from Alkl58
with MIT License
from Alkl58
public static void GetSourceFrameCount(string source)
{
// Skip Framecount Calculation if it already "exists" (Resume Mode)
if (File.Exists(Path.Combine(Global.temp_path, Global.temp_path_folder, "framecount.log")) == false)
{
// This function calculates the total number of frames
Process process = new Process
{
StartInfo = new ProcessStartInfo()
{
UseShellExecute = false,
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
FileName = "cmd.exe",
WorkingDirectory = Global.FFmpeg_Path,
Arguments = "/C ffmpeg.exe -i " + '\u0022' + source + '\u0022' + " -hide_banner -loglevel 32 -map 0:v:0 -f null -",
RedirectStandardError = true,
RedirectStandardOutput = true
}
};
process.Start();
string stream = process.StandardError.ReadToEnd();
process.WaitForExit();
string tempStream = stream.Substring(stream.LastIndexOf("frame="));
string data = GetBetween(tempStream, "frame=", "fps=");
MainWindow.TotalFrames = int.Parse(data);
Helpers.WriteToFileThreadSafe(data, Path.Combine(Global.temp_path, Global.temp_path_folder, "framecount.log"));
}
else
{
// Reads the first line of the framecount file
MainWindow.TotalFrames = int.Parse(File.ReadLines(Path.Combine(Global.temp_path, Global.temp_path_folder, "framecount.log")).First());
}
}
19
Source : JsonSchemaToMetamodelConverter.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
private bool IsRequired(string id, string name)
{
string parentId;
if (id.Contains("."))
{
parentId = id.Substring(0, id.LastIndexOf("."));
}
else
{
parentId = id;
}
if (_requiredProperties.ContainsKey(parentId))
{
return _requiredProperties[parentId].Contains(name);
}
return false;
}
19
Source : AddToSccCommands.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from AmpScm
static bool AskSetManagedSelectionProjects(CommandEventArgs e, IProjectFileMapper mapper, IAnkhSccService scc, IEnumerable<SccProject> succeededProjects)
{
if (e.DontPrompt || e.IsInAutomation)
return true;
AnkhMessageBox mb = new AnkhMessageBox(e.Context);
StringBuilder sb = new StringBuilder();
bool foundOne = false;
foreach (SccProject project in succeededProjects)
{
ISccProjectInfo info;
if (!scc.IsProjectManaged(project) && null != (info = mapper.GetProjectInfo(project)))
{
if (sb.Length > 0)
sb.Append("', '");
sb.Append(info.ProjectName);
}
foundOne = true;
}
if (!foundOne)
return false; // No need to add when there are no projects
string txt = sb.ToString();
int li = txt.LastIndexOf("', '");
if (li > 0)
txt = txt.Substring(0, li + 1) + CommandStrings.FileAnd + txt.Substring(li + 3);
return DialogResult.Yes == mb.Show(string.Format(CommandStrings.MarkXAsManaged,
txt), AnkhId.PlkProduct, MessageBoxButtons.YesNo);
}
19
Source : TransformingAutoEncoders.cs
with MIT License
from anastasios-stamoulis
with MIT License
from anastasios-stamoulis
double extractLoss(string filename) {
var prefix = "val_metric_";
var pos = filename.LastIndexOf(prefix);
if ( pos<0 ) { return 0; }
var dotPos = filename.LastIndexOf(".model");
if ( dotPos<0 ) { return 0; }
var startPos = pos + prefix.Length;
var lossMetricreplacedtring = filename.Substring(startPos, dotPos - startPos);
var lossMetric = double.Parse(lossMetricreplacedtring);
return lossMetric;
}
19
Source : Util.cs
with MIT License
from anastasios-stamoulis
with MIT License
from anastasios-stamoulis
public static string fullpathForDownloadedFile(string dstDir, string dstFilename) {
var fullpath = string.Empty;
var path = System.IO.Directory.GetCurrentDirectory();
var modelsPath = System.IO.Path.Combine("DeepLearning", dstDir);
var pos = path.LastIndexOf("DeepLearning");
if (pos >= 0) {
fullpath = System.IO.Path.Combine(path.Substring(0, pos), modelsPath);
}
if (!System.IO.Directory.Exists(fullpath)) {
try {
System.IO.Directory.CreateDirectory(fullpath);
}
catch (Exception e) {
System.Console.WriteLine("Could not create directory " + fullpath + "," + e.Message);
fullpath = System.IO.Directory.GetCurrentDirectory();
}
}
fullpath = System.IO.Path.Combine(fullpath, dstFilename);
return fullpath;
}
19
Source : TranslationSource.cs
with GNU General Public License v3.0
from androllen
with GNU General Public License v3.0
from androllen
public static Tuple<string, string> SplitName(string local)
{
int idx = local.ToString().LastIndexOf(".");
var tuple = new Tuple<string, string>(local.Substring(0, idx), local.Substring(idx + 1));
return tuple;
}
19
Source : ModelSaberAPI.cs
with MIT License
from andruzzzhka
with MIT License
from andruzzzhka
public static IEnumerator DownloadAvatarCoroutine(string hash)
{
queuedAvatars.Add(hash);
string downloadUrl = "";
string avatarName = "";
UnityWebRequest www = SongDownloader.GetRequestForUrl("https://modelsaber.com/api/v1/avatar/get.php?filter=hash:" + hash);
www.timeout = 10;
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Plugin.log.Error($"Unable to download avatar! {(www.isNetworkError ? $"Network error: " + www.error : (www.isHttpError ? $"HTTP error: " + www.error : "Unknown error"))}");
queuedAvatars.Remove(hash);
yield break;
}
else
{
Plugin.log.Debug("Received response from ModelSaber...");
JSONNode node = JSON.Parse(www.downloadHandler.text);
if (node.Count == 0)
{
Plugin.log.Error($"Avatar with hash {hash} doesn't exist on ModelSaber!");
cachedAvatars.Add(hash, null);
queuedAvatars.Remove(hash);
yield break;
}
var tags = node[0]["tags"].AsArray;
bool isNSFW = false;
foreach(var child in tags.Values)
{
if(child.Value == "NSFW")
{
isNSFW = true;
}
}
if (isNSFW && !Config.Instance.DownloadNSFWAvatars)
{
Plugin.log.Error($"The avatar is NSFW!");
queuedAvatars.Remove(hash);
nsfwAvatars.Add(hash);
yield break;
}
downloadUrl = node[0]["download"].Value;
avatarName = downloadUrl.Substring(downloadUrl.LastIndexOf("/") + 1);
}
if (string.IsNullOrEmpty(downloadUrl))
{
queuedAvatars.Remove(hash);
yield break;
}
bool timeout = false;
float time = 0f;
UnityWebRequestAsyncOperation asyncRequest;
try
{
www = SongDownloader.GetRequestForUrl(downloadUrl);
www.timeout = 0;
asyncRequest = www.SendWebRequest();
}
catch (Exception e)
{
Plugin.log.Error($"Unable to download avatar! Exception: {e}");
queuedAvatars.Remove(hash);
yield break;
}
while (!asyncRequest.isDone)
{
yield return null;
time += Time.deltaTime;
if ((time >= 5f && asyncRequest.progress <= float.Epsilon))
{
www.Abort();
timeout = true;
Plugin.log.Error("Connection timed out!");
}
}
if (www.isNetworkError || www.isHttpError || timeout)
{
queuedAvatars.Remove(hash);
Plugin.log.Error("Unable to download avatar! " + (www.isNetworkError ? $"Network error: {www.error}" : (www.isHttpError ? $"HTTP error: {www.error}" : "Unknown error")));
}
else
{
Plugin.log.Debug("Received response from ModelSaber...");
string docPath = "";
string customAvatarPath = "";
byte[] data = www.downloadHandler.data;
try
{
docPath = Application.dataPath;
docPath = docPath.Substring(0, docPath.Length - 5);
docPath = docPath.Substring(0, docPath.LastIndexOf("/"));
customAvatarPath = docPath + "/CustomAvatars/" + avatarName;
Plugin.log.Debug($"Saving avatar to \"{customAvatarPath}\"...");
File.WriteAllBytes(customAvatarPath, data);
Plugin.log.Debug("Downloaded avatar!");
Plugin.log.Debug($"Loading avatar...");
SharedCoroutineStarter.instance.StartCoroutine(LoadedAvatar.FromFileCoroutine(avatarName,
(LoadedAvatar avatar) =>
{
queuedAvatars.Remove(hash);
cachedAvatars.Add(hash, avatar);
avatarDownloaded?.Invoke(hash);
}, (Exception ex) =>
{
Plugin.log.Error($"Unable to load avatar! Exception: {ex}");
queuedAvatars.Remove(hash);
}));
}
catch (Exception e)
{
Plugin.log.Critical(e);
queuedAvatars.Remove(hash);
yield break;
}
}
}
19
Source : SongDownloader.cs
with MIT License
from andruzzzhka
with MIT License
from andruzzzhka
public IEnumerator DownloadSongCoroutine(Song songInfo)
{
songInfo.songQueueState = SongQueueState.Downloading;
UnityWebRequest www;
bool timeout = false;
float time = 0f;
UnityWebRequestAsyncOperation asyncRequest;
try
{
www = UnityWebRequest.Get(songInfo.downloadUrl);
asyncRequest = www.SendWebRequest();
}
catch (Exception e)
{
Plugin.log.Error(e);
songInfo.songQueueState = SongQueueState.Error;
songInfo.downloadingProgress = 1f;
yield break;
}
while ((!asyncRequest.isDone || songInfo.downloadingProgress < 1f) && songInfo.songQueueState != SongQueueState.Error)
{
yield return null;
time += Time.deltaTime;
if (time >= 5f && asyncRequest.progress <= float.Epsilon)
{
www.Abort();
timeout = true;
Plugin.log.Error("Connection timed out!");
}
songInfo.downloadingProgress = asyncRequest.progress;
}
if(songInfo.songQueueState == SongQueueState.Error && (!asyncRequest.isDone || songInfo.downloadingProgress < 1f))
www.Abort();
if (www.isNetworkError || www.isHttpError || timeout || songInfo.songQueueState == SongQueueState.Error)
{
songInfo.songQueueState = SongQueueState.Error;
Plugin.log.Error("Unable to download song! " + (www.isNetworkError ? $"Network error: {www.error}" : (www.isHttpError ? $"HTTP error: {www.error}" : "Unknown error")));
}
else
{
Plugin.log.Info("Received response from BeatSaver.com...");
string docPath = "";
string customSongsPath = "";
byte[] data = www.downloadHandler.data;
Stream zipStream = null;
try
{
docPath = Application.dataPath;
docPath = docPath.Substring(0, docPath.Length - 5);
docPath = docPath.Substring(0, docPath.LastIndexOf("/"));
customSongsPath = docPath + "/CustomSongs/" + songInfo.id + "/";
if (!Directory.Exists(customSongsPath))
{
Directory.CreateDirectory(customSongsPath);
}
zipStream = new MemoryStream(data);
Plugin.log.Info("Downloaded zip!");
}
catch (Exception e)
{
Plugin.log.Critical(e);
songInfo.songQueueState = SongQueueState.Error;
yield break;
}
yield return new WaitWhile(() => _extractingZip); //because extracting several songs at once sometimes hangs the game
Task extract = ExtractZipAsync(songInfo, zipStream, customSongsPath);
yield return new WaitWhile(() => !extract.IsCompleted);
songDownloaded?.Invoke(songInfo);
}
}
19
Source : SongDownloader.cs
with MIT License
from andruzzzhka
with MIT License
from andruzzzhka
public void DeleteSong(Song song)
{
bool zippedSong = false;
string path = "";
CustomLevel level = SongLoader.CustomLevels.FirstOrDefault(x => x.levelID.StartsWith(song.hash));
if (level != null)
SongLoader.Instance.RemoveSongWithLevelID(level.levelID);
if (string.IsNullOrEmpty(song.path))
{
if (level != null)
path = level.customSongInfo.path;
}
else
{
path = song.path;
}
if (string.IsNullOrEmpty(path))
return;
if (!Directory.Exists(path))
return;
if (path.Contains("/.cache/"))
zippedSong = true;
Task.Run(() =>
{
if (zippedSong)
{
Plugin.log.Info("Deleting \"" + path.Substring(path.LastIndexOf('/')) + "\"...");
if (PluginConfig.deleteToRecycleBin)
{
FileOperationAPIWrapper.MoveToRecycleBin(path);
}
else
{
Directory.Delete(path, true);
}
string songHash = Directory.GetParent(path).Name;
try
{
if (Directory.GetFileSystemEntries(path.Substring(0, path.LastIndexOf('/'))).Length == 0)
{
Plugin.log.Info("Deleting empty folder \"" + path.Substring(0, path.LastIndexOf('/')) + "\"...");
Directory.Delete(path.Substring(0, path.LastIndexOf('/')), false);
}
}
catch
{
Plugin.log.Warn("Can't find or delete empty folder!");
}
string docPath = Application.dataPath;
docPath = docPath.Substring(0, docPath.Length - 5);
docPath = docPath.Substring(0, docPath.LastIndexOf("/"));
string customSongsPath = docPath + "/CustomSongs/";
string hash = "";
foreach (string file in Directory.GetFiles(customSongsPath, "*.zip"))
{
if (CreateMD5FromFile(file, out hash))
{
if (hash == songHash)
{
File.Delete(file);
break;
}
}
}
}
else
{
Plugin.log.Info("Deleting \"" + path.Substring(path.LastIndexOf('/')) + "\"...");
if (PluginConfig.deleteToRecycleBin)
{
FileOperationAPIWrapper.MoveToRecycleBin(path);
}
else
{
Directory.Delete(path, true);
}
try
{
if (Directory.GetFileSystemEntries(path.Substring(0, path.LastIndexOf('/'))).Length == 0)
{
Plugin.log.Info("Deleting empty folder \"" + path.Substring(0, path.LastIndexOf('/')) + "\"...");
Directory.Delete(path.Substring(0, path.LastIndexOf('/')), false);
}
}
catch
{
Plugin.log.Warn("Unable to delete empty folder!");
}
}
Plugin.log.Info($"{_alreadyDownloadedSongs.RemoveAll(x => x.Compare(song))} song removed");
}).ConfigureAwait(false);
}
See More Examples