Here are the examples of the csharp api string.Remove(int, int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1670 Examples
19
View Source File : Entry.cs
License : MIT License
Project Creator : 0ffffffffh
License : MIT License
Project Creator : 0ffffffffh
public void FixForMultipleLineFeeds()
{
int index=0;
while (index != -1)
{
index = Content.IndexOf("\r\n", index);
if (index != -1)
{
Content = Content.Remove(index, 2);
while (index + 2 < Content.Length)
{
if (Content.Substring(index, 2) == "\r\n")
{
Content = Content.Remove(index, 2).Insert(index, "<br/>");
index += 5;
}
else
{
Content = Content.Insert(index, "\r\n");
index += 2;
break;
}
}
if (index + 2 > Content.Length)
break;
}
}
}
19
View Source File : CelesteNetChatComponent.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public void OnTextInput(char c) {
if (!Active)
return;
if (c == (char) 13) {
// Enter - send.
// Handled in Update.
} else if (c == (char) 8 && _CursorIndex > 0) {
// Backspace - trim.
if (Typing.Length > 0) {
int trim = 1;
// extra CursorIndex check since at index=1 using trim=1 is fine
if (_ControlHeld && _CursorIndex > 1) {
// adjust Ctrl+Backspace for having a space right before cursor
int _adjustedCursor = CursorIndex;
if (Typing[_CursorIndex - 1] == ' ')
_adjustedCursor--;
int prevWord = Typing.LastIndexOf(" ", _adjustedCursor - 1);
// if control is held and a space is found, trim from cursor back to space
if (prevWord >= 0)
trim = _adjustedCursor - prevWord;
// otherwise trim whole input back from cursor as it is one word
else
trim = _adjustedCursor;
}
// remove <trim> amount of characters before cursor
Typing = Typing.Remove(_CursorIndex - trim, trim);
_CursorIndex -= trim;
}
_RepeatIndex = 0;
_Time = 0;
} else if (c == (char) 127 && CursorIndex < Typing.Length) {
// Delete - remove character after cursor.
if (_ControlHeld && Typing[_CursorIndex] != ' ') {
int nextWord = Typing.IndexOf(" ", _CursorIndex);
// if control is held and a space is found, remove from cursor to space
if (nextWord >= 0) {
// include the found space in removal
nextWord++;
Typing = Typing.Remove(_CursorIndex, nextWord - _CursorIndex);
} else {
// otherwise remove everything after cursor
Typing = Typing.Substring(0, _CursorIndex);
}
} else {
// just remove single char
Typing = Typing.Remove(_CursorIndex, 1);
}
_RepeatIndex = 0;
_Time = 0;
} else if (!char.IsControl(c)) {
if (CursorIndex == Typing.Length) {
// Any other character - append.
Typing += c;
} else {
// insert into string if cursor is not at the end
Typing = Typing.Insert(_CursorIndex, c.ToString());
}
_CursorIndex++;
_RepeatIndex = 0;
_Time = 0;
}
}
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 : Program.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 0xthirteen
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 0xthirteen
static void CleanSingle(string command)
{
string keypath = "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\RunMRU";
string keyvalue = string.Empty;
string regcmd = string.Empty;
if (command.EndsWith("\\1"))
{
regcmd = command;
}
else
{
regcmd = string.Format("{0}\\1", command);
}
try
{
RegistryKey regkey;
regkey = Registry.CurrentUser.OpenSubKey(keypath, true);
if (regkey.ValueCount > 0)
{
foreach (string subKey in regkey.GetValueNames())
{
if(regkey.GetValue(subKey).ToString() == regcmd)
{
keyvalue = subKey;
regkey.DeleteValue(subKey);
Console.WriteLine(regcmd);
Console.WriteLine("[+] Cleaned {0} from HKCU:{1}", command, keypath);
}
}
if(keyvalue != string.Empty)
{
string mruchars = regkey.GetValue("MRUList").ToString();
int index = mruchars.IndexOf(keyvalue);
mruchars = mruchars.Remove(index, 1);
regkey.SetValue("MRUList", mruchars);
}
}
regkey.Close();
}
catch (ArgumentException)
{
Console.WriteLine("[-] Error: Selected Registry value does not exist");
}
}
19
View Source File : SqlExtensions.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
public static string Splice(this string sql, params bool[] conditions)
{
var startIndex = 0;
foreach (var condition in conditions)
{
var start = sql.IndexOf('{', startIndex);
if (start < 0)
return sql;
var end = sql.IndexOf('}', start);
if (end < 0)
return sql;
startIndex = end;
var elseIndex = sql.IndexOf(':', start, end - start);
if (elseIndex < 0)
{
if (condition)
{
sql = sql.Remove(start, 1).Remove(end - 1, 1);
startIndex -= 2;
}
else
{
var count = end - start + 1;
sql = sql.Remove(start, count);
startIndex -= count;
}
}
else
{
if (condition)
{
var count = end - elseIndex + 1;
sql = sql.Remove(start, 1).Remove(elseIndex - 1, count);
startIndex -= count;
}
else
{
var count = elseIndex - start + 1;
sql = sql.Remove(start, count).Remove(end - count, 1);
startIndex -= count;
}
}
}
return sql;
}
19
View Source File : CommandNode.cs
License : Apache License 2.0
Project Creator : 1448376744
License : Apache License 2.0
Project Creator : 1448376744
private string ResolveWhereNode<T>(WhereNode node, T parameter) where T :clreplaced
{
var buffer = new StringBuilder();
foreach (var item in node.Nodes)
{
if (parameter!=default && item is IfNode)
{
var text = ResolveIfNode(item as IfNode, parameter);
buffer.Append($"{text} ");
}
else if (item is TextNode)
{
var text = ResolveTextNode(item as TextNode);
buffer.Append($"{text} ");
}
}
var sql = buffer.ToString().Trim(' ');
if (sql.StartsWith("and", StringComparison.OrdinalIgnoreCase))
{
sql = sql.Remove(0, 3);
}
else if (sql.StartsWith("or", StringComparison.OrdinalIgnoreCase))
{
sql = sql.Remove(0, 2);
}
return sql.Length > 0 ? "WHERE " + sql : string.Empty;
}
19
View Source File : DbQuery.cs
License : Apache License 2.0
Project Creator : 1448376744
License : Apache License 2.0
Project Creator : 1448376744
private string ResovleCount()
{
var table = GetTableMetaInfo().TableName;
var column = "COUNT(1)";
var where = ResolveWhere();
var group = ResolveGroup();
if (group.Length > 0)
{
column = group.Remove(0, 10);
}
else if (_countExpression != null)
{
column = new SelectExpressionResovle(_countExpression).Resovle();
}
var sql = $"SELECT {column} FROM {table}{where}{group}";
if (group.Length > 0)
{
sql = $"SELECT COUNT(1) FROM ({sql}) as t";
return sql;
}
return sql;
}
19
View Source File : Program.cs
License : GNU Affero General Public License v3.0
Project Creator : 3CORESec
License : GNU Affero General Public License v3.0
Project Creator : 3CORESec
public static Dictionary<string, dynamic> DeserializeYamlFile(string ruleFilePath, Options o)
{
var contents = File.ReadAllText(ruleFilePath);
if (!contents.Contains("tags"))
{
Console.WriteLine($"Ignoring rule {ruleFilePath} (no tags)");
return null;
}
if (o.Warning)
contents = contents.Replace(Environment.NewLine + Environment.NewLine,
Environment.NewLine)
.Remove(0, contents.IndexOf("tags", StringComparison.Ordinal));
if (contents.Contains("---"))
contents = contents.Remove(contents.IndexOf("---", StringComparison.Ordinal));
var deserializer = new YamlDotNet.Serialization.Deserializer();
var dict = deserializer.Deserialize<Dictionary<string, dynamic>>(contents);
return dict;
}
19
View Source File : GCodeParser.cs
License : MIT License
Project Creator : 3RD-Dimension
License : MIT License
Project Creator : 3RD-Dimension
static string CleanupLine(string line, int lineNumber)
{
int commentIndex = line.IndexOf(';');
if (commentIndex > -1)
line = line.Remove(commentIndex);
int start = -1;
while ((start = line.IndexOf('(')) != -1)
{
int end = line.IndexOf(')');
if (end < start)
throw new ParseException("mismatched parentheses", lineNumber);
line = line.Remove(start, end - start);
}
return line;
}
19
View Source File : WorkOffsetsWindow.xaml.cs
License : MIT License
Project Creator : 3RD-Dimension
License : MIT License
Project Creator : 3RD-Dimension
public void parseG5xOffsets(string recievedG5x)
{
// Need someway to ignore this until the machine is idle and not operating
if (recievedG5x.StartsWith("[G54:") || recievedG5x.StartsWith("[G55:") || recievedG5x.StartsWith("[G56:") || recievedG5x.StartsWith("[G57:") || recievedG5x.StartsWith("[G58:") || recievedG5x.StartsWith("[G59:"))
{
// Splitting each recieved axis and value
string label;
string[] axes;
recievedG5x = recievedG5x.Remove(0, 1); // remove the leading [
recievedG5x = recievedG5x.Remove(recievedG5x.Length - 1, 1); // remove the trailing "] <vbLf>"
label = recievedG5x.Substring(0, 3);
recievedG5x = recievedG5x.Remove(0, 4); // finally remove the label:
axes = recievedG5x.Split(',');
switch (label)
{
case "G54":
{
G54X.Text = axes[0].ToString();
G54Y.Text = axes[1].ToString();
G54Z.Text = axes[2].ToString();
break;
}
case "G55":
{
G55X.Text = axes[0].ToString();
G55Y.Text = axes[1].ToString();
G55Z.Text = axes[2].ToString();
break;
}
case "G56":
{
G56X.Text = axes[0].ToString();
G56Y.Text = axes[1].ToString();
G56Z.Text = axes[2].ToString();
break;
}
case "G57":
{
G57X.Text = axes[0].ToString();
G57Y.Text = axes[1].ToString();
G57Z.Text = axes[2].ToString();
break;
}
case "G58":
{
G58X.Text = axes[0].ToString();
G58Y.Text = axes[1].ToString();
G58Z.Text = axes[2].ToString();
break;
}
case "G59":
{
G59X.Text = axes[0].ToString();
G59Y.Text = axes[1].ToString();
G59Z.Text = axes[2].ToString();
break;
}
}
}
else
{
return;
}
}
19
View Source File : GrblSettingsWindow.xaml.cs
License : MIT License
Project Creator : 3RD-Dimension
License : MIT License
Project Creator : 3RD-Dimension
public void LineReceived(string line)
{
// Recieve GRBL Controller Version number and display - $i
// Recieved in format [VER: ... and [OPT:
if (!line.StartsWith("$") && !line.StartsWith("[VER:") && !line.StartsWith("[OPT:"))
return;
if (line.StartsWith("$"))
{
try
{
Match m = settingParser.Match(line);
int number = int.Parse(m.Groups[1].Value);
double value = double.Parse(m.Groups[2].Value, Util.Constants.DecimalParseFormat);
// Value = Setting Value, Number = Setting Code
if (!CurrentSettings.ContainsKey(number))
{
RowDefinition rowDef = new RowDefinition();
rowDef.Height = new GridLength(25);
gridMain.RowDefinitions.Add(rowDef);
TextBox valBox = new TextBox // Value of Setting Textbox
{
Text = value.ToString(Util.Constants.DecimalOutputFormat),
VerticalAlignment = VerticalAlignment.Center
};
// Define Mouseclick for textbox to open GRBLStepsCalcWindow for setting $100, $101, $102
if (number == 100) { valBox.Name = "Set100"; valBox.MouseDoubleClick += openStepsCalc; }
else if (number == 101) { valBox.Name = "Set101"; valBox.MouseDoubleClick += openStepsCalc; }
else if (number == 102) { valBox.Name = "Set102"; valBox.MouseDoubleClick += openStepsCalc; }
Grid.SetRow(valBox, gridMain.RowDefinitions.Count - 1);
Grid.SetColumn(valBox, 1);
gridMain.Children.Add(valBox);
TextBlock num = new TextBlock
{
Text = $"${number}=",
HorizontalAlignment = HorizontalAlignment.Right,
VerticalAlignment = VerticalAlignment.Center
};
Grid.SetRow(num, gridMain.RowDefinitions.Count - 1);
Grid.SetColumn(num, 0);
gridMain.Children.Add(num);
if (Util.GrblCodeTranslator.Settings.ContainsKey(number))
{
Tuple<string, string, string> labels = Util.GrblCodeTranslator.Settings[number];
TextBlock name = new TextBlock
{
Text = labels.Item1,
VerticalAlignment = VerticalAlignment.Center
};
Grid.SetRow(name, gridMain.RowDefinitions.Count - 1);
Grid.SetColumn(name, 0);
gridMain.Children.Add(name);
TextBlock unit = new TextBlock
{
Text = labels.Item2,
VerticalAlignment = VerticalAlignment.Center
};
Grid.SetRow(unit, gridMain.RowDefinitions.Count - 1);
Grid.SetColumn(unit, 2);
gridMain.Children.Add(unit);
valBox.ToolTip = $"{labels.Item1} ({labels.Item2}):\n{labels.Item3}";
}
CurrentSettings.Add(number, value);
SettingsBoxes.Add(number, valBox);
}
else
{
SettingsBoxes[number].Text = value.ToString(Util.Constants.DecimalOutputFormat);
CurrentSettings[number] = value;
}
}
catch { }
}
// If the line starts with [VER: then we know we are getting the version and options
else if (line.StartsWith("[VER:") || line.StartsWith("[OPT:"))
{
// Frist need to remove front [ and rear ]
string VerOptInput; // Input string
string[] VerOptTrimmed;
VerOptInput = line.Remove(0, 1); // Remove [ from the start
VerOptInput = VerOptInput.Remove(VerOptInput.Length - 1);
// Next, split the values in half at the : - we only want VER/OPT and then the values
VerOptTrimmed = VerOptInput.Split(':');
// Now we fill in the boxes depending on which one
switch (VerOptTrimmed[0])
{
case "VER":
controllerInfo += "Version: " + VerOptTrimmed[1];
break;
case "OPT":
// First we have to split commas
string[] optSplit;
optSplit = VerOptTrimmed[1].Split(','); // Splits Options into 3. 0=Options, 1=blockBufferSize, 2=rxBufferSize
var individualChar = optSplit[0].ToCharArray();// Now split optSplit[0] into each option character
controllerInfo += " | Options: " + VerOptTrimmed[1]; // Full Options Non-Decoded String
foreach (char c in individualChar)
{
// Lookup what each code is and display.... buildCodes Dictionary
if (Util.GrblCodeTranslator.BuildCodes.ContainsKey(c.ToString()))
{
// Now lets try and create and append to a string and then bind it to a ToolTip? or some other way
controllerInfo += Environment.NewLine + Util.GrblCodeTranslator.BuildCodes[c.ToString()];
}
}
controllerInfo += Environment.NewLine + "Block Buffer Size: " + optSplit[1];
controllerInfo += Environment.NewLine + "RX Buffer Size: " + optSplit[2];
GRBL_Controller_Info.Text = controllerInfo.ToString();
break;
}
}
}
19
View Source File : MainWindow.xaml.cs
License : MIT License
Project Creator : 3RD-Dimension
License : MIT License
Project Creator : 3RD-Dimension
private void AutoUpdaterOnParseUpdateInfoEvent(ParseUpdateInfoEventArgs args)
{
dynamic json = JsonConvert.DeserializeObject(args.RemoteData);
string VersionGitHub = json.tag_name; // Version Number - Change this to tag_name on deployment
string replacedetDownloadURL = "";
VersionGitHub = (VersionGitHub.Remove(0, 1)); // Remove "v" from beginning
Version v = new Version(VersionGitHub); // Conver to Version
foreach (var replacedets in json.replacedets)
{
replacedetDownloadURL = replacedets.browser_download_url;
}
args.UpdateInfo = new UpdateInfoEventArgs
{
CurrentVersion = v,
ChangelogURL = json.body,
//Mandatory = json.mandatory,
DownloadURL = replacedetDownloadURL
};
}
19
View Source File : RedisCache.cs
License : Apache License 2.0
Project Creator : 91270
License : Apache License 2.0
Project Creator : 91270
public void Remove<V>(string key)
{
RedisServer.Cache.Del(key.Remove(0, 6));
}
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 : Helper.cs
License : Apache License 2.0
Project Creator : aadreja
License : Apache License 2.0
Project Creator : aadreja
internal static string RemoveLastComma(this string pString)
{
if (pString[pString.Length - 1] == ',')
{
pString = pString.Remove(pString.Length - 1, 1);
}
return pString;
}
19
View Source File : MainPage.xaml.cs
License : MIT License
Project Creator : Abdesol
License : MIT License
Project Creator : Abdesol
private async void back_clicked(object sender, EventArgs args)
{
Button btn = (Button)sender;
btn.BackgroundColor = Color.FromHex("#C7C7C7");
await Task.Delay(50);
if (no_char > 0)
{
current_opt = current_opt.Remove(current_opt.Length - 1, 1);
current_opt_below = equal(current_opt);
Main_number_add.Text = current_opt + " ";
second_number_add.Text = current_opt_below + " ";
no_char = current_opt.Length;
try
{
char l = current_opt[no_char - 1];
if (l == '+' || l == '-' || l == '÷' || l == '×')
{
opt = 1;
}
else
{
opt = 0;
}
}
catch { }
}
btn.BackgroundColor = Color.Transparent;
}
19
View Source File : PackageManifestUpdater.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
internal static void EnsureMSBuildForUnity()
{
PackageManifest manifest = null;
string manifestPath = GetPackageManifestFilePath();
if (string.IsNullOrWhiteSpace(manifestPath))
{
return;
}
// Read the package manifest into a list of strings (for easy finding of entries)
// and then deserialize.
List<string> manifestFileLines = new List<string>();
using (FileStream manifestStream = new FileStream(manifestPath, FileMode.Open, FileAccess.Read))
{
using (StreamReader reader = new StreamReader(manifestStream))
{
// Read the manifest file a line at a time.
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
manifestFileLines.Add(line);
}
// Go back to the start of the file.
manifestStream.Seek(0, 0);
// Deserialize the scoped registries portion of the package manifest.
manifest = JsonUtility.FromJson<PackageManifest>(reader.ReadToEnd());
}
}
if (manifest == null)
{
Debug.LogError($"Failed to read the package manifest file ({manifestPath})");
return;
}
// Ensure that pre-existing scoped registries are retained.
List<ScopedRegistry> scopedRegistries = new List<ScopedRegistry>();
if ((manifest.scopedRegistries != null) && (manifest.scopedRegistries.Length > 0))
{
scopedRegistries.AddRange(manifest.scopedRegistries);
}
// Attempt to find an entry in the scoped registries collection for the MSBuild for Unity URL
bool needToAddRegistry = true;
foreach (ScopedRegistry registry in scopedRegistries)
{
if (registry.url == MSBuildRegistryUrl)
{
needToAddRegistry = false;
}
}
// If no entry was found, add one.
if (needToAddRegistry)
{
ScopedRegistry registry = new ScopedRegistry();
registry.name = MSBuildRegistryName;
registry.url = MSBuildRegistryUrl;
registry.scopes = MSBuildRegistryScopes;
scopedRegistries.Add(registry);
}
// Update the manifest's scoped registries, as the collection may have been modified.
manifest.scopedRegistries = scopedRegistries.ToArray();
int dependenciesStartIndex = -1;
int scopedRegistriesStartIndex = -1;
int scopedRegistriesEndIndex = -1;
int packageLine = -1;
// Presume that we need to add the MSBuild for Unity package. If this value is false,
// we will check to see if the currently configured version meets or exceeds the
// minimum requirements.
bool needToAddPackage = true;
// Attempt to find the MSBuild for Unity package entry in the dependencies collection
// This loop also identifies the dependencies collection line and the start / end of a
// pre-existing scoped registries collections
for (int i = 0; i < manifestFileLines.Count; i++)
{
if (manifestFileLines[i].Contains("\"scopedRegistries\":"))
{
scopedRegistriesStartIndex = i;
}
if (manifestFileLines[i].Contains("],") && (scopedRegistriesStartIndex != -1) && (scopedRegistriesEndIndex == -1))
{
scopedRegistriesEndIndex = i;
}
if (manifestFileLines[i].Contains("\"dependencies\": {"))
{
dependenciesStartIndex = i;
}
if (manifestFileLines[i].Contains(MSBuildPackageName))
{
packageLine = i;
needToAddPackage = false;
}
}
// If no package was found add it to the dependencies collection.
if (needToAddPackage)
{
// Add the package to the collection (pad the entry with four spaces)
manifestFileLines.Insert(dependenciesStartIndex + 1, $" \"{MSBuildPackageName}\": \"{MSBuildPackageVersion}\",");
}
else
{
// Replace the line that currently exists
manifestFileLines[packageLine] = $" \"{MSBuildPackageName}\": \"{MSBuildPackageVersion}\",";
}
// Update the manifest file.
// First, serialize the scoped registry collection.
string serializedRegistriesJson = JsonUtility.ToJson(manifest, true);
// Ensure that the file is truncated to ensure it is always valid after writing.
using (FileStream outFile = new FileStream(manifestPath, FileMode.Truncate, FileAccess.Write))
{
using (StreamWriter writer = new StreamWriter(outFile))
{
bool scopedRegistriesWritten = false;
// Write each line of the manifest back to the file.
for (int i = 0; i < manifestFileLines.Count; i++)
{
if ((i >= scopedRegistriesStartIndex) && (i <= scopedRegistriesEndIndex))
{
// Skip these lines, they will be replaced.
continue;
}
if (!scopedRegistriesWritten && (i > 0))
{
// Trim the leading '{' and '\n' from the serialized scoped registries
serializedRegistriesJson = serializedRegistriesJson.Remove(0, 2);
// Trim, the trailing '\n' and '}'
serializedRegistriesJson = serializedRegistriesJson.Remove(serializedRegistriesJson.Length - 2);
// Append a trailing ',' to close the scopedRegistries node
serializedRegistriesJson = serializedRegistriesJson.Insert(serializedRegistriesJson.Length, ",");
writer.WriteLine(serializedRegistriesJson);
scopedRegistriesWritten = true;
}
writer.WriteLine(manifestFileLines[i]);
}
}
}
}
19
View Source File : FileContainerServer.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
private async Task<UploadResult> UploadAsync(RunnerActionPluginExecutionContext context, int uploaderId, CancellationToken token)
{
List<string> failedFiles = new List<string>();
long uploadedSize = 0;
string fileToUpload;
Stopwatch uploadTimer = new Stopwatch();
while (_fileUploadQueue.TryDequeue(out fileToUpload))
{
token.ThrowIfCancellationRequested();
try
{
using (FileStream fs = File.Open(fileToUpload, FileMode.Open, FileAccess.Read, FileShare.Read))
{
string itemPath = (_containerPath.TrimEnd('/') + "/" + fileToUpload.Remove(0, _sourceParentDirectory.Length + 1)).Replace('\\', '/');
bool failAndExit = false;
try
{
uploadTimer.Restart();
using (HttpResponseMessage response = await _fileContainerHttpClient.UploadFileAsync(_containerId, itemPath, fs, _projectId, cancellationToken: token, chunkSize: 4 * 1024 * 1024))
{
if (response == null || response.StatusCode != HttpStatusCode.Created)
{
context.Output($"Unable to copy file to server StatusCode={response?.StatusCode}: {response?.ReasonPhrase}. Source file path: {fileToUpload}. Target server path: {itemPath}");
if (response?.StatusCode == HttpStatusCode.Conflict)
{
// fail upload task but continue with any other files
context.Error($"Error '{fileToUpload}' has already been uploaded.");
}
else if (_fileContainerHttpClient.IsFastFailResponse(response))
{
// Fast fail: we received an http status code where we should abandon our efforts
context.Output($"Cannot continue uploading files, so draining upload queue of {_fileUploadQueue.Count} items.");
DrainUploadQueue(context);
failedFiles.Clear();
failAndExit = true;
throw new UploadFailedException($"Critical failure uploading '{fileToUpload}'");
}
else
{
context.Debug($"Adding '{fileToUpload}' to retry list.");
failedFiles.Add(fileToUpload);
}
throw new UploadFailedException($"Http failure response '{response?.StatusCode}': '{response?.ReasonPhrase}' while uploading '{fileToUpload}'");
}
uploadTimer.Stop();
context.Debug($"File: '{fileToUpload}' took {uploadTimer.ElapsedMilliseconds} milliseconds to finish upload");
uploadedSize += fs.Length;
OutputLogForFile(context, fileToUpload, $"Detail upload trace for file: {itemPath}", context.Debug);
}
}
catch (OperationCanceledException) when (token.IsCancellationRequested)
{
context.Output($"File upload has been cancelled during upload file: '{fileToUpload}'.");
throw;
}
catch (Exception ex)
{
context.Output($"Fail to upload '{fileToUpload}' due to '{ex.Message}'.");
context.Output(ex.ToString());
OutputLogForFile(context, fileToUpload, $"Detail upload trace for file that fail to upload: {itemPath}", context.Output);
if (failAndExit)
{
context.Debug("Exiting upload.");
throw;
}
}
}
Interlocked.Increment(ref _uploadFilesProcessed);
}
catch (Exception ex)
{
context.Output($"File error '{ex.Message}' when uploading file '{fileToUpload}'.");
throw ex;
}
}
return new UploadResult(failedFiles, uploadedSize);
}
19
View Source File : ContainerInfo.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public string TranslateToContainerPath(string path)
{
if (!string.IsNullOrEmpty(path))
{
foreach (var mapping in _pathMappings)
{
#if OS_WINDOWS
if (string.Equals(path, mapping.HostPath, StringComparison.OrdinalIgnoreCase))
{
return mapping.ContainerPath;
}
if (path.StartsWith(mapping.HostPath + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) ||
path.StartsWith(mapping.HostPath + Path.AltDirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
{
return mapping.ContainerPath + path.Remove(0, mapping.HostPath.Length);
}
#else
if (string.Equals(path, mapping.HostPath))
{
return mapping.ContainerPath;
}
if (path.StartsWith(mapping.HostPath + Path.DirectorySeparatorChar))
{
return mapping.ContainerPath + path.Remove(0, mapping.HostPath.Length);
}
#endif
}
}
return path;
}
19
View Source File : ContainerInfo.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public string TranslateToHostPath(string path)
{
if (!string.IsNullOrEmpty(path))
{
foreach (var mapping in _pathMappings)
{
#if OS_WINDOWS
if (string.Equals(path, mapping.ContainerPath, StringComparison.OrdinalIgnoreCase))
{
return mapping.HostPath;
}
if (path.StartsWith(mapping.ContainerPath + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) ||
path.StartsWith(mapping.ContainerPath + Path.AltDirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
{
return mapping.HostPath + path.Remove(0, mapping.ContainerPath.Length);
}
#else
if (string.Equals(path, mapping.ContainerPath))
{
return mapping.HostPath;
}
if (path.StartsWith(mapping.ContainerPath + Path.DirectorySeparatorChar))
{
return mapping.HostPath + path.Remove(0, mapping.ContainerPath.Length);
}
#endif
}
}
return path;
}
19
View Source File : ActionManifestManager.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public ActionDefinitionData Load(IExecutionContext executionContext, string manifestFile)
{
var templateContext = CreateTemplateContext(executionContext);
ActionDefinitionData actionDefinition = new ActionDefinitionData();
// Clean up file name real quick
// Instead of using Regex which can be computationally expensive,
// we can just remove the # of characters from the fileName according to the length of the basePath
string basePath = HostContext.GetDirectory(WellKnownDirectory.Actions);
string fileRelativePath = manifestFile;
if (manifestFile.Contains(basePath))
{
fileRelativePath = manifestFile.Remove(0, basePath.Length + 1);
}
try
{
var token = default(TemplateToken);
// Get the file ID
var fileId = templateContext.GetFileId(fileRelativePath);
// Add this file to the FileTable in executionContext if it hasn't been added already
// we use > since fileID is 1 indexed
if (fileId > executionContext.Global.FileTable.Count)
{
executionContext.Global.FileTable.Add(fileRelativePath);
}
// Read the file
var fileContent = File.ReadAllText(manifestFile);
using (var stringReader = new StringReader(fileContent))
{
var yamlObjectReader = new YamlObjectReader(fileId, stringReader);
token = TemplateReader.Read(templateContext, "action-root", yamlObjectReader, fileId, out _);
}
var actionMapping = token.replacedertMapping("action manifest root");
var actionOutputs = default(MappingToken);
var actionRunValueToken = default(TemplateToken);
foreach (var actionPair in actionMapping)
{
var propertyName = actionPair.Key.replacedertString($"action.yml property key");
switch (propertyName.Value)
{
case "name":
actionDefinition.Name = actionPair.Value.replacedertString("name").Value;
break;
case "outputs":
actionOutputs = actionPair.Value.replacedertMapping("outputs");
break;
case "description":
actionDefinition.Description = actionPair.Value.replacedertString("description").Value;
break;
case "inputs":
ConvertInputs(actionPair.Value, actionDefinition);
break;
case "runs":
// Defer runs token evaluation to after for loop to ensure that order of outputs doesn't matter.
actionRunValueToken = actionPair.Value;
break;
default:
Trace.Info($"Ignore action property {propertyName}.");
break;
}
}
// Evaluate Runs Last
if (actionRunValueToken != null)
{
actionDefinition.Execution = ConvertRuns(executionContext, templateContext, actionRunValueToken, fileRelativePath, actionOutputs);
}
}
catch (Exception ex)
{
Trace.Error(ex);
templateContext.Errors.Add(ex);
}
if (templateContext.Errors.Count > 0)
{
foreach (var error in templateContext.Errors)
{
Trace.Error($"Action.yml load error: {error.Message}");
executionContext.Error(error.Message);
}
throw new ArgumentException($"Fail to load {fileRelativePath}");
}
if (actionDefinition.Execution == null)
{
executionContext.Debug($"Loaded action.yml file: {StringUtil.ConvertToJson(actionDefinition)}");
throw new ArgumentException($"Top level 'runs:' section is required for {fileRelativePath}");
}
else
{
Trace.Info($"Loaded action.yml file: {StringUtil.ConvertToJson(actionDefinition)}");
}
return actionDefinition;
}
19
View Source File : ItemFinder.cs
License : MIT License
Project Creator : adainrivers
License : MIT License
Project Creator : adainrivers
private static string FixWords(string original)
{
if (original.StartsWith("`") || original.StartsWith("‘"))
{
original = original.Remove(0, 1);
}
return Words.Replace
(original,
m => WordFixes.TryGetValue(m.Groups[1].Value, out var value) ?
value :
m.Groups[1].Value);
}
19
View Source File : Utility.cs
License : MIT License
Project Creator : ADefWebserver
License : MIT License
Project Creator : ADefWebserver
public static string CleanOutlookFontDefinitions(string HtmlContent)
{
// Strip out Font Definitions from Outlook emails
string strResponse = "";
// Get range
int intStart = HtmlContent.IndexOf(@"/* Font Definitions */");
if(intStart < 0)
{
return strResponse;
}
intStart = intStart - 5;
int intStop = HtmlContent.IndexOf(@"-->",(intStart + 28));
if (intStop < 0)
{
return strResponse;
}
if (intStart >= intStop)
{
return strResponse;
}
// Strip contents
strResponse = HtmlContent.Remove(intStart, (intStop - intStart));
// Strip empty Style tags
strResponse = strResponse.Replace(@"<style><--></style>", "");
return strResponse;
}
19
View Source File : UploadController.cs
License : MIT License
Project Creator : ADefWebserver
License : MIT License
Project Creator : ADefWebserver
[HttpPost("[action]")]
public async Task<IActionResult> MultipleAsync(
IFormFile[] files, string CurrentDirectory)
{
try
{
if (HttpContext.Request.Form.Files.Any())
{
foreach (var file in HttpContext.Request.Form.Files)
{
// reconstruct the path to ensure everything
// goes to uploads directory
if(CurrentDirectory == null)
{
CurrentDirectory = "";
}
string RequestedPath =
CurrentDirectory.ToLower()
.Replace(environment.WebRootPath.ToLower(), "");
if (RequestedPath.Contains("\\uploads\\"))
{
RequestedPath =
RequestedPath.Replace("\\uploads\\", "");
}
// If RequestedPath begins with \\ remove them
if (RequestedPath.Length > 1)
{
if (RequestedPath.Substring(0, 1) == @"\")
{
RequestedPath = RequestedPath.Remove(0, 1);
}
}
string path =
Path.Combine(
environment.WebRootPath,
"uploads\\",
RequestedPath,
file.FileName);
using (var stream =
new FileStream(path, FileMode.Create))
{
await file.CopyToAsync(stream);
}
}
}
return StatusCode(200);
}
catch (Exception ex)
{
return StatusCode(500, ex.Message);
}
}
19
View Source File : MainWindow.xaml.cs
License : MIT License
Project Creator : ADeltaX
License : MIT License
Project Creator : ADeltaX
private void UpdateSuggestedList(string text)
{
//TODO: BROKEN
var filter = text;
if (filter.StartsWith(@"Computer\", StringComparison.InvariantCultureIgnoreCase))
filter = filter.Remove(0, @"Computer\".Length);
listViewSuggestion.ItemsSource = null;
if (string.IsNullOrEmpty(filter))
{
IList<string> str = new List<string>();
foreach (var x in treeRoot[0].RegistryHiveTreeViews)
str.Add(@"Computer\" + x.Name);
listViewSuggestion.ItemsSource = str;
}
else
{
var splitted = filter.Split(new char[] { '\\' }, 2);
if (splitted.Length >= 2)
{
splitted[1] = splitted[1].Trim();
List<RegistryHive> registries = new List<RegistryHive>();
foreach (var x in treeRoot[0].RegistryHiveTreeViews)
{
if (x.Name.Equals(splitted[0], StringComparison.InvariantCultureIgnoreCase))
registries.Add(x.AttachedHive);
}
IList<string> str = new List<string>();
var subSplitted = splitted[1].Split(new char[] { '\\' });
var subIncorporated = string.Join("\\", subSplitted, 0, subSplitted.Length - 1);
foreach (var reg in registries)
{
var key = reg.Root.OpenSubKey(splitted[1] == "" ? "\\" : subIncorporated);
if (key != null)
foreach (var subKey in key.SubKeys)
str.Add(@"Computer\" + splitted[0] + subKey.Name); //TODO
}
if (subSplitted.Length >= 1 && !string.IsNullOrEmpty(subSplitted[0]))
str = str.Where(x => x.StartsWith(@"Computer\" + splitted[0] + "\\" + splitted[1], StringComparison.InvariantCultureIgnoreCase)).ToList();
listViewSuggestion.ItemsSource = str;
}
else
{
IList<string> str = new List<string>();
foreach (var x in treeRoot[0].RegistryHiveTreeViews)
{
if (x.Name.StartsWith(splitted[0], StringComparison.InvariantCultureIgnoreCase))
str.Add(@"Computer\" + x.Name);
}
listViewSuggestion.ItemsSource = str;
}
}
}
19
View Source File : PortalFacetedIndexSearcher.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private string RemoveDuplicates(string input)
{
if (string.IsNullOrEmpty(input))
{
return input;
}
var uniqueWords = new List<string>();
var duplicateWords = new List<string>();
foreach (var word in input.Split(';', ','))
{
var trimmedWord = word.Trim();
if (string.IsNullOrEmpty(trimmedWord))
{
continue;
}
if (uniqueWords.Contains(trimmedWord))
{
duplicateWords.Add(trimmedWord);
continue;
}
uniqueWords.Add(trimmedWord);
}
foreach (var duplicateWord in duplicateWords)
{
var startIndex = input.IndexOf(duplicateWord, StringComparison.InvariantCulture) + duplicateWord.Length;
var secondDuplicateIndex = input.IndexOf(duplicateWord, startIndex, StringComparison.InvariantCulture);
input = input.Remove(secondDuplicateIndex, duplicateWord.Length);
}
return input;
}
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 : 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 : UrlBuilder.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public new string ToString()
{
base.Query = Query.TrimStart('?'); // trim the '?' because the base setter adds it
if (!Path.StartsWith("~/"))
{
return Uri.AbsoluteUri;
}
// we allow the Path to store a ~ based path which should be removed when calling ToString()
UrlBuilder temp = new UrlBuilder(this);
temp.Path = temp.Path.Remove(0, 2);
return temp.Uri.AbsoluteUri;
}
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 : CommandsExtensions.cs
License : GNU General Public License v3.0
Project Creator : aelariane
License : GNU General Public License v3.0
Project Creator : aelariane
public static string ParseStringWithSpaces(string[] src, ref int index)
{
string sym = '"'.ToString();
if (src[index].StartsWith(sym))
{
int startIndex = index;
bool found = false;
List<string> tmp = new List<string>();
tmp.Add(src[index++].Substring(1));
while (index < src.Length)
{
if (src[index].EndsWith(sym))
{
found = true;
tmp.Add(src[index].Remove(src[index].Length - 1, 1));
break;
}
tmp.Add(src[index++]);
}
if (found)
{
return string.Join(" ", tmp.ToArray());
}
index = startIndex;
}
return src[index];
}
19
View Source File : User.cs
License : GNU General Public License v3.0
Project Creator : aelariane
License : GNU General Public License v3.0
Project Creator : aelariane
private static void RefreshProfilesList()
{
var temp = System.IO.Directory.GetFiles(directory);
var tmp =
(from t in temp
where !t.Contains(Example)
select t.Remove(0, directory.Length)
.Replace(Extension, string.Empty))
.ToList();
AllProfiles = tmp.ToArray();
}
19
View Source File : Chat.cs
License : GNU General Public License v3.0
Project Creator : aelariane
License : GNU General Public License v3.0
Project Creator : aelariane
private static string CheckForMention(string message)
{
string sentData = message;
if (message.Contains("@"))
{
var strings = message.Split(' ');
sentData = string.Empty;
for (int i = 0; i < strings.Length; i++)
{
string str = strings[i];
if (str.Contains("@") && str.Length > 1)
{
string id = str.Remove(str.IndexOf("@"), 1);
if (int.TryParse(id, out int ID))
{
sentData += (i == 0 ? "" : " ") + "<b>[" + id + "] " + PhotonPlayer.Find(System.Convert.ToInt32(ID)).UIName.ToHTMLFormat() + "</b>";
}
else sentData += (i == 0 ? "" : " ") + strings[i];
}
else sentData += (i == 0 ? "" : " ") + str;
}
}
return sentData;
}
19
View Source File : NGUITools.cs
License : GNU General Public License v3.0
Project Creator : aelariane
License : GNU General Public License v3.0
Project Creator : aelariane
public static string StripSymbols(string text)
{
if (text != null)
{
int i = 0;
int length = text.Length;
while (i < length)
{
char c = text[i];
if (c == '[')
{
int num = NGUITools.ParseSymbol(text, i, null, false);
if (num > 0)
{
text = text.Remove(i, num);
length = text.Length;
continue;
}
}
i++;
}
}
return text;
}
19
View Source File : CacheResources.cs
License : GNU General Public License v3.0
Project Creator : aelariane
License : GNU General Public License v3.0
Project Creator : aelariane
public static GameObject RCLoad(string _name)
{
string name = _name.StartsWith("RCreplacedet/") ? _name.Remove(0, 8) : _name;
if (!cacheRC.ContainsKey(name))
{
return cacheRC[name] = (GameObject)RC.RCManager.replacedet.Load(name);
}
return cacheRC[name];
}
19
View Source File : CommandsNextUtilities.cs
License : MIT License
Project Creator : Aiko-IT-Systems
License : MIT License
Project Creator : Aiko-IT-Systems
internal static string CleanupString(this string s, IList<int> indices)
{
if (!indices.Any())
return s;
var li = indices.Last();
var ll = 1;
for (var x = indices.Count - 2; x >= 0; x--)
{
if (li - indices[x] == ll)
{
ll++;
continue;
}
s = s.Remove(li - ll + 1, ll);
li = indices[x];
ll = 1;
}
return s.Remove(li - ll + 1, ll);
}
19
View Source File : Util.cs
License : MIT License
Project Creator : ajayyy
License : MIT License
Project Creator : ajayyy
public static string FixupNewlines( string text )
{
bool newLinesRemaining = true;
while ( newLinesRemaining )
{
int CIndex = text.IndexOf( "\\n" );
if ( CIndex == -1 )
{
newLinesRemaining = false;
}
else
{
text = text.Remove( CIndex - 1, 3 );
text = text.Insert( CIndex - 1, "\n" );
}
}
return text;
}
19
View Source File : InternalExpressionHelper.cs
License : Apache License 2.0
Project Creator : AKlaus
License : Apache License 2.0
Project Creator : AKlaus
private static string EnsureControllerName(Type controllerType)
{
var controllerName = controllerType.Name;
if (!controllerName.EndsWith("Controller", StringComparison.OrdinalIgnoreCase))
{
throw new ArgumentException("Action target must end in controller", "action");
}
controllerName = controllerName.Remove(controllerName.Length - 10, 10);
if (controllerName.Length == 0)
{
throw new ArgumentException("Action cannot route to controller", "action");
}
return controllerName;
}
19
View Source File : ItemParser.cs
License : GNU General Public License v3.0
Project Creator : AlanMorel
License : GNU General Public License v3.0
Project Creator : AlanMorel
protected override List<ItemMetadata> Parse()
{
// Item breaking ingredients
Dictionary<int, List<ItemBreakReward>> rewards = new();
foreach (PackFileEntry entry in Resources.XmlReader.Files)
{
if (!entry.Name.StartsWith("table/itembreakingredient"))
{
continue;
}
XmlDoreplacedent innerDoreplacedent = Resources.XmlReader.GetXmlDoreplacedent(entry);
XmlNodeList individualItems = innerDoreplacedent.SelectNodes($"/ms2/item");
foreach (XmlNode nodes in individualItems)
{
string locale = nodes.Attributes["locale"]?.Value ?? "";
if (locale != "NA" && locale != "")
{
continue;
}
int itemID = int.Parse(nodes.Attributes["ItemID"].Value);
rewards[itemID] = new();
int ingredienreplacedemID1 = int.Parse(nodes.Attributes["IngredienreplacedemID1"]?.Value ?? "0");
int ingredientCount1 = int.Parse(nodes.Attributes["IngredientCount1"]?.Value ?? "0");
rewards[itemID].Add(new(ingredienreplacedemID1, ingredientCount1));
_ = int.TryParse(nodes.Attributes["IngredienreplacedemID2"]?.Value ?? "0", out int ingredienreplacedemID2);
_ = int.TryParse(nodes.Attributes["IngredientCount2"]?.Value ?? "0", out int ingredientCount2);
rewards[itemID].Add(new(ingredienreplacedemID2, ingredientCount2));
_ = int.TryParse(nodes.Attributes["IngredienreplacedemID3"]?.Value ?? "0", out int ingredienreplacedemID3);
_ = int.TryParse(nodes.Attributes["IngredientCount3"]?.Value ?? "0", out int ingredientCount3);
rewards[itemID].Add(new(ingredienreplacedemID3, ingredientCount3));
}
}
//Item Name
Dictionary<int, string> names = new();
foreach (PackFileEntry entry in Resources.XmlReader.Files)
{
if (!entry.Name.StartsWith("string/en/itemname.xml"))
{
continue;
}
XmlDoreplacedent innerDoreplacedent = Resources.XmlReader.GetXmlDoreplacedent(entry);
XmlNodeList nodes = innerDoreplacedent.SelectNodes($"/ms2/key");
foreach (XmlNode node in nodes)
{
int itemId = int.Parse(node.Attributes["id"].Value);
if (node.Attributes["name"] == null)
{
continue;
}
string itemName = node.Attributes["name"].Value;
names[itemId] = itemName;
}
}
// Item rarity
Dictionary<int, int> rarities = new();
foreach (PackFileEntry entry in Resources.XmlReader.Files)
{
if (!entry.Name.StartsWith("table/na/itemwebfinder"))
{
continue;
}
XmlDoreplacedent innerDoreplacedent = Resources.XmlReader.GetXmlDoreplacedent(entry);
XmlNodeList nodes = innerDoreplacedent.SelectNodes($"/ms2/key");
foreach (XmlNode node in nodes)
{
int itemId = int.Parse(node.Attributes["id"].Value);
int rarity = int.Parse(node.Attributes["grade"].Value);
rarities[itemId] = rarity;
}
}
// Items
List<ItemMetadata> items = new();
foreach (PackFileEntry entry in Resources.XmlReader.Files)
{
if (!entry.Name.StartsWith("item/"))
{
continue;
}
ItemMetadata metadata = new();
string filename = Path.GetFileNameWithoutExtension(entry.Name);
int itemId = int.Parse(filename);
if (items.Exists(item => item.Id == itemId))
{
continue;
}
metadata.Id = itemId;
Debug.replacedert(metadata.Id > 0, $"Invalid Id {metadata.Id} from {itemId}");
// Parse XML
XmlDoreplacedent doreplacedent = Resources.XmlReader.GetXmlDoreplacedent(entry);
XmlNode item = doreplacedent.SelectSingleNode("ms2/environment");
// Tag
XmlNode basic = item.SelectSingleNode("basic");
metadata.Tag = basic.Attributes["stringTag"].Value;
// Gear/Cosmetic slot
XmlNode slots = item.SelectSingleNode("slots");
XmlNode slot = slots.FirstChild;
bool slotResult = Enum.TryParse(slot.Attributes["name"].Value, out metadata.Slot);
if (!slotResult && !string.IsNullOrEmpty(slot.Attributes["name"].Value))
{
Console.WriteLine($"Failed to parse item slot for {itemId}: {slot.Attributes["name"].Value}");
}
int totalSlots = slots.SelectNodes("slot").Count;
if (totalSlots > 1)
{
if (metadata.Slot == ItemSlot.CL || metadata.Slot == ItemSlot.PA)
{
metadata.IsDress = true;
}
else if (metadata.Slot == ItemSlot.RH || metadata.Slot == ItemSlot.LH)
{
metadata.IsTwoHand = true;
}
}
// Hair data
if (slot.Attributes["name"].Value == "HR")
{
int replacedetNodeCount = slot.SelectNodes("replacedet").Count;
XmlNode replacedet = slot.FirstChild;
XmlNode scaleNode = slot.SelectSingleNode("scale");
if (replacedetNodeCount == 3) // This hair has a front and back positionable hair
{
XmlNode backHair = replacedet.NextSibling; // back hair info
XmlNode frontHair = backHair.NextSibling; // front hair info
int backHairNodes = backHair.SelectNodes("custom").Count;
CoordF[] bPosCord = new CoordF[backHairNodes];
CoordF[] bPosRotation = new CoordF[backHairNodes];
CoordF[] fPosCord = new CoordF[backHairNodes];
CoordF[] fPosRotation = new CoordF[backHairNodes];
for (int i = 0; i < backHairNodes; i++)
{
foreach (XmlNode backPresets in backHair)
{
if (backPresets.Name == "custom")
{
bPosCord[i] = CoordF.Parse(backPresets.Attributes["position"].Value);
bPosRotation[i] = CoordF.Parse(backPresets.Attributes["rotation"].Value);
}
}
foreach (XmlNode frontPresets in frontHair)
{
if (frontPresets.Name == "custom")
{
fPosCord[i] = CoordF.Parse(frontPresets.Attributes["position"].Value);
fPosRotation[i] = CoordF.Parse(frontPresets.Attributes["position"].Value);
}
}
HairPresets hairPresets = new()
{
};
hairPresets.BackPositionCoord = bPosCord[i];
hairPresets.BackPositionRotation = bPosRotation[i];
hairPresets.FrontPositionCoord = fPosCord[i];
hairPresets.FrontPositionRotation = fPosRotation[i];
hairPresets.MinScale = float.Parse(scaleNode?.Attributes["min"]?.Value ?? "0");
hairPresets.MaxScale = float.Parse(scaleNode?.Attributes["max"]?.Value ?? "0");
metadata.HairPresets.Add(hairPresets);
}
}
else if (replacedetNodeCount == 2) // This hair only has back positionable hair
{
XmlNode backHair = replacedet.NextSibling; // back hair info
int backHairNodes = backHair.SelectNodes("custom").Count;
CoordF[] bPosCord = new CoordF[backHairNodes];
CoordF[] bPosRotation = new CoordF[backHairNodes];
for (int i = 0; i < backHairNodes; i++)
{
foreach (XmlNode backPresets in backHair)
{
if (backPresets.Name == "custom")
{
bPosCord[i] = CoordF.Parse(backPresets.Attributes["position"].Value);
bPosRotation[i] = CoordF.Parse(backPresets.Attributes["rotation"].Value);
}
}
HairPresets hairPresets = new()
{
};
hairPresets.BackPositionCoord = bPosCord[i];
hairPresets.BackPositionRotation = bPosRotation[i];
hairPresets.FrontPositionCoord = CoordF.Parse("0, 0, 0");
hairPresets.FrontPositionRotation = CoordF.Parse("0, 0, 0");
hairPresets.MinScale = float.Parse(scaleNode?.Attributes["min"]?.Value ?? "0");
hairPresets.MaxScale = float.Parse(scaleNode?.Attributes["max"]?.Value ?? "0");
metadata.HairPresets.Add(hairPresets);
}
}
else // hair does not have back or front positionable hair
{
HairPresets hairPresets = new()
{
};
hairPresets.BackPositionCoord = CoordF.Parse("0, 0, 0");
hairPresets.BackPositionRotation = CoordF.Parse("0, 0, 0");
hairPresets.FrontPositionCoord = CoordF.Parse("0, 0, 0");
hairPresets.FrontPositionRotation = CoordF.Parse("0, 0, 0");
hairPresets.MinScale = float.Parse(scaleNode?.Attributes["min"]?.Value ?? "0");
hairPresets.MaxScale = float.Parse(scaleNode?.Attributes["max"]?.Value ?? "0");
metadata.HairPresets.Add(hairPresets);
}
}
// Color data
XmlNode customize = item.SelectSingleNode("customize");
metadata.ColorIndex = int.Parse(customize.Attributes["defaultColorIndex"].Value);
metadata.ColorPalette = int.Parse(customize.Attributes["colorPalette"].Value);
// Badge slot
XmlNode gem = item.SelectSingleNode("gem");
bool gemResult = Enum.TryParse(gem.Attributes["system"].Value, out metadata.Gem);
if (!gemResult && !string.IsNullOrEmpty(gem.Attributes["system"].Value))
{
Console.WriteLine($"Failed to parse badge slot for {itemId}: {gem.Attributes["system"].Value}");
}
// Inventory tab and max stack size
XmlNode property = item.SelectSingleNode("property");
try
{
byte type = byte.Parse(property.Attributes["type"].Value);
byte subType = byte.Parse(property.Attributes["subtype"].Value);
bool skin = byte.Parse(property.Attributes["skin"].Value) != 0;
metadata.Tab = GetTab(type, subType, skin);
metadata.IsTemplate = byte.Parse(property.Attributes["skinType"]?.Value ?? "0") == 99;
metadata.TradeableCount = byte.Parse(property.Attributes["tradableCount"].Value);
metadata.RepackageCount = byte.Parse(property.Attributes["rePackingLimitCount"].Value);
metadata.RepackageItemConsumeCount = byte.Parse(property.Attributes["rePackingItemConsumeCount"].Value);
metadata.BlackMarketCategory = property.Attributes["blackMarketCategory"].Value;
// sales price
XmlNode sell = property.SelectSingleNode("sell");
metadata.SellPrice = sell.Attributes["price"]?.Value.Split(',').Select(int.Parse).ToList() ?? null;
metadata.SellPriceCustom = sell.Attributes["priceCustom"]?.Value.Split(',').Select(int.Parse).ToList() ?? null;
}
catch (Exception e)
{
Console.WriteLine($"Failed to parse tab slot for {itemId}: {e.Message}");
}
metadata.StackLimit = int.Parse(property.Attributes["slotMax"].Value);
// Rarity
XmlNode option = item.SelectSingleNode("option");
metadata.OptionStatic = int.Parse(option.Attributes["static"].Value);
metadata.OptionRandom = int.Parse(option.Attributes["random"].Value);
metadata.OptionConstant = int.Parse(option.Attributes["constant"].Value);
metadata.OptionLevelFactor = int.Parse(option.Attributes["optionLevelFactor"].Value);
XmlNode function = item.SelectSingleNode("function");
string contentType = function.Attributes["name"].Value;
metadata.FunctionData.Name = contentType;
// Item boxes
if (contentType == "OpenItemBox")
{
// selection boxes are SelecreplacedemBox and 1,boxid
// normal boxes are OpenItemBox and 0,1,0,boxid
// fragments are OpenItemBox and 0,1,0,boxid,required_amount
if (function.Attributes["parameter"].Value.Contains('l'))
{
continue; // TODO: Implement these CN items. Skipping for now
}
List<string> parameters = new(function.Attributes["parameter"].Value.Split(","));
OpenItemBox box = new();
box.RequiredItemId = int.Parse(parameters[0]);
box.ReceiveOneItem = parameters[1] == "1";
box.BoxId = int.Parse(parameters[3]);
box.AmountRequired = 1;
if (parameters.Count == 5)
{
box.AmountRequired = int.Parse(parameters[4]);
}
metadata.FunctionData.OpenItemBox = box;
}
else if (contentType == "SelecreplacedemBox")
{
if (function.Attributes["parameter"].Value.Contains('l'))
{
continue; // TODO: Implement these CN items. Skipping for now
}
List<string> parameters = new(function.Attributes["parameter"].Value.Split(","));
parameters.RemoveAll(param => param.Length == 0);
SelecreplacedemBox box = new();
box.GroupId = int.Parse(parameters[0]);
box.BoxId = int.Parse(parameters[1]);
metadata.FunctionData.SelecreplacedemBox = box;
}
else if (contentType == "ChatEmoticonAdd")
{
ChatEmoticonAdd sticker = new();
string rawParameter = function.Attributes["parameter"].Value;
string decodedParameter = HttpUtility.HtmlDecode(rawParameter);
XmlDoreplacedent xmlParameter = new();
xmlParameter.LoadXml(decodedParameter);
XmlNode functionParameters = xmlParameter.SelectSingleNode("v");
sticker.Id = byte.Parse(functionParameters.Attributes["id"].Value);
sticker.Duration = int.Parse(functionParameters.Attributes["durationSec"]?.Value ?? "0");
metadata.FunctionData.ChatEmoticonAdd = sticker;
}
else if (contentType == "OpenMreplacedive")
{
OpenMreplacediveEvent mreplacediveEvent = new();
string rawParameter = function.Attributes["parameter"].Value;
string cleanParameter = rawParameter.Remove(1, 1); // remove the unwanted space
string decodedParameter = HttpUtility.HtmlDecode(cleanParameter);
XmlDoreplacedent xmlParameter = new();
xmlParameter.LoadXml(decodedParameter);
XmlNode functionParameters = xmlParameter.SelectSingleNode("v");
mreplacediveEvent.FieldId = int.Parse(functionParameters.Attributes["fieldID"].Value);
mreplacediveEvent.Duration = int.Parse(functionParameters.Attributes["portalDurationTick"].Value);
mreplacediveEvent.Capacity = byte.Parse(functionParameters.Attributes["maxCount"].Value);
metadata.FunctionData.OpenMreplacediveEvent = mreplacediveEvent;
}
else if (contentType == "LevelPotion")
{
LevelPotion levelPotion = new();
string rawParameter = function.Attributes["parameter"].Value;
string decodedParameter = HttpUtility.HtmlDecode(rawParameter);
XmlDoreplacedent xmlParameter = new();
xmlParameter.LoadXml(decodedParameter);
XmlNode functionParameters = xmlParameter.SelectSingleNode("v");
levelPotion.TargetLevel = byte.Parse(functionParameters.Attributes["targetLevel"].Value);
metadata.FunctionData.LevelPotion = levelPotion;
}
else if (contentType == "VIPCoupon")
{
VIPCoupon coupon = new();
string rawParameter = function.Attributes["parameter"].Value;
string decodedParameter = HttpUtility.HtmlDecode(rawParameter);
XmlDoreplacedent xmlParameter = new();
xmlParameter.LoadXml(decodedParameter);
XmlNode functionParameters = xmlParameter.SelectSingleNode("v");
coupon.Duration = int.Parse(functionParameters.Attributes["period"].Value);
metadata.FunctionData.VIPCoupon = coupon;
}
else if (contentType == "HongBao")
{
HongBaoData hongBao = new();
string rawParameter = function.Attributes["parameter"].Value;
string decodedParameter = HttpUtility.HtmlDecode(rawParameter);
XmlDoreplacedent xmlParameter = new();
xmlParameter.LoadXml(decodedParameter);
XmlNode functionParameters = xmlParameter.SelectSingleNode("v");
hongBao.Id = int.Parse(functionParameters.Attributes["itemId"].Value);
hongBao.Count = short.Parse(functionParameters.Attributes["totalCount"].Value);
hongBao.TotalUsers = byte.Parse(functionParameters.Attributes["totalUser"].Value);
hongBao.Duration = int.Parse(functionParameters.Attributes["durationSec"].Value);
metadata.FunctionData.HongBao = hongBao;
}
else if (contentType == "SuperWorldChat")
{
string[] parameters = function.Attributes["parameter"].Value.Split(",");
metadata.FunctionData.Id = int.Parse(parameters[0]); // only storing the first parameter. Not sure if the server uses the other 2.
}
else if (contentType == "OpenGachaBox")
{
string[] parameters = function.Attributes["parameter"].Value.Split(",");
metadata.FunctionData.Id = int.Parse(parameters[0]); // only storing the first parameter. Unknown what the second parameter is used for.
}
else if (contentType == "OpenCoupleEffectBox")
{
OpenCoupleEffectBox box = new();
string[] parameters = function.Attributes["parameter"].Value.Split(",");
box.Id = int.Parse(parameters[0]);
box.Rarity = byte.Parse(parameters[1]);
metadata.FunctionData.OpenCoupleEffectBox = box;
}
else if (contentType == "InstallBillBoard")
{
InstallBillboard balloon = new();
string rawParameter = function.Attributes["parameter"].Value;
string decodedParameter = HttpUtility.HtmlDecode(rawParameter);
XmlDoreplacedent xmlParameter = new();
xmlParameter.LoadXml(decodedParameter);
XmlNode functionParameters = xmlParameter.SelectSingleNode("v");
balloon.InteractId = int.Parse(functionParameters.Attributes["interactID"].Value);
balloon.Duration = int.Parse(functionParameters.Attributes["durationSec"].Value);
balloon.Model = functionParameters.Attributes["model"].Value;
balloon.replacedet = functionParameters.Attributes["replacedet"]?.Value ?? "";
balloon.NormalState = functionParameters.Attributes["normal"].Value;
balloon.Reactable = functionParameters.Attributes["reactable"].Value;
balloon.Scale = float.Parse(functionParameters.Attributes["scale"]?.Value ?? "0");
metadata.FunctionData.InstallBillboard = balloon;
}
else if (contentType == "replacedleScroll" || contentType == "ItemExchangeScroll" || contentType == "OpenInstrument" || contentType == "StoryBook" || contentType == "FishingRod" || contentType == "ItemChangeBeauty"
|| contentType == "ItemRePackingScroll")
{
metadata.FunctionData.Id = int.Parse(function.Attributes["parameter"].Value);
}
// Music score charges
XmlNode musicScore = item.SelectSingleNode("MusicScore");
metadata.PlayCount = int.Parse(musicScore.Attributes["playCount"].Value);
metadata.FileName = musicScore.Attributes["fileName"].Value;
metadata.IsCustomScore = bool.Parse(musicScore.Attributes["isCustomNote"].Value);
// Shop ID from currency items
if (item["Shop"] != null)
{
XmlNode shop = item.SelectSingleNode("Shop");
metadata.ShopID = int.Parse(shop.Attributes["systemShopID"].Value);
}
XmlNode skill = item.SelectSingleNode("skill");
metadata.SkillID = int.Parse(skill.Attributes["skillID"].Value);
XmlNode limit = item.SelectSingleNode("limit");
metadata.EnableBreak = byte.Parse(limit.Attributes["enableBreak"].Value) == 1;
metadata.Level = int.Parse(limit.Attributes["levelLimit"].Value);
metadata.TransferType = (TransferType) byte.Parse(limit.Attributes["transferType"].Value);
metadata.Sellable = byte.Parse(limit.Attributes["shopSell"].Value) == 1;
metadata.RecommendJobs = limit.Attributes["recommendJobs"]?.Value.Split(",").Where(x => !string.IsNullOrEmpty(x)).Select(int.Parse).ToList();
metadata.Gender = (Gender) byte.Parse(limit.Attributes["genderLimit"].Value);
XmlNode installNode = item.SelectSingleNode("install");
metadata.IsCubeSolid = byte.Parse(installNode.Attributes["cubeProp"].Value) == 1;
metadata.ObjectId = int.Parse(installNode.Attributes["objCode"].Value);
XmlNode housingNode = item.SelectSingleNode("housing");
string value = housingNode.Attributes["categoryTag"]?.Value;
if (value is not null)
{
List<string> categories = new(value.Split(","));
_ = short.TryParse(categories[0], out short category);
metadata.HousingCategory = (ItemHousingCategory) category;
}
// Item breaking ingredients
if (rewards.ContainsKey(itemId))
{
metadata.BreakRewards = rewards[itemId];
}
// Item rarities
if (rarities.ContainsKey(itemId))
{
metadata.Rarity = rarities[itemId];
}
// Item Names
if (names.ContainsKey(itemId))
{
metadata.Name = names[itemId];
}
items.Add(metadata);
}
return items;
}
19
View Source File : WordsToNumbers.cs
License : MIT License
Project Creator : AlbertMN
License : MIT License
Project Creator : AlbertMN
public int EnglishGet(string words) {
//Thanks to https://www.programmingalgorithms.com/algorithm/words-to-numbers/
if (string.IsNullOrEmpty(words)) return -1;
words = words.Trim();
words += ' ';
int number = -1;
string[] singles = new string[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
string[] teens = new string[] { "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
string[] tens = new string[] { "", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninty" };
string[] powers = new string[] { "", "thousand", "million", "billion", "trillion", "quadrillion", "quintillion" };
for (int i = powers.Length - 1; i >= 0; i--) {
if (!string.IsNullOrEmpty(powers[i])) {
int index = words.IndexOf(powers[i]);
if (index >= 0 && words[index + powers[i].Length] == ' ') {
int count = EnglishGet(words.Substring(0, index));
number += count * (int)Math.Pow(1000, i);
words = words.Remove(0, index);
}
}
}
{
int index = words.IndexOf("hundred");
if (index >= 0 && words[index + "hundred".Length] == ' ') {
int count = EnglishGet(words.Substring(0, index));
number += count * 100;
words = words.Remove(0, index);
}
}
for (int i = tens.Length - 1; i >= 0; i--) {
if (!string.IsNullOrEmpty(tens[i])) {
int index = words.IndexOf(tens[i]);
if (index >= 0 && words[index + tens[i].Length] == ' ') {
number += (int)(i * 10);
words = words.Remove(0, index);
}
}
}
for (int i = teens.Length - 1; i >= 0; i--) {
if (!string.IsNullOrEmpty(teens[i])) {
int index = words.IndexOf(teens[i]);
if (index >= 0 && words[index + teens[i].Length] == ' ') {
number += (int)(i + 10);
words = words.Remove(0, index);
}
}
}
for (int i = singles.Length - 1; i >= 0; i--) {
if (!string.IsNullOrEmpty(singles[i])) {
int index = words.IndexOf(singles[i] + ' ');
if (index >= 0 && words[index + singles[i].Length] == ' ') {
number += (int)(i);
words = words.Remove(0, index);
}
}
}
return number;
}
19
View Source File : Translator.cs
License : MIT License
Project Creator : AlbertMN
License : MIT License
Project Creator : AlbertMN
public static void TranslateWinForms(string domain, ControlCollection ctrl) {
foreach (Control xx in ctrl) {
if (xx is Label || xx is Button || xx is CheckBox || xx is LinkLabel) {
if (xx.Text[0] != '|') {
xx.Text = Translator.__(xx.Text, domain);
} else {
xx.Text = xx.Text.Remove(0, 1);
}
//TODO ADD TOOLTIP TEXT IF "_hover_content" EXISTS
}
}
}
19
View Source File : StatisticsCounter.cs
License : GNU General Public License v3.0
Project Creator : Albo1125
License : GNU General Public License v3.0
Project Creator : Albo1125
public static void AddCountToStatistic(string Statistic, string PluginName)
{
try
{
SimpleAES StringEncrypter = new SimpleAES();
Directory.CreateDirectory(Directory.GetParent(StatisticsFilePath).FullName);
if (!File.Exists(StatisticsFilePath))
{
new XDoreplacedent(
new XElement("LSPDFRPlus")
)
.Save(StatisticsFilePath);
}
string pswd = Environment.UserName;
string EncryptedStatistic = XmlConvert.EncodeName(StringEncrypter.EncryptToString(Statistic + PluginName + pswd));
string EncryptedPlugin = XmlConvert.EncodeName(StringEncrypter.EncryptToString(PluginName + pswd));
XDoreplacedent xdoc = XDoreplacedent.Load(StatisticsFilePath);
char[] trim = new char[] { '\'', '\"', ' ' };
XElement LSPDFRPlusElement;
if (xdoc.Element("LSPDFRPlus") == null)
{
LSPDFRPlusElement = new XElement("LSPDFRPlus");
xdoc.Add(LSPDFRPlusElement);
}
LSPDFRPlusElement = xdoc.Element("LSPDFRPlus");
XElement StatisticElement;
if (LSPDFRPlusElement.Elements(EncryptedStatistic).Where(x => (string)x.Attribute("Plugin") == EncryptedPlugin).ToList().Count == 0)
{
//Game.LogTrivial("Creating new statistic entry.");
StatisticElement = new XElement(EncryptedStatistic);
StatisticElement.Add(new XAttribute("Plugin", EncryptedPlugin));
LSPDFRPlusElement.Add(StatisticElement);
}
StatisticElement = LSPDFRPlusElement.Elements(EncryptedStatistic).Where(x => (string)x.Attribute("Plugin") == EncryptedPlugin).FirstOrDefault();
int StatisticCount;
if (StatisticElement.IsEmpty)
{
StatisticCount = 0;
}
else
{
string DecryptedStatistic = StringEncrypter.DecryptString(XmlConvert.DecodeName(StatisticElement.Value));
//Game.LogTrivial("Decryptedstatistic: " + DecryptedStatistic);
int index = DecryptedStatistic.IndexOf(EncryptedStatistic);
string cleanPath = (index < 0)
? "0"
: DecryptedStatistic.Remove(index, EncryptedStatistic.Length);
//if (cleanPath == "0") { Game.LogTrivial("Cleanpath debug 2"); }
index = cleanPath.IndexOf(pswd);
cleanPath = (index < 0)
? "0"
: cleanPath.Remove(index, pswd.Length);
//if (cleanPath == "0") { Game.LogTrivial("Cleanpath debug 1"); }
StatisticCount = int.Parse(cleanPath);
}
//Game.LogTrivial("Statisticscount: " + StatisticCount.ToString());
StatisticCount++;
string ValueToWrite = StatisticCount.ToString() + pswd;
int indextoinsertat = LSPDFRPlusHandler.rnd.Next(ValueToWrite.Length);
ValueToWrite = ValueToWrite.Substring(0, indextoinsertat) + EncryptedStatistic + ValueToWrite.Substring(indextoinsertat);
//Game.LogTrivial("Valueotwrite: " + ValueToWrite);
StatisticElement.Value = XmlConvert.EncodeName(StringEncrypter.EncryptToString(ValueToWrite));
xdoc.Save(StatisticsFilePath);
}
catch (System.Threading.ThreadAbortException e) { }
catch (Exception e)
{
Game.LogTrivial("LSPDFR+ encountered a statistics exception. It was: " + e.ToString());
Game.DisplayNotification("~r~LSPDFR+: Statistics error.");
}
}
19
View Source File : AutoComputeShaderNodeView.cs
License : MIT License
Project Creator : alelievr
License : MIT License
Project Creator : alelievr
Type ComputeShaderTypeToCSharp(string computeShaderType)
{
if (computeShaderType.StartsWith("RW"))
computeShaderType = computeShaderType.Remove(0, 2);
switch (computeShaderType)
{
case "bool": return typeof(bool);
case "int": return typeof(int);
case "float": return typeof(float);
case "int2":
case "float2": return typeof(Vector2);
case "int3":
case "float3": return typeof(Vector3);
case "int4":
case "float4": return typeof(Vector4);
case "Texture2D": return typeof(Texture2D);
case "Texture2DArray": return typeof(Texture2DArray);
case "Texture3D": return typeof(Texture3D);
case "TextureCube": return typeof(Cubemap);
case "TextureCubeArray": return typeof(CubemapArray);
case "Buffer":
case "ByteAddressBuffer":
case "StructuredBuffer": return typeof(ComputeBuffer);
default: throw new Exception("Unknown compute shader type " + computeShaderType);
}
}
19
View Source File : MethodHelper.cs
License : MIT License
Project Creator : AlenToma
License : MIT License
Project Creator : AlenToma
internal static ISqlCommand ProcessSql(this IRepository repository, TransactionSqlConnection connection, IDbTransaction tran, string sql)
{
var i = 1;
var dicCols = new SafeValueType<string, Tuple<object, SqlDbType>>();
MatchCollection matches = null;
while ((matches = stringExp.Matches(sql)).Count > 0)
{
var exp = matches[0];
var col = "@CO" + i + "L";
object str = exp.Value.TrimEnd(']').Substring(@"String\[".Length - 1);
sql = sql.Remove(exp.Index, exp.Value.Length);
sql = sql.Insert(exp.Index, col);
var v = str.ConvertValue<string>();
if (string.Equals(v, "null", StringComparison.OrdinalIgnoreCase))
v = null;
dicCols.TryAdd(col, new Tuple<object, SqlDbType>(v, SqlDbType.NVarChar));
i++;
}
while ((matches = dateExp.Matches(sql)).Count > 0)
{
var exp = matches[0];
var col = "@CO" + i + "L";
object str = exp.Value.TrimEnd(']').Substring(@"Date\[".Length - 1);
sql = sql.Remove(exp.Index, exp.Value.Length);
sql = sql.Insert(exp.Index, col);
dicCols.TryAdd(col, new Tuple<object, SqlDbType>(str.ConvertValue<DateTime?>(), SqlDbType.DateTime));
i++;
}
while ((matches = guidExp.Matches(sql)).Count > 0)
{
var exp = matches[0];
var col = "@CO" + i + "L";
object str = exp.Value.TrimEnd(']').Substring(@"Guid\[".Length - 1);
sql = sql.Remove(exp.Index, exp.Value.Length);
sql = sql.Insert(exp.Index, col);
dicCols.TryAdd(col, new Tuple<object, SqlDbType>(str.ConvertValue<Guid?>(), SqlDbType.UniqueIdentifier));
i++;
}
while ((matches = decimalExp.Matches(sql)).Count > 0)
{
var exp = matches[0];
var col = "@CO" + i + "L";
object str = exp.Value.TrimEnd(']').Substring(@"Decimal\[".Length - 1);
sql = sql.Remove(exp.Index, exp.Value.Length);
sql = sql.Insert(exp.Index, col);
dicCols.TryAdd(col, new Tuple<object, SqlDbType>(str.ConvertValue<decimal?>(), SqlDbType.Decimal));
i++;
}
sql = sql.CleanValidSqlName(repository.DataBaseTypes);
DbCommand cmd = null;
try
{
switch (repository.DataBaseTypes)
{
case DataBaseTypes.Mssql:
cmd = tran != null ?
"System.Data.SqlClient.SqlCommand".GetObjectType("System.Data.SqlClient").CreateInstance(new object[] { sql, connection.DBConnection, tran }) as DbCommand :
"System.Data.SqlClient.SqlCommand".GetObjectType("System.Data.SqlClient").CreateInstance(new object[] { sql, connection.DBConnection }) as DbCommand;
break;
case DataBaseTypes.PostgreSql:
cmd = tran != null ?
"Npgsql.NpgsqlCommand".GetObjectType("Npgsql").CreateInstance(new object[] { sql, connection.DBConnection, tran }) as DbCommand :
"Npgsql.NpgsqlCommand".GetObjectType("Npgsql").CreateInstance(new object[] { sql, connection.DBConnection }) as DbCommand;
break;
case DataBaseTypes.Sqllight:
cmd = tran != null ?
"System.Data.SQLite.SQLiteCommand".GetObjectType("System.Data.SQLite").CreateInstance(new object[] { sql, connection.DBConnection, tran }) as DbCommand :
"System.Data.SQLite.SQLiteCommand".GetObjectType("System.Data.SQLite").CreateInstance(new object[] { sql, connection.DBConnection }) as DbCommand;
break;
}
}
catch (Exception e)
{
switch (repository.DataBaseTypes)
{
case DataBaseTypes.Mssql:
throw new EnreplacedyException($"Please make sure that nuget 'System.Data.SqlClient' is installed \n orginal exception: \n {e.Message}");
case DataBaseTypes.PostgreSql:
throw new EnreplacedyException($"Please make sure that nuget 'Npgsql' is installed \n orginal exception: \n {e.Message}");
case DataBaseTypes.Sqllight:
throw new EnreplacedyException($"Please make sure that nuget 'System.Data.SQLite' is installed \n orginal exception: \n {e.Message}");
}
}
var dbCommandExtended = new DbCommandExtended(cmd, repository);
foreach (var dic in dicCols)
{
dbCommandExtended.AddInnerParameter(dic.Key, dic.Value.Item1);
}
return dbCommandExtended;
}
19
View Source File : MKMAuth.cs
License : GNU Affero General Public License v3.0
Project Creator : alexander-pick
License : GNU Affero General Public License v3.0
Project Creator : alexander-pick
public string GetAuthorizationHeader(string method, string url)
{
var uri = new Uri(url);
var baseUri = uri.GetLeftPart(UriPartial.Path);
//MessageBox.Show(baseUri);
Dictionary<string, string> headerParams = new Dictionary<string, string>(configHeaderParams)
{
{ "realm", baseUri }
};
/// Start composing the base string from the method and request URI
var baseString = method.ToUpper()
+ "&"
+ Uri.EscapeDataString(baseUri)
+ "&";
var index = url.IndexOf("?");
if (index > 0)
{
var urlParams = url.Substring(index).Remove(0, 1);
var args = ParseQueryString(urlParams);
foreach (var k in args)
{
headerParams.Add(k.Key, k.Value);
}
}
/// Gather, encode, and sort the base string parameters
var encodedParams = new SortedDictionary<string, string>();
foreach (var parameter in headerParams)
{
if (false == parameter.Key.Equals("realm"))
{
encodedParams.Add(Uri.EscapeDataString(parameter.Key), Uri.EscapeDataString(parameter.Value));
}
}
/// Expand the base string by the encoded parameter=value pairs
var paramStrings = new List<string>();
foreach (var parameter in encodedParams)
{
paramStrings.Add(parameter.Key + "=" + parameter.Value);
}
var paramString = Uri.EscapeDataString(string.Join<string>("&", paramStrings));
baseString += paramString;
/// Create the OAuth signature
var signatureKey = Uri.EscapeDataString(appSecret) + "&" + Uri.EscapeDataString(accessSecret);
var hasher = HMAC.Create();
hasher.Key = Encoding.UTF8.GetBytes(signatureKey);
var rawSignature = hasher.ComputeHash(Encoding.UTF8.GetBytes(baseString));
var oAuthSignature = Convert.ToBase64String(rawSignature);
/// Include the OAuth signature parameter in the header parameters array
headerParams.Add("oauth_signature", oAuthSignature);
/// Construct the header string
var headerParamStrings = new List<string>();
foreach (var parameter in headerParams)
{
headerParamStrings.Add(parameter.Key + "=\"" + parameter.Value + "\"");
}
var authHeader = "OAuth " + string.Join<string>(", ", headerParamStrings);
return authHeader;
}
19
View Source File : TrackNodeTool.cs
License : GNU General Public License v3.0
Project Creator : AlexandreDoucet
License : GNU General Public License v3.0
Project Creator : AlexandreDoucet
public void FindTrackFiles()
{
saveLoad.dataPath = Application.dataPath;
availableTrackFiles.Clear();
string patern = "*." + saveLoad.extension;
string[] files = System.IO.Directory.GetFiles(saveLoad.dataPath, patern);
foreach (string item in files)
{
string x = item;
if (x.Contains(saveLoad.dataPath))
{
x = x.Replace(saveLoad.dataPath, "").Remove(0, 1);
x = x.Replace("."+saveLoad.extension, "");
}
availableTrackFiles.Add(x);
}
}
19
View Source File : NodeTextBox.cs
License : MIT License
Project Creator : AlexGyver
License : MIT License
Project Creator : AlexGyver
public override void Delete(Control control)
{
var textBox = control as TextBox;
int len = Math.Max(textBox.SelectionLength, 1);
if (textBox.SelectionStart < textBox.Text.Length)
{
int start = textBox.SelectionStart;
textBox.Text = textBox.Text.Remove(textBox.SelectionStart, len);
textBox.SelectionStart = start;
}
}
19
View Source File : NumericTextBox.cs
License : MIT License
Project Creator : AlexGyver
License : MIT License
Project Creator : AlexGyver
protected override void WndProc(ref Message m)
{
// Switch to handle message...
switch (m.Msg)
{
case WM_PASTE:
{
// Get clipboard object to paste
IDataObject clipboardData = Clipboard.GetDataObject();
// Get text from clipboard data
string pasteText = (string)clipboardData.GetData(
DataFormats.UnicodeText);
// Get the number of characters to replace
int selectionLength = SelectionLength;
// If no replacement or insertion, we are done
if (pasteText.Length == 0)
{
break;
}
else if (selectionLength != 0)
{
base.Text = base.Text.Remove(SelectionStart, selectionLength);
}
bool containsInvalidChars = false;
foreach (char c in pasteText)
{
if (containsInvalidChars)
{
break;
}
else if (invalidNumeric(c))
{
containsInvalidChars = true;
}
}
if (!containsInvalidChars)
{
base.Text = base.Text.Insert(SelectionStart, pasteText);
}
return;
}
}
base.WndProc(ref m);
}
19
View Source File : NegateNode.cs
License : MIT License
Project Creator : alexismorin
License : MIT License
Project Creator : alexismorin
public override string GenerateShaderForOutput( int outputId, ref MasterNodeDataCollector dataCollector, bool ignoreLocalvar )
{
string result = m_inputPorts[ 0 ].GeneratePortInstructions( ref dataCollector );
if ( result.StartsWith( "-" ) )
{
return result.Remove( 0, 1 );
}
else
{
return "-" + result;
}
}
19
View Source File : Utility.cs
License : MIT License
Project Creator : alexrainman
License : MIT License
Project Creator : alexrainman
public static void VerifyPins(string[] pins)
{
foreach (var pin in pins)
{
if (!pin.StartsWith("sha256/", StringComparison.Ordinal) && !pin.StartsWith("sha1/", StringComparison.Ordinal))
{
throw new HttpRequestException(FailureMessages.InvalidPublicKey);
}
try
{
byte[] bytes = Convert.FromBase64String(pin.Remove(0, pin.IndexOf('/') + 1));
}
catch (Exception ex)
{
throw new HttpRequestException(FailureMessages.InvalidPublicKey, ex);
}
}
}
See More Examples