Here are the examples of the csharp api string.LastIndexOf(char) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1934 Examples
19
View Source File : TerrariaHooksManager.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
internal static ModuleDefinition GenerateCecilModule(replacedemblyName name) {
replacedemblyName UnwrapName(replacedemblyName other) {
int underscore = other.Name.LastIndexOf('_');
if (underscore == -1)
return other;
other.Name = other.Name.Substring(0, underscore);
return other;
}
// Terraria ships with some dependencies as embedded resources.
string resourceName = name.Name + ".dll";
resourceName = Array.Find(typeof(Program).replacedembly.GetManifestResourceNames(), element => element.EndsWith(resourceName));
if (resourceName != null) {
using (Stream stream = typeof(Program).replacedembly.GetManifestResourceStream(resourceName))
// Read immediately, as the stream isn't open forever.
return ModuleDefinition.ReadModule(stream, new ReaderParameters(ReadingMode.Immediate));
}
// Mod .dlls exist in the mod's .tmod containers.
string nameStr = name.ToString();
foreach (Mod mod in ModLoader.LoadedMods) {
if (mod.Code == null || mod.File == null)
continue;
// Check if it's the main replacedembly.
if (mod.Code.GetName().ToString() == nameStr) {
// Let's unwrap the name and cache it for all DMDs as well.
// tModLoader changes the replacedembly name to allow mod updates, which breaks replacedembly.Load
ReflectionHelper.replacedemblyCache[UnwrapName(mod.Code.GetName()).ToString()] = mod.Code;
using (MemoryStream stream = new MemoryStream(mod.File.GetMainreplacedembly()))
// Read immediately, as the stream isn't open forever.
return ModuleDefinition.ReadModule(stream, new ReaderParameters(ReadingMode.Immediate));
}
// Check if the replacedembly is possibly included in the .tmod
if (!mod.Code.GetReferencedreplacedemblies().Any(other => UnwrapName(other).ToString() == nameStr))
continue;
// Try to load lib/Name.dll
byte[] data;
if ((data = mod.File.GetFile($"lib/{name.Name}.dll")) != null)
using (MemoryStream stream = new MemoryStream(data))
// Read immediately, as the stream isn't open forever.
return ModuleDefinition.ReadModule(stream, new ReaderParameters(ReadingMode.Immediate));
}
return null;
}
19
View Source File : Program.cs
License : MIT License
Project Creator : 0xDivyanshu
License : MIT License
Project Creator : 0xDivyanshu
public static string RemoveMatchingQuotes(string stringToTrim)
{
var firstQuoteIndex = stringToTrim.IndexOf('"');
var lastQuoteIndex = stringToTrim.LastIndexOf('"');
while (firstQuoteIndex != lastQuoteIndex)
{
stringToTrim = stringToTrim.Remove(firstQuoteIndex, 1);
stringToTrim = stringToTrim.Remove(lastQuoteIndex - 1, 1); //-1 because we've shifted the indicies left by one
firstQuoteIndex = stringToTrim.IndexOf('"');
lastQuoteIndex = stringToTrim.LastIndexOf('"');
}
return stringToTrim;
}
19
View Source File : MethodJitter.cs
License : MIT License
Project Creator : 0xd4d
License : MIT License
Project Creator : 0xd4d
static string MakeClrmdTypeName(string name) {
if (name.Length > 0 && char.IsDigit(name[name.Length - 1])) {
int index = name.LastIndexOf('`');
if (index >= 0)
return name.Substring(0, index);
}
return name;
}
19
View Source File : TypeConverterHelper.cs
License : MIT License
Project Creator : 1iveowl
License : MIT License
Project Creator : 1iveowl
private static string GetScope(string name)
{
var indexOfLastPeriod = name.LastIndexOf('.');
if (indexOfLastPeriod != name.Length - 1)
{
return name.Substring(0, indexOfLastPeriod);
}
return name;
}
19
View Source File : Program.cs
License : MIT License
Project Creator : 2401dem
License : MIT License
Project Creator : 2401dem
public static int Denoise()
{
if (_is_folder)
{
if (Directory.Exists(_input_path) || Directory.Exists(_input_path.Substring(0, _input_path.LastIndexOf('\\') > 0 ? _input_path.LastIndexOf('\\') : 0)))
{
if (Directory.Exists(_output_path) || Directory.Exists(_output_path.Substring(0, _output_path.LastIndexOf('\\') > 0 ? _output_path.LastIndexOf('\\') : 0)))
{
var file_paths = Directory.GetFiles(_input_path, "*.*", SearchOption.TopDirectoryOnly);
List<string> input_file_paths = new List<string>();
List<string> output_file_paths = new List<string>();
foreach (string file_path in file_paths)
{
Regex regex = new Regex(".\\.(bmp|jpg|png|tif|exr)$", RegexOptions.IgnoreCase);
if (regex.IsMatch(file_path))
{
input_file_paths.Add(file_path);
output_file_paths.Add(_output_path + "\\out_" + file_path.Substring(file_path.LastIndexOf('\\') + 1));
Console.WriteLine(file_path);
}
}
int width = _getWidth(input_file_paths[0].ToCharArray());
int height = _getHeight(input_file_paths[0].ToCharArray());
if (width == -1 || height == -1)
{
MessageBox.Show("Picture Format Error!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
Program.form1.unlockButton();
return -1;
}
//Bitmap pBuffer = new Bitmap(input_file_paths[0], false);
IntPtr tmpptr = new IntPtr();
_jobStart(width, height, _blend);
for (int i = 0; i < input_file_paths.Count; ++i)
{
Program.form1.SetProgress((float)i / (float)input_file_paths.Count);
if (File.Exists(output_file_paths[i]))
continue;
//IntPtr tmpptr =
tmpptr = _denoiseImplement(input_file_paths[i].ToCharArray(), output_file_paths[i].ToCharArray(), _blend, _is_folder);
/*if (tmpptr != null)
if (Program.form1.DrawToPictureBox(tmpptr, pBuffer.Width, pBuffer.Height) == 0)
continue;
else
{
MessageBox.Show("Picture Size Error!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
break;
}
else
{
//MessageBox.Show("Picture Size Error!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
//break;
}*/
}
_jobComplete();
if (tmpptr != null)
if (Program.form1.DrawToPictureBox(tmpptr, width, height) != 0)
MessageBox.Show("Picture Size Error!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
Program.form1.SetProgress(1.0f);
Program.form1.unlockButton();
return 0;
}
else
MessageBox.Show("Output folder does not exists!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
MessageBox.Show("Input folder does not exists!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
if (File.Exists(_input_path))
{
if (Directory.Exists(_output_path.Substring(0, _output_path.LastIndexOf('\\'))))
{
int width = _getWidth(_input_path.ToCharArray());
int height = _getHeight(_input_path.ToCharArray());
Console.WriteLine(width.ToString());
Console.WriteLine(height.ToString());
if (width == -1 || height == -1)
{
MessageBox.Show("Picture Format Error!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
Program.form1.unlockButton();
return -1;
}
_jobStart(width, height, _blend);
IntPtr tmpptr = _denoiseImplement(_input_path.ToCharArray(), _output_path.ToCharArray(), _blend, _is_folder);
if (tmpptr != null)
{
if (Program.form1.DrawToPictureBox(tmpptr, width, height) == -1)
MessageBox.Show("Picture Size Error(NULL to Draw)!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
MessageBox.Show("Picture Size Error!(NULL Return)", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
Program.form1.SetProgress(1.0f);
Program.form1.unlockButton();
_jobComplete();
return 0;
}
else
MessageBox.Show("Output folder does not exists!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
MessageBox.Show("Input file does not exists!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
Program.form1.unlockButton();
return -1;
}
19
View Source File : Form1.cs
License : MIT License
Project Creator : 2401dem
License : MIT License
Project Creator : 2401dem
private void button1_Click(object sender, EventArgs e)
{
if (IsFolder)
{
CommonOpenFileDialog dialog = new CommonOpenFileDialog();
dialog.IsFolderPicker = true;
if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
{
string tmp = dialog.FileName;
if (tmp.LastIndexOf('\\') != -1)
{
textBox1.Text = tmp;
if (!Directory.Exists(textBox2.Text))
textBox2.Text = tmp;
}
}
}
else
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Supported Files (*.bmp, *.jpg, *.png, *.tif, *.exr)|*.jpg;*.png;*.bmp;*.tif;*.exr|Bitmap Images (*.bmp)|*.bmp|JPEG Images (*.jpg)|*.jpg|PNG Images (*.png)|*.png|TIFF Images (*.tif)|*.tif|OpenEXR Images (*.exr)|*.exr";
if (dialog.ShowDialog() == DialogResult.OK)
{
string tmp = dialog.FileName;
if (tmp.LastIndexOf('\\') != -1)
{
textBox1.Text = tmp;
textBox2.Text = tmp.Substring(0, tmp.LastIndexOf('\\') + 1) + "out_" + tmp.Substring(tmp.LastIndexOf('\\') + 1);
}
}
}
}
19
View Source File : Form1.cs
License : MIT License
Project Creator : 2401dem
License : MIT License
Project Creator : 2401dem
private void button2_Click(object sender, EventArgs e)
{
if (IsFolder)
{
CommonOpenFileDialog dialog = new CommonOpenFileDialog();
dialog.IsFolderPicker = true;
if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
{
string tmp = dialog.FileName;
if (tmp.LastIndexOf('\\') != -1)
{
textBox2.Text = tmp;
}
}
}
else
{
SaveFileDialog dialog = new SaveFileDialog();
dialog.Filter = "Bitmap Images (*.bmp)|*.bmp|JPEG Images (*.jpg)|*.jpg|PNG Images (*.png)|*.png|TIFF Images (*.tif)|*.tif|OpenEXR Images (*.exr)|*.exr";
if (dialog.ShowDialog() == DialogResult.OK)
{
string tmp = dialog.FileName;
if (tmp.LastIndexOf('\\') != -1)
{
textBox2.Text = tmp;
}
}
}
}
19
View Source File : DynamicProxy.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
static replacedembly CompileCode(string cscode)
{
var files = Directory.GetFiles(Directory.GetParent(Type.GetType("FreeSql.DynamicProxy, FreeSql.DynamicProxy").replacedembly.Location).FullName);
using (var compiler = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("cs"))
{
var objCompilerParameters = new System.CodeDom.Compiler.CompilerParameters();
objCompilerParameters.Referencedreplacedemblies.Add("System.dll");
objCompilerParameters.Referencedreplacedemblies.Add("System.Core.dll");
objCompilerParameters.Referencedreplacedemblies.Add("FreeSql.DynamicProxy.dll");
foreach (var dll in files)
{
if (!dll.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) &&
!dll.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) continue;
Console.WriteLine(dll);
var dllName = string.Empty;
var idx = dll.LastIndexOf('/');
if (idx != -1) dllName = dll.Substring(idx + 1);
else
{
idx = dll.LastIndexOf('\\');
if (idx != -1) dllName = dll.Substring(idx + 1);
}
if (string.IsNullOrEmpty(dllName)) continue;
try
{
var replaced = replacedembly.LoadFile(dll);
objCompilerParameters.Referencedreplacedemblies.Add(dllName);
}
catch
{
}
}
objCompilerParameters.GenerateExecutable = false;
objCompilerParameters.GenerateInMemory = true;
var cr = compiler.CompilereplacedemblyFromSource(objCompilerParameters, cscode);
if (cr.Errors.Count > 0)
throw new DynamicProxyException($"FreeSql.DynamicProxy 失败提示:{cr.Errors[0].ErrorText} {cscode}", null);
return cr.Compiledreplacedembly;
}
}
19
View Source File : BeatmapConverter.cs
License : MIT License
Project Creator : 39M
License : MIT License
Project Creator : 39M
static void Convert()
{
Debug.Log(string.Format("Source path: {0}", beatmapPath));
// 每个目录代表一首歌,里面按字典序放置至多三个谱面,依次为 Easy, Normal, Hard
string[] sourceDirectories = Directory.GetDirectories(beatmapPath);
foreach (string directoryPath in sourceDirectories)
{
Music music = new Music();
// 遍历单个目录下的所有 osu 文件,对每个文件创建一个 Beatmap 对象,加到 Music 对象里面
string[] sourceFiles = Directory.GetFiles(directoryPath, "*.osu");
int count = 0;
foreach (string filepath in sourceFiles)
{
string[] lines = File.ReadAllLines(filepath);
Beatmap beatmap = new Beatmap();
music.beatmapList.Add(beatmap);
#region Set Difficulty
beatmap.difficultyName = difficultyNames[Mathf.Min(count, difficultyNames.Length - 1)];
beatmap.difficultyDisplayColor = new SimpleColor(difficultyColors[Mathf.Min(count, difficultyNames.Length - 1)]);
count++;
#endregion
#region Processing file line by line
bool startProcessNotes = false;
foreach (string line in lines)
{
if (line.StartsWith("[HitObjects]"))
{
startProcessNotes = true;
continue;
}
if (!startProcessNotes)
{
// 处理谱面信息
int lastIndex = line.LastIndexOf(':');
if (lastIndex < 0)
{
// 如果不是有效信息行则跳过
continue;
}
string value = line.Substring(lastIndex + 1).Trim();
if (line.StartsWith("replacedle"))
{
music.replacedle = value;
}
else if (line.StartsWith("Artist"))
{
music.artist = value;
}
else if (line.StartsWith("AudioFilename"))
{
value = value.Remove(value.LastIndexOf('.'));
music.audioFilename = value;
music.bannerFilename = value;
music.soundEffectFilename = value;
}
else if (line.StartsWith("PreviewTime"))
{
music.previewTime = float.Parse(value) / 1000;
}
else if (line.StartsWith("Creator"))
{
beatmap.creator = value;
}
else if (line.StartsWith("Version"))
{
beatmap.version = value;
}
}
else
{
// 开始处理 HitObject
string[] noteInfo = line.Split(',');
int type = int.Parse(noteInfo[3]);
if ((type & 0x01) != 0)
{
// Circle
beatmap.noteList.Add(new Note
{
x = int.Parse(noteInfo[0]),
y = int.Parse(noteInfo[1]),
time = float.Parse(noteInfo[2]) / 1000,
// 其他 Circle 相关的处理
});
}
else if ((type & 0x02) != 0)
{
// Slider
beatmap.noteList.Add(new Note
{
x = int.Parse(noteInfo[0]),
y = int.Parse(noteInfo[1]),
time = float.Parse(noteInfo[2]) / 1000,
// 其他 Slider 相关的处理
});
}
else if ((type & 0x08) != 0)
{
// Spinner
beatmap.noteList.Add(new Note
{
x = int.Parse(noteInfo[0]),
y = int.Parse(noteInfo[1]),
time = float.Parse(noteInfo[2]) / 1000,
// 其他 Spinner 相关的处理
});
beatmap.noteList.Add(new Note
{
x = int.Parse(noteInfo[0]),
y = int.Parse(noteInfo[1]),
time = float.Parse(noteInfo[5]) / 1000,
// 其他 Spinner 相关的处理
});
}
}
}
#endregion
}
string targetPath = directoryPath + ".json";
if (File.Exists(targetPath))
{
File.Delete(targetPath);
}
File.WriteAllText(targetPath, music.ToJson());
Debug.Log(string.Format("Converted osu! beatmap\n[{0}]\nto json file\n[{1}]", directoryPath, targetPath));
}
Debug.Log(string.Format("All done, converted {0} files.", sourceDirectories.Length));
}
19
View Source File : Utils.cs
License : MIT License
Project Creator : 39M
License : MIT License
Project Creator : 39M
public static string RemoveExtensionName(string path)
{
int index = path.LastIndexOf('.');
if (index >= 0)
{
if (extensionNameList.Contains(path.Substring(index)))
{
path = path.Remove(index);
}
}
return path;
}
19
View Source File : GCodeFile.cs
License : MIT License
Project Creator : 3RD-Dimension
License : MIT License
Project Creator : 3RD-Dimension
public static GCodeFile Load(string path)
{
GCodeParser.Reset();
GCodeParser.ParseFile(path);
GCodeFile gcodeFile = new GCodeFile(GCodeParser.Commands) { FileName = path.Substring(path.LastIndexOf('\\') + 1) };
gcodeFile.Warnings.InsertRange(0, GCodeParser.Warnings);
return gcodeFile;
}
19
View Source File : LogConfigUtil.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
public static string GetFilePath(string data)
{
int start = data.IndexOf("(at ") + 4;
int end = data.LastIndexOf(':');
return data.Substring(start, end - start);
}
19
View Source File : LogConfigUtil.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
public static int GetFileLine(string data)
{
int start = data.LastIndexOf(':') + 1;
int end = data.LastIndexOf(')');
return int.Parse(data.Substring(start, end - start));
}
19
View Source File : ExternalLoginInfoHelper.cs
License : MIT License
Project Creator : 52ABP
License : MIT License
Project Creator : 52ABP
public static (string name, string surname) GetNameAndSurnameFromClaims(List<Claim> claims)
{
string name = null;
string surname = null;
var givennameClaim = claims.FirstOrDefault(c => c.Type == ClaimTypes.GivenName);
if (givennameClaim != null && !givennameClaim.Value.IsNullOrEmpty())
{
name = givennameClaim.Value;
}
var surnameClaim = claims.FirstOrDefault(c => c.Type == ClaimTypes.Surname);
if (surnameClaim != null && !surnameClaim.Value.IsNullOrEmpty())
{
surname = surnameClaim.Value;
}
if (name == null || surname == null)
{
var nameClaim = claims.FirstOrDefault(c => c.Type == ClaimTypes.Name);
if (nameClaim != null)
{
var nameSurName = nameClaim.Value;
if (!nameSurName.IsNullOrEmpty())
{
var lastSpaceIndex = nameSurName.LastIndexOf(' ');
if (lastSpaceIndex < 1 || lastSpaceIndex > (nameSurName.Length - 2))
{
name = surname = nameSurName;
}
else
{
name = nameSurName.Substring(0, lastSpaceIndex);
surname = nameSurName.Substring(lastSpaceIndex);
}
}
}
}
return (name, surname);
}
19
View Source File : FrmLauncher.cs
License : GNU General Public License v3.0
Project Creator : 9vult
License : GNU General Public License v3.0
Project Creator : 9vult
private replacedle GetSelected()
{
replacedle selected = null;
if (tabControl1.SelectedTab == tabpageManga)
{
string selectedText = lstManga.SelectedItem.ToString();
string name = selectedText.Substring(0, selectedText.LastIndexOf('»')).Trim();
foreach (Manga m in WFClient.dbm.GetMangaPopulation())
{
if (m.GetUserreplacedle().StartsWith(name))
{
selected = m;
break;
}
}
}
else // Hentai
{
string selectedText = lstHentai.SelectedItem.ToString();
string name = selectedText.Substring(0, selectedText.LastIndexOf('»')).Trim();
foreach (Hentai h in WFClient.dbm.GetHentaiPopulation())
{
if (h.GetUserreplacedle().StartsWith(name))
{
selected = h;
break;
}
}
}
if (selected != null)
{
return selected;
}
else
MessageBox.Show(ll.Msg_notfound);
return null;
}
19
View Source File : UmaSlotBuilderWindow.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : A7ocin
private void GetMaterialName(string name, UnityEngine.Object obj)
{
if (relativeFolder != null)
{
var relativeLocation = replacedetDatabase.GetreplacedetPath(relativeFolder);
var replacedetLocation = replacedetDatabase.GetreplacedetPath(obj);
if (replacedetLocation.StartsWith(relativeLocation, System.StringComparison.InvariantCultureIgnoreCase))
{
string temp = replacedetLocation.Substring(relativeLocation.Length + 1); // remove the prefix
temp = temp.Substring(0, temp.LastIndexOf('/') + 1); // remove the replacedet name
slotName = temp + name; // add the cleaned name
}
}
else
{
slotName = name;
}
}
19
View Source File : UmaSlotBuilderWindow.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : A7ocin
string GetreplacedetFolder()
{
int index = slotName.LastIndexOf('/');
if( index > 0 )
{
return slotName.Substring(0, index+1);
}
return "";
}
19
View Source File : UmaSlotBuilderWindow.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : A7ocin
string GetreplacedetName()
{
int index = slotName.LastIndexOf('/');
if (index > 0)
{
return slotName.Substring(index + 1);
}
return slotName;
}
19
View Source File : UmaSlotBuilderWindow.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : A7ocin
public void EnforceFolder(ref UnityEngine.Object folderObject)
{
if (folderObject != null)
{
string destpath = replacedetDatabase.GetreplacedetPath(folderObject);
if (string.IsNullOrEmpty(destpath))
{
folderObject = null;
}
else if (!System.IO.Directory.Exists(destpath))
{
destpath = destpath.Substring(0, destpath.LastIndexOf('/'));
folderObject = replacedetDatabase.LoadMainreplacedetAtPath(destpath);
}
}
}
19
View Source File : BTCChinaAPI.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
private string DoMethod(NameValueCollection jParams)
{
const int RequestTimeoutMilliseconds = 2*1000; // 2 sec
string tempResult = "";
try
{
lock (m_tonceLock)
{
//get tonce
TimeSpan timeSpan = DateTime.UtcNow - genesis;
long milliSeconds = Convert.ToInt64(timeSpan.TotalMilliseconds*1000);
jParams[pTonce] = Convert.ToString(milliSeconds, CultureInfo.InvariantCulture);
//mock json request id
jParams[pId] = jsonRequestID.Next().ToString(CultureInfo.InvariantCulture);
//build http head
string paramsHash = GetHMACSHA1Hash(jParams);
string base64String = Convert.ToBase64String(Encoding.ASCII.GetBytes(accessKey + ':' + paramsHash));
string postData = "{\"method\": \"" + jParams[pMethod] + "\", \"params\": [" + jParams[pParams] + "], \"id\": " +
jParams[pId] + "}";
//get webrequest,respawn new object per call for multiple connections
var webRequest = (HttpWebRequest) WebRequest.Create(url);
webRequest.Timeout = RequestTimeoutMilliseconds;
var bytes = Encoding.ASCII.GetBytes(postData);
webRequest.Method = jParams[pRequestMethod];
webRequest.ContentType = "application/json-rpc";
webRequest.ContentLength = bytes.Length;
webRequest.Headers["Authorization"] = "Basic " + base64String;
webRequest.Headers["Json-Rpc-Tonce"] = jParams[pTonce];
// Send the json authentication post request
using (var dataStream = webRequest.GetRequestStream())
{
dataStream.Write(bytes, 0, bytes.Length);
}
// Get authentication response
using (var response = webRequest.GetResponse())
{
using (var stream = response.GetResponseStream())
{
// ReSharper disable once replacedignNullToNotNullAttribute
using (var reader = new StreamReader(stream))
{
tempResult = reader.ReadToEnd();
}
}
}
}
}
catch (WebException ex)
{
throw new BTCChinaException(jParams[pMethod], jParams[pId], ex.Message, ex);
}
//there are two kinds of API response, result or error.
if (tempResult.IndexOf("result", StringComparison.Ordinal) < 0)
{
throw new BTCChinaException(jParams[pMethod], jParams[pId], "API error:\n" + tempResult);
}
//compare response id with request id and remove it from result
try
{
int cutoff = tempResult.LastIndexOf(':') + 2;//"id":"1"} so (last index of ':')+2=length of cutoff=start of id-string
string idString = tempResult.Substring(cutoff, tempResult.Length - cutoff - 2);//2=last "}
if (idString != jParams[pId])
{
throw new BTCChinaException(jParams[pMethod], jParams[pId], "JSON-request id is not equal with JSON-response id.");
}
else
{
//remove json request id from response json string
int fromComma = tempResult.LastIndexOf(',');
int toLastBrace = tempResult.Length - 1;
tempResult = tempResult.Remove(fromComma, toLastBrace - fromComma);
}
}
catch (ArgumentOutOfRangeException ex)
{
throw new BTCChinaException(jParams[pMethod], jParams[pId], "Argument out of range in parsing JSON response id:" + ex.Message, ex);
}
return tempResult;
}
19
View Source File : UMAUtils.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : A7ocin
public static string GetreplacedetFolder(string path)
{
int index = path.LastIndexOf('/');
if( index > 0 )
{
return path.Substring(0, index);
}
return "";
}
19
View Source File : BTCChinaWebSocketApi.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
private void btc_MessageReceived(object sender, MessageReceivedEventArgs e)
{
int eioMessageType;
if (int.TryParse(e.Message.Substring(0, 1), out eioMessageType))
{
switch ((EngineioMessageType)eioMessageType)
{
case EngineioMessageType.PING:
//replace incoming PING with PONG in incoming message and resend it.
m_webSocket.Send(string.Format(CultureInfo.InvariantCulture, "{0}{1}", (int)EngineioMessageType.PONG, e.Message.Substring(1, e.Message.Length - 1)));
break;
case EngineioMessageType.PONG:
m_pong = true;
break;
case EngineioMessageType.MESSAGE:
int sioMessageType;
if (int.TryParse(e.Message.Substring(1, 1), out sioMessageType))
{
switch ((SocketioMessageType)sioMessageType)
{
case SocketioMessageType.CONNECT:
//Send "42["subscribe",["marketdata_cnybtc","marketdata_cnyltc","marketdata_btcltc"]]"
m_webSocket.Send(string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", (int)EngineioMessageType.MESSAGE,
(int)SocketioMessageType.EVENT,
// "[\"subscribe\",[\"marketdata_cnybtc\",\"marketdata_cnyltc\",\"grouporder_cnybtc\"]]"
"[\"subscribe\",[\"grouporder_cnybtc\"]]"
)
);
break;
case SocketioMessageType.EVENT:
if (e.Message.Substring(4, 5) == "trade")//listen on "trade"
Log.Info("[BtcChina] TRADE: " + e.Message.Substring(e.Message.IndexOf('{'), e.Message.LastIndexOf('}') - e.Message.IndexOf('{') + 1));
else
if (e.Message.Substring(4, 10) == "grouporder")//listen on "trade")
{
Log.Info("[BtcChina] grouporder event");
var json = e.Message.Substring(e.Message.IndexOf('{'), e.Message.LastIndexOf('}') - e.Message.IndexOf('{') + 1);
var objResponse = JsonConvert.DeserializeObject<WsGroupOrderMessage>(json);
OnMessageGroupOrder(objResponse.GroupOrder);
}
else
{
Log.Warn("[BtcChina] Unknown message: " + e.Message.Substring(0, 100));
}
break;
default:
Log.Error("[BtcChina] error switch socket.io messagetype: " + e.Message);
break;
}
}
else
{
Log.Error("[BtcChina] error parse socket.io messagetype!");
}
break;
default:
Log.Error("[BtcChina] error switch engine.io messagetype");
break;
}
}
else
{
Log.Error("[BtcChina] error parsing engine.io messagetype!");
}
}
19
View Source File : ChangesetConverter.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
private static string ConvertFileExtensionToLowerCase(string fileName)
{
var slashIndex = Math.Max(fileName.LastIndexOf('/'), fileName.LastIndexOf('\\'));
var pointIndex = fileName.LastIndexOf('.');
if (pointIndex < slashIndex || pointIndex < 1 || pointIndex >= fileName.Length - 1)
return fileName;
#pragma warning disable CA1308 // Normalize strings to uppercase
return fileName.Substring(0, pointIndex + 1) + fileName.Substring(pointIndex + 1, fileName.Length - (pointIndex + 1)).ToLowerInvariant();
#pragma warning restore CA1308 // Normalize strings to uppercase
}
19
View Source File : Program.cs
License : Apache License 2.0
Project Creator : aaaddress1
License : Apache License 2.0
Project Creator : aaaddress1
static void Main(string[] args)
{
printMenu();
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
if (args.Length < 1) {
log("usage: xlsKami.exe [path/to/xls]", ConsoleColor.Red);
return;
}
WorkbookEditor wbe;
try {
wbe = new WorkbookEditor(LoadDecoyDoreplacedent(args[0]));
}
catch (Exception e) {
log(e.Message, ConsoleColor.Red);
return;
}
for (bool bye = false; !bye; ) {
try {
printMenu(showMenu: true, loadXlsPath: args[0]);
switch (Convert.ToInt32(Console.ReadLine())) {
case 1:
log("[+] Enter Mode: Label Patching\n", ConsoleColor.Cyan);
wbe = cmd_ModifyLabel(wbe);
log("[+] Exit Mode\n", ConsoleColor.Cyan);
break;
case 2:
log("[+] Enter Mode: Sheet Patching\n", ConsoleColor.Cyan);
wbe = cmd_ModifySheet(wbe);
log("[!] Exit Mode\n", ConsoleColor.Cyan);
break;
case 3:
WorkbookStream createdWorkbook = wbe.WbStream;
ExcelDocWriter writer = new ExcelDocWriter();
string outputPath = args[0].Insert(args[0].LastIndexOf('.'), "_infect");
Console.WriteLine("Writing generated doreplacedent to {0}", outputPath);
writer.WriteDoreplacedent(outputPath, createdWorkbook, null);
bye = true;
break;
case 4:
bye = true;
break;
}
}
catch (Exception) { }
}
Console.WriteLine("Thanks for using xlsKami\nbye.\n");
}
19
View Source File : V2Loader.cs
License : MIT License
Project Creator : Abdesol
License : MIT License
Project Creator : Abdesol
static XshdReference<XshdRuleSet> ParseRuleSetReference(XmlReader reader)
{
string ruleSet = reader.GetAttribute("ruleSet");
if (ruleSet != null) {
// '/' is valid in highlighting definition names, so we need the last occurence
int pos = ruleSet.LastIndexOf('/');
if (pos >= 0) {
return new XshdReference<XshdRuleSet>(ruleSet.Substring(0, pos), ruleSet.Substring(pos + 1));
} else {
return new XshdReference<XshdRuleSet>(null, ruleSet);
}
} else {
return new XshdReference<XshdRuleSet>();
}
}
19
View Source File : V2Loader.cs
License : MIT License
Project Creator : Abdesol
License : MIT License
Project Creator : Abdesol
static XshdReference<XshdColor> ParseColorReference(XmlReader reader)
{
string color = reader.GetAttribute("color");
if (color != null) {
int pos = color.LastIndexOf('/');
if (pos >= 0) {
return new XshdReference<XshdColor>(color.Substring(0, pos), color.Substring(pos + 1));
} else {
return new XshdReference<XshdColor>(null, color);
}
} else {
return new XshdReference<XshdColor>(ParseColorAttributes(reader));
}
}
19
View Source File : TypeReferencePropertyDrawer.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
private static string FormatGroupedTypeName(Type type, TypeGrouping grouping)
{
string name = type.FullName;
switch (grouping)
{
case TypeGrouping.None:
return name;
case TypeGrouping.ByNamespace:
return string.IsNullOrEmpty(name) ? string.Empty : name.Replace('.', '/');
case TypeGrouping.ByNamespaceFlat:
int lastPeriodIndex = string.IsNullOrEmpty(name) ? -1 : name.LastIndexOf('.');
if (lastPeriodIndex != -1)
{
name = string.IsNullOrEmpty(name)
? string.Empty
: $"{name.Substring(0, lastPeriodIndex)}/{name.Substring(lastPeriodIndex + 1)}";
}
return name;
case TypeGrouping.ByAddComponentMenu:
var addComponentMenuAttributes = type.GetCustomAttributes(typeof(AddComponentMenu), false);
if (addComponentMenuAttributes.Length == 1)
{
return ((AddComponentMenu)addComponentMenuAttributes[0]).componentMenu;
}
Debug.replacedert(type.FullName != null);
return $"Scripts/{type.FullName.Replace('.', '/')}";
default:
throw new ArgumentOutOfRangeException(nameof(grouping), grouping, null);
}
}
19
View Source File : Example.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
private void LoadCode()
{
try
{
_sourceFilePaths.ForEach(file =>
{
var index = file.LastIndexOf('/') + 1;
var fileName = file.Substring(index).Replace(".txt", String.Empty);
_sourceFiles[fileName] = ExampleLoader.LoadSourceFile(file);
});
}
catch (Exception ex)
{
throw new Exception(string.Format("An error occurred when parsing the source-code files for Example '{0}'", replacedle), ex);
}
}
19
View Source File : ProjectWriter.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
private static string GetExampleNamespace(string xamlFile, out string xamlFileName)
{
var xml = XDoreplacedent.Parse(xamlFile);
if (xml.Root != null)
{
var xClreplacedAttribute = xml.Root.Attributes().FirstOrDefault(x => x.Name.LocalName == "Clreplaced");
if (xClreplacedAttribute != null)
{
var clreplacedNs = xClreplacedAttribute.Value;
var index = clreplacedNs.LastIndexOf('.');
if (index > 0)
{
xamlFileName = clreplacedNs.Substring(index + 1, clreplacedNs.Length - index - 1);
return clreplacedNs.Substring(0, index);
}
}
}
xamlFileName = null;
return null;
}
19
View Source File : LootSwap.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 Dictionary<string, Type> GetTypes(string prefix)
{
var replacedembly = replacedembly.GetExecutingreplacedembly();
var types = replacedembly.GetTypes();
return types.Where(i => i.FullName.StartsWith(prefix)).ToDictionary(i => i.FullName.Substring(i.FullName.LastIndexOf('.') + 1), i => i);
}
19
View Source File : CodeResolvingUtils.cs
License : GNU General Public License v3.0
Project Creator : Acumatica
License : GNU General Public License v3.0
Project Creator : Acumatica
public static bool IsPXSelectReadOnlyCommand(this ITypeSymbol bqlTypeSymbol)
{
bqlTypeSymbol.ThrowOnNull(nameof(bqlTypeSymbol));
if (!bqlTypeSymbol.IsBqlCommand())
return false;
foreach (ITypeSymbol type in bqlTypeSymbol.GetBaseTypesAndThis())
{
int indexOfGenericArgsSeparator = type.Name.LastIndexOf('`');
string typeName = indexOfGenericArgsSeparator > 0
? type.Name.Substring(0, indexOfGenericArgsSeparator)
: type.Name;
if (TypeNames.ReadOnlySelects.Contains(typeName))
return true;
}
return false;
}
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 GetTagsFromBQLCommand(ITextSnapshot newSnapshot, string bqlCommand, int offset)
{
int lastAngleBraces = bqlCommand.LastIndexOf('>');
bqlCommand = bqlCommand.Substring(0, lastAngleBraces + 1);
int lastAngleBraceIndex = bqlCommand.LastIndexOf('>');
if (lastAngleBraceIndex >= 0)
bqlCommand = bqlCommand.Substring(0, lastAngleBraceIndex + 1);
int firstAngleBraceIndex = bqlCommand.IndexOf('<');
if (firstAngleBraceIndex < 0)
return;
string selectOp = bqlCommand.Substring(0, firstAngleBraceIndex);
GetSelectCommandTag(newSnapshot, bqlCommand, offset);
GetBQLOperandTags(newSnapshot, bqlCommand, offset);
GetDacWithFieldTags(newSnapshot, bqlCommand, offset);
GetSingleDacAndConstantTags(newSnapshot, bqlCommand, offset);
GetBqlParameterTags(newSnapshot, bqlCommand, offset);
}
19
View Source File : LogFileSettings.cs
License : MIT License
Project Creator : adams85
License : MIT License
Project Creator : adams85
protected internal static IEnumerable<string> GetPrefixes(string categoryName, bool returnDefault = true)
{
while (!string.IsNullOrEmpty(categoryName))
{
yield return categoryName;
var index = categoryName.LastIndexOf('.');
if (index == -1)
{
if (returnDefault)
yield return DefaultCategoryName;
break;
}
categoryName = categoryName.Substring(0, index);
}
}
19
View Source File : StringFunctions.cs
License : MIT License
Project Creator : adamped
License : MIT License
Project Creator : adamped
public static string StrRChr(string stringToSearch, char charToFind)
{
int index = stringToSearch.LastIndexOf(charToFind);
if (index > -1)
return stringToSearch.Substring(index);
else
return null;
}
19
View Source File : POComment.cs
License : MIT License
Project Creator : adams85
License : MIT License
Project Creator : adams85
public static bool TryParse(string value, out POSourceReference result)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var index = value.LastIndexOf(':');
if (index >= 0 && int.TryParse(value.Substring(index + 1), NumberStyles.Integer, CultureInfo.InvariantCulture, out int line))
value = value.Remove(index);
else
line = default(int);
var length = value.Length;
if (length > 0 && value[0] == '"')
if (length > 1 && value[length - 1] == '"')
value = value.Substring(1, length - 2);
else
{
result = default(POSourceReference);
return false;
}
result = new POSourceReference(value, line);
return true;
}
19
View Source File : Utilities.cs
License : MIT License
Project Creator : ADeltaX
License : MIT License
Project Creator : ADeltaX
public static string GetFileFromPath(string path)
{
string trimmed = path.Trim('\\');
int index = trimmed.LastIndexOf('\\');
if (index < 0)
{
return trimmed; // No directory, just a file name
}
return trimmed.Substring(index + 1);
}
19
View Source File : Utilities.cs
License : MIT License
Project Creator : ADeltaX
License : MIT License
Project Creator : ADeltaX
public static string GetDirectoryFromPath(string path)
{
string trimmed = path.TrimEnd('\\');
int index = trimmed.LastIndexOf('\\');
if (index < 0)
{
return string.Empty; // No directory, just a file name
}
return trimmed.Substring(0, index);
}
19
View Source File : SharePointDataAdapter.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public ISharePointCollection GetFoldersAndFiles(EnreplacedyReference regarding, string sortExpression = DefaultSortExpression, int page = 1, int pageSize = DefaultPageSize, string pagingInfo = null, string folderPath = null)
{
var context = _dependencies.GetServiceContextForWrite();
var website = _dependencies.GetWebsite();
var enreplacedyPermissionProvider = new CrmEnreplacedyPermissionProvider();
var result = new SharePointResult(regarding, enreplacedyPermissionProvider, context);
// replacedert permission to create the sharepointdoreplacedentlocation enreplacedy
if (!result.PermissionsExist || !result.CanCreate || !result.CanAppend || !result.CanAppendTo)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Permission Denied. You do not have the appropriate Enreplacedy Permissions to Create or Append doreplacedent locations or AppendTo the regarding enreplacedy.");
return SharePointCollection.Empty(true);
}
var enreplacedyMetadata = context.GetEnreplacedyMetadata(regarding.LogicalName);
var enreplacedy = context.CreateQuery(regarding.LogicalName).First(e => e.GetAttributeValue<Guid>(enreplacedyMetadata.PrimaryIdAttribute) == regarding.Id);
var spConnection = new SharePointConnection(SharePointConnectionStringName);
var spSite = context.GetSharePointSiteFromUrl(spConnection.Url);
var location = GetDoreplacedentLocation(context, enreplacedy, enreplacedyMetadata, spSite);
if (!enreplacedyPermissionProvider.Tryreplacedert(context, CrmEnreplacedyPermissionRight.Read, location))
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Permission Denied. You do not have the appropriate Enreplacedy Permissions to Read doreplacedent locations.");
return SharePointCollection.Empty(true);
}
ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Read SharePoint Doreplacedent Location Permission Granted.");
var factory = new ClientFactory();
using (var client = factory.CreateClientContext(spConnection))
{
// retrieve the SharePoint list and folder names for the doreplacedent location
string listUrl, folderUrl;
context.GetDoreplacedentLocationListAndFolder(location, out listUrl, out folderUrl);
var sharePointFolder = client.AddOrGetExistingFolder(listUrl, folderUrl + folderPath);
var list = client.GetListByUrl(listUrl);
if (!sharePointFolder.IsPropertyAvailable("ServerRelativeUrl"))
{
client.Load(sharePointFolder, folder => folder.ServerRelativeUrl);
}
if (!sharePointFolder.IsPropertyAvailable("ItemCount"))
{
client.Load(sharePointFolder, folder => folder.ItemCount);
}
var camlQuery = new CamlQuery
{
FolderServerRelativeUrl = sharePointFolder.ServerRelativeUrl,
ViewXml = @"
<View>
<Query>
<OrderBy>
<FieldRef {0}></FieldRef>
</OrderBy>
<Where></Where>
</Query>
<RowLimit>{1}</RowLimit>
</View>".FormatWith(
ConvertSortExpressionToCaml(sortExpression),
pageSize)
};
if (page > 1)
{
camlQuery.LisreplacedemCollectionPosition = new LisreplacedemCollectionPosition { PagingInfo = pagingInfo };
}
var folderItems = list.Gereplacedems(camlQuery);
client.Load(folderItems,
items => items.LisreplacedemCollectionPosition,
items => items.Include(
item => item.ContentType,
item => item["ID"],
item => item["FileLeafRef"],
item => item["Created"],
item => item["Modified"],
item => item["FileSizeDisplay"]));
client.ExecuteQuery();
var sharePoinreplacedems = new List<SharePoinreplacedem>();
if (!string.IsNullOrEmpty(folderPath) && folderPath.Contains("/"))
{
var relativePaths = folderPath.Split('/');
var parentFolderName = relativePaths.Length > 2 ? relativePaths.Skip(relativePaths.Length - 2).First() : "/";
sharePoinreplacedems.Add(new SharePoinreplacedem()
{
Name = @"""{0}""".FormatWith(parentFolderName),
IsFolder = true,
FolderPath = folderPath.Substring(0, folderPath.LastIndexOf('/')),
IsParent = true
});
}
if (folderItems.Count < 1)
{
return new SharePointCollection(sharePoinreplacedems, null, sharePoinreplacedems.Count());
}
foreach (var item in folderItems)
{
var id = item["ID"] as int?;
var name = item["FileLeafRef"] as string;
var created = item["Created"] as DateTime?;
var modified = item["Modified"] as DateTime?;
long longFileSize;
var fileSize = long.TryParse(item["FileSizeDisplay"] as string, out longFileSize) ? longFileSize : null as long?;
if (string.Equals(item.ContentType.Name, "Folder", StringComparison.InvariantCultureIgnoreCase))
{
sharePoinreplacedems.Add(new SharePoinreplacedem
{
Id = id,
Name = name,
IsFolder = true,
CreatedOn = created,
ModifiedOn = modified,
FolderPath = "{0}/{1}".FormatWith(folderPath, name)
});
}
else
{
sharePoinreplacedems.Add(new SharePoinreplacedem
{
Id = id,
Name = name,
CreatedOn = created,
ModifiedOn = modified,
FileSize = fileSize,
Url = GetAbsolutePath(website, location, name, folderPath)
});
}
}
var pageInfo = folderItems.LisreplacedemCollectionPosition != null
? folderItems.LisreplacedemCollectionPosition.PagingInfo
: null;
return new SharePointCollection(sharePoinreplacedems, pageInfo, sharePointFolder.ItemCount);
}
}
19
View Source File : ContentMapUrlMapping.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static bool ParseParentPath(string path, out string parentPath, out string lastPathComponent)
{
parentPath = null;
lastPathComponent = null;
if (path == "/") return false;
var lastIndex = path.LastIndexOf('/');
if (lastIndex >= 0)
{
var newPath = path.Remove(lastIndex + 1);
if (newPath == string.Empty)
{
parentPath = "/";
lastPathComponent = path.Remove(0, 1);
return true;
}
parentPath = newPath;
lastPathComponent = path.Remove(0, newPath.Length);
return true;
}
return false;
}
19
View Source File : UrlHistoryRedirectProvider.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static IMatch FindPage(OrganizationServiceContext context, Enreplacedy website, string path)
{
var mappedPageResult = UrlMapping.LookupPageByUrlPath(context, website, path);
if (mappedPageResult.Node != null)
{
return new NonHistoryMatch(mappedPageResult.Node);
}
var historyMatchPage = FindHistoryMatchPage(context, website, path);
if (historyMatchPage != null)
{
return new HistoryMatch(historyMatchPage);
}
// find the last slash in the path
var lastSlash = path.LastIndexOf('/');
if (lastSlash != -1)
{
// we found a slash
var pathBeforeSlash = path.Substring(0, lastSlash);
var pathAfterSlash = path.Substring(lastSlash + 1);
var parentMatch = (string.IsNullOrWhiteSpace(pathBeforeSlash) || _homePaths.Contains(pathBeforeSlash))
// do a final traversal against the home page
? GetHomePage(context, website)
// see if we can find a path for the parent url
: FindPage(context, website, pathBeforeSlash);
if (parentMatch.Success)
{
var foundParentPageID = parentMatch.WebPage.ToEnreplacedyReference();
var fetch = new Fetch
{
Enreplacedy = new FetchEnreplacedy("adx_webpage")
{
Filters = new List<Filter>
{
new Filter
{
Conditions = new[]
{
new Condition("statecode", ConditionOperator.Equal, 0),
new Condition("adx_parentpageid", ConditionOperator.Equal, foundParentPageID.Id),
new Condition("adx_partialurl", ConditionOperator.Equal, pathAfterSlash)
}
}
}
}
};
// we found a parent path, now rebuild the path of the child
var child = context.RetrieveSingle(fetch);
if (child != null)
{
return new SuccessfulMatch(child, parentMatch.UsedHistory);
}
var parentPath = context.GetApplicationPath(parentMatch.WebPage);
if (parentPath == null)
{
return new FailedMatch();
}
if (parentPath.AppRelativePath.TrimEnd('/') == path)
{
// prevent stack overflow
return new FailedMatch();
}
var newPath = parentPath.AppRelativePath + (parentPath.AppRelativePath.EndsWith("/") ? string.Empty : "/") + pathAfterSlash;
if (newPath == path)
{
return new FailedMatch();
}
var childMatch = FindPage(context, website, newPath);
if (childMatch.Success)
{
return new HistoryMatch(childMatch.WebPage);
}
}
}
return new FailedMatch();
}
19
View Source File : UrlMapping.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static bool ParseParentPath(string path, out string parentPath, out string lastPathComponent)
{
parentPath = null;
lastPathComponent = null;
if (path == "/") return false;
var lastIndex = path.LastIndexOf('/');
if (lastIndex >= 0)
{
var newPath = path.Remove(lastIndex);
if (newPath == string.Empty)
{
parentPath = "/";
lastPathComponent = path.Remove(0, 1);
return true;
}
parentPath = newPath;
lastPathComponent = path.Remove(0, newPath.Length + 1);
return true;
}
return false;
}
19
View Source File : EmbeddedResourceAssemblyAttribute.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private string ConvertResourceNameToVirtualPath(string resourceName)
{
// generic algorithm for turning a resource name into a virtual path
// replace every dot with a slash except for the last dot
// chop off the leading default namespace
var index1 = resourceName.LastIndexOf('.');
var index2 = index1 + 1;
var head = Regex.Replace(resourceName.Substring(0, index1), "^" + Namespace, string.Empty, RegexOptions.IgnoreCase).Replace('.', '/');
var tail = resourceName.Substring(index2, resourceName.Length - index2);
return "~/{0}.{1}".FormatWith(head, tail);
}
19
View Source File : TypeResolverImpl.cs
License : MIT License
Project Creator : adrianoc
License : MIT License
Project Creator : adrianoc
private string OpenGenericTypeName(ITypeSymbol type)
{
var genericTypeWithTypeParameters = type.ToString();
var genOpenBraceIndex = genericTypeWithTypeParameters.IndexOf('<');
var genCloseBraceIndex = genericTypeWithTypeParameters.LastIndexOf('>');
var nts = (INamedTypeSymbol) type;
var commas = new string(',', nts.TypeParameters.Length - 1);
return genericTypeWithTypeParameters.Remove(genOpenBraceIndex + 1, genCloseBraceIndex - genOpenBraceIndex - 1).Insert(genOpenBraceIndex + 1, commas);
}
19
View Source File : SyntaxWalkerBase.cs
License : MIT License
Project Creator : adrianoc
License : MIT License
Project Creator : adrianoc
private IEnumerable<string> ProcessDllImportAttribute(AttributeSyntax attribute, string methodVar)
{
var moduleName = attribute.ArgumentList?.Arguments.First().ToFullString();
var existingModuleVar = Context.DefinitionVariables.GetVariable(moduleName, MemberKind.ModuleReference);
var moduleVar = existingModuleVar.IsValid
? existingModuleVar.VariableName
: Context.Naming.SyntheticVariable("dllImportModule", ElementKind.LocalVariable);
var exps = new List<string>
{
$"{methodVar}.PInvokeInfo = new PInvokeInfo({ PInvokeAttributesFrom(attribute) }, { EntryPoint() }, {moduleVar});",
$"{methodVar}.Body = null;",
$"{methodVar}.ImplAttributes = {MethodImplAttributes()};",
};
if (!existingModuleVar.IsValid)
{
exps.InsertRange(0, new []
{
$"var {moduleVar} = new ModuleReference({moduleName});",
$"replacedembly.MainModule.ModuleReferences.Add({moduleVar});",
});
}
Context.DefinitionVariables.RegisterNonMethod("", moduleName, MemberKind.ModuleReference, moduleVar);
return exps;
string EntryPoint() => attribute?.ArgumentList?.Arguments.FirstOrDefault(arg => arg.NameEquals?.Name.Identifier.Text == "EntryPoint")?.Expression.ToString() ?? "\"\"";
string MethodImplAttributes()
{
var preserveSig = Boolean.Parse(AttributePropertyOrDefaultValue(attribute, "PreserveSig", "true"));
return preserveSig
? "MethodImplAttributes.PreserveSig | MethodImplAttributes.Managed"
: "MethodImplAttributes.Managed";
}
string CallingConventionFrom(AttributeSyntax attr)
{
var callingConventionStr = attr.ArgumentList?.Arguments.FirstOrDefault(arg => arg.NameEquals?.Name.Identifier.Text == "CallingConvention")?.Expression.ToFullString()
?? "Winapi";
// ensures we use the enum member simple name; Parse() fails if we preplaced a qualified enum member
var index = callingConventionStr.LastIndexOf('.');
callingConventionStr = callingConventionStr.Substring(index + 1);
return CallingConventionToCecil(Enum.Parse<CallingConvention>(callingConventionStr));
}
string CharSetFrom(AttributeSyntax attr)
{
var enumMemberName = AttributePropertyOrDefaultValue(attr, "CharSet", "None");
// Only use the actual enum member name Parse() fails if we preplaced a qualified enum member
var index = enumMemberName.LastIndexOf('.');
enumMemberName = enumMemberName.Substring(index + 1);
var charSet = Enum.Parse<CharSet>(enumMemberName);
return charSet == CharSet.None ? string.Empty : $"PInvokeAttributes.CharSet{charSet}";
}
string SetLastErrorFrom(AttributeSyntax attr)
{
var setLastError = bool.Parse(AttributePropertyOrDefaultValue(attr, "SetLastError", "false"));
return setLastError ? "PInvokeAttributes.SupportsLastError" : string.Empty;
}
string ExactSpellingFrom(AttributeSyntax attr)
{
var exactSpelling = bool.Parse(AttributePropertyOrDefaultValue(attr, "ExactSpelling", "false"));
return exactSpelling ? "PInvokeAttributes.NoMangle" : string.Empty;
}
string BestFitMappingFrom(AttributeSyntax attr)
{
var bestFitMapping = bool.Parse(AttributePropertyOrDefaultValue(attr, "BestFitMapping", "true"));
return bestFitMapping ? "PInvokeAttributes.BestFitEnabled" : "PInvokeAttributes.BestFitDisabled";
}
string ThrowOnUnmappableCharFrom(AttributeSyntax attr)
{
var bestFitMapping = bool.Parse(AttributePropertyOrDefaultValue(attr, "ThrowOnUnmappableChar", "false"));
return bestFitMapping ? "PInvokeAttributes.ThrowOnUnmappableCharEnabled" : "PInvokeAttributes.ThrowOnUnmappableCharDisabled";
}
// For more information and default values see
// https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.dllimportattribute
string PInvokeAttributesFrom(AttributeSyntax attr)
{
return CallingConventionFrom(attr)
.AppendModifier(CharSetFrom(attr))
.AppendModifier(SetLastErrorFrom(attr))
.AppendModifier(ExactSpellingFrom(attr))
.AppendModifier(BestFitMappingFrom(attr))
.AppendModifier(ThrowOnUnmappableCharFrom(attr));
}
string AttributePropertyOrDefaultValue(AttributeSyntax attr, string propertyName, string defaultValue)
{
return attr.ArgumentList?.Arguments.FirstOrDefault(arg => arg.NameEquals?.Name.Identifier.Text == propertyName)?.Expression.ToFullString() ?? defaultValue;
}
}
19
View Source File : RedisLiteHelper.cs
License : MIT License
Project Creator : AElfProject
License : MIT License
Project Creator : AElfProject
public static string [] SplitOnLast (this string strVal, char needle)
{
if (strVal == null) return EmptyStringArray;
var pos = strVal.LastIndexOf (needle);
return pos == -1
? new [] { strVal }
: new [] { strVal.Substring (0, pos), strVal.Substring (pos + 1) };
}
19
View Source File : Weapon.cs
License : GNU General Public License v3.0
Project Creator : aenemenate
License : GNU General Public License v3.0
Project Creator : aenemenate
public override string DetermineDescription()
{
string description = "";
string particle = "A";
switch (weaponName[0]) {
case ('a'): case ('e'):
case ('i'): case ('o'):
case ('u'):
case ('A'): case ('E'):
case ('I'): case ('O'):
case ('U'):
particle = "An";
break;
}
if (enchantments == null || enchantments.Count == 0)
return $"{particle} {weaponName}.";
else
{
description = $"An enchanted {weaponName} which ";
foreach (WeaponEnchantment enchant in enchantments)
if (enchant.AppliedEffect != null)
description += $"has a {enchant.AppliedEffect.Chance}% chance to inflict {enchant.AppliedEffect.Name}, ";
foreach (WeaponEnchantment enchant in enchantments)
if (enchant.VictimDamage != 0)
description += $"deals {enchant.VictimDamage} {enchant.DamageType.ToString().ToLower()} dmg, ";
description = description.Substring(0, description.LastIndexOf(',')) + '.';
if (description.Count(c => c == ',') > 0)
{
int commaIndex = description.LastIndexOf(',');
description = description.Substring(0, commaIndex) + " and " + description.Substring(commaIndex + 2, description.Length - (commaIndex + 2));
}
return description;
}
}
19
View Source File : Effect.cs
License : GNU General Public License v3.0
Project Creator : aenemenate
License : GNU General Public License v3.0
Project Creator : aenemenate
public void Apply(Creature victim)
{
string victimText = $"{victim.Name}";
string userText = $"{user.Name}";
if (victimHPDamageType != DamageType.None)
{
int damageTaken = victim.Defend(victimHPDamageType, victimResourceDamage[0], victim.Position);
victimText += $" recieved {damageTaken} {victimHPDamageType.ToString()} damage,";
}
if (victimResourceDamage[1] > 0)
{
victim.ChangeResource(Resource.MP, - victimResourceDamage[1]);
victimText += $" lost {victimResourceDamage[1]} magicka,";
}
if (victimResourceDamage[2] > 0)
{
victim.ChangeResource(Resource.SP, -victimResourceDamage[2]);
victimText += $" lost {victimResourceDamage[2]} stamina,";
}
if (victimResourceHealing[0] > 0)
{
victim.ChangeResource(Resource.HP, victimResourceHealing[0]);
victimText += $" had {victimResourceHealing[0]} health restored,";
}
if (victimResourceHealing[1] > 0)
{
victim.ChangeResource(Resource.MP, victimResourceHealing[1]);
victimText += $" had {victimResourceHealing[1]} magicka restored,";
}
if (victimResourceHealing[2] > 0)
{
victim.ChangeResource(Resource.SP, victimResourceHealing[2]);
victimText += $" had {victimResourceHealing[2]} stamina restored,";
}
if (userResourceHealing[0] > 0)
{
user.ChangeResource(Resource.SP, userResourceHealing[0]);
userText += $" recieved {userResourceHealing[0]} health,";
}
if (userResourceHealing[1] > 0)
{
user.ChangeResource(Resource.SP, userResourceHealing[1]);
userText += $" recieved {userResourceHealing[1]} magicka,";
}
if (userResourceHealing[2] > 0)
{
user.ChangeResource(Resource.SP, userResourceHealing[2]);
userText += $" recieved {userResourceHealing[2]} stamina,";
}
if (!victimText.Equals($"{victim.Name}"))
{
victimText = victimText.Substring(0, victimText.LastIndexOf(','));
if (victimText.Contains(","))
{
int commaIndex = victimText.LastIndexOf(',');
victimText = victimText.Substring(0, commaIndex) + " and " + victimText.Substring(commaIndex + 2, victimText.Length - (commaIndex + 2));
}
victimText += $" from {name}.";
Program.MsgConsole.WriteLine(victimText);
}
if (!userText.Equals($"{user.Name}"))
{
userText = userText.Substring(0, userText.LastIndexOf(','));
if (userText.Contains(","))
{
int commaIndex = userText.LastIndexOf(',');
userText = userText.Substring(0, commaIndex) + " and " + userText.Substring(commaIndex + 2, userText.Length - (commaIndex + 2));
}
userText += $" from {name}.";
Program.MsgConsole.WriteLine(userText);
}
turns--;
if (turns == 0)
victim.Effects.Remove(this);
}
19
View Source File : Window.cs
License : GNU General Public License v3.0
Project Creator : aenemenate
License : GNU General Public License v3.0
Project Creator : aenemenate
public void PrintMessage(int y, string str, int length, Color foreColor)
{
str = str + ' ';
int endIndex = str.LastIndexOf(' ');
string nextLine = str.Substring(0, endIndex + 1);
while (true)
{
if (nextLine.Length > length + 1)
{
if (nextLine.Contains(" "))
endIndex = nextLine.Substring(0, endIndex).LastIndexOf(' ');
nextLine = str.Substring(0, endIndex + 1);
}
else
{
Program.MsgConsole.Console.Print(InventoryPanel.Width, y, nextLine, new Color(foreColor, 0.97F), new Color(Color.DarkSlateGray, 0.7F));
y++;
str = str.Substring(endIndex + 1, str.Length - nextLine.Length);
endIndex = str.LastIndexOf(' ');
nextLine = str.Substring(0, endIndex + 1);
if (str == "")
return;
}
}
}
19
View Source File : Window.cs
License : GNU General Public License v3.0
Project Creator : aenemenate
License : GNU General Public License v3.0
Project Creator : aenemenate
static public Tuple<string, string> SplitNameIfGreaterThanLength(string str, string pt2, int length)
{
int endIndex;
if (str.Length > length)
{
if (str.Contains(" "))
{
endIndex = str.LastIndexOf(' ');
while (str.Substring(0, endIndex).Length > length)
endIndex = str.Substring(0, endIndex).LastIndexOf(' ');
}
else
endIndex = length - 1;
}
else
endIndex = str.Length - 1;
if (endIndex != str.Length - 1 && str[endIndex] == ' ')
pt2 += str.Substring(endIndex + 1, (str.Length - endIndex) - 1);
else if (endIndex != str.Length - 1 && str[endIndex] != ' ')
pt2 += str.Substring(endIndex, (str.Length - endIndex) - 1);
str = str.Substring(0, endIndex + 1);
if (pt2.Length > length)
pt2 = pt2.Substring(0, length - 3) + "...";
return Tuple.Create(str, pt2);
}
19
View Source File : Window.cs
License : GNU General Public License v3.0
Project Creator : aenemenate
License : GNU General Public License v3.0
Project Creator : aenemenate
public int Print( Console console, int x, int y, string str, int length, Color foreColor )
{
str = str + ' ';
int lines = 1;
int endIndex = str.LastIndexOf( ' ' );
string nextLine = str.Substring( 0, endIndex + 1 );
while (true)
{
if (nextLine.Length > length + 1)
{
if (nextLine.Contains( " " ))
endIndex = nextLine.Substring( 0, endIndex ).LastIndexOf( ' ' );
nextLine = str.Substring( 0, endIndex + 1 );
} else
{
if (y >= Program.Window.Height)
return lines;
console.Print( x, y, nextLine, foreColor );
y++;
lines++;
str = str.Substring( endIndex + 1, str.Length - nextLine.Length );
endIndex = str.LastIndexOf( ' ' );
nextLine = str.Substring( 0, endIndex + 1 );
if (str == "")
return lines;
}
}
}
See More Examples