Here are the examples of the csharp api string.IndexOf(string, int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
630 Examples
19
View Source File : RequestObject.cs
License : MIT License
Project Creator : 0ffffffffh
License : MIT License
Project Creator : 0ffffffffh
private void Parse(string data)
{
string key,value, tagEnd;
int beg=-1, end=0;
beg = data.IndexOf("<", beg+1);
while (beg != -1)
{
end = data.IndexOf(">", beg);
if (end == -1)
break;
beg++;
key = data.Substring(beg, end - beg);
tagEnd = string.Format("</{0}>", key);
beg = end + 1;
end = data.IndexOf(tagEnd, beg);
if (end == -1)
break;
value = data.Substring(beg, end - beg);
items.Add(key.ToLower(), NormalizeValue(value));
beg = data.IndexOf("<", end + 1);
}
}
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 : CelesteNetChatComponent.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public override void Update(GameTime gameTime) {
base.Update(gameTime);
_Time += Engine.RawDeltaTime;
_TimeSinceCursorMove += Engine.RawDeltaTime;
bool isRebinding = Engine.Scene == null ||
Engine.Scene.Enreplacedies.FindFirst<KeyboardConfigUI>() != null ||
Engine.Scene.Enreplacedies.FindFirst<ButtonConfigUI>() != null;
if (!(Engine.Scene?.Paused ?? true) || isRebinding) {
string typing = Typing;
Active = false;
Typing = typing;
}
if (!Active && !isRebinding && Settings.ButtonChat.Button.Pressed) {
Active = true;
} else if (Active) {
Engine.Commands.Open = false;
_ControlHeld = MInput.Keyboard.Check(Keys.LeftControl) || MInput.Keyboard.Check(Keys.RightControl);
if (!MInput.Keyboard.Check(Keys.Left) && !MInput.Keyboard.Check(Keys.Right)) {
_CursorMoveFast = false;
_TimeSinceCursorMove = 0;
}
// boolean to determine if Left or Right were already held on previous frame
bool _directionHeldLast = MInput.Keyboard.PreviousState[Keys.Left] == KeyState.Down
|| MInput.Keyboard.PreviousState[Keys.Right] == KeyState.Down;
bool _cursorCanMove = true;
// conditions for the cursor to be moving:
// 1. Don't apply delays on first frame Left/Right is pressed
if (_directionHeldLast) {
// 2. Delay time depends on whether this is the initial delay or subsequent "scrolling" left or right
_cursorCanMove = _TimeSinceCursorMove > (_CursorMoveFast ? _CursorMoveDelay : _CursorInitialMoveDelay);
}
if (MInput.Keyboard.Pressed(Keys.Enter)) {
if (!string.IsNullOrWhiteSpace(Typing))
Repeat.Insert(1, Typing);
Send(Typing);
Active = false;
} else if (MInput.Keyboard.Pressed(Keys.Down) && RepeatIndex > 0) {
RepeatIndex--;
} else if (MInput.Keyboard.Pressed(Keys.Up) && RepeatIndex < Repeat.Count - 1) {
RepeatIndex++;
} else if (MInput.Keyboard.Check(Keys.Left) && _cursorCanMove && CursorIndex > 0) {
if (_ControlHeld) {
// skip over space right before the cursor, if there is one
if (Typing[_CursorIndex - 1] == ' ')
CursorIndex--;
if (CursorIndex > 0) {
int prevWord = Typing.LastIndexOf(" ", _CursorIndex - 1);
CursorIndex = (prevWord < 0) ? 0 : prevWord + 1;
}
} else {
CursorIndex--;
}
_TimeSinceCursorMove = 0;
_CursorMoveFast = _directionHeldLast;
_Time = 0;
} else if (MInput.Keyboard.Check(Keys.Right) && _cursorCanMove && CursorIndex < Typing.Length) {
if (_ControlHeld) {
int nextWord = Typing.IndexOf(" ", _CursorIndex);
CursorIndex = (nextWord < 0) ? Typing.Length : nextWord + 1;
} else {
CursorIndex++;
}
_TimeSinceCursorMove = 0;
_CursorMoveFast = _directionHeldLast;
_Time = 0;
} else if (MInput.Keyboard.Pressed(Keys.Home)) {
CursorIndex = 0;
} else if (MInput.Keyboard.Pressed(Keys.End)) {
CursorIndex = Typing.Length;
} else if (Input.ESC.Pressed) {
Active = false;
}
}
// Prevent menus from reacting to player input after exiting chat.
if (_ConsumeInput > 0) {
Input.MenuConfirm.ConsumeBuffer();
Input.MenuConfirm.ConsumePress();
Input.ESC.ConsumeBuffer();
Input.ESC.ConsumePress();
Input.Pause.ConsumeBuffer();
Input.Pause.ConsumePress();
_ConsumeInput--;
}
}
19
View Source File : TextEditorForm.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
public void FindChars(string str, int index)
{
string cont = GetContent();
int start = cont.IndexOf(str, index);
if (start != index && start != -1)
{
index = start;
}
editor.SelectionStart = index;
editor.ScrollToCaret();
editor.Select(index, str.Length);
editor.Focus();
}
19
View Source File : YmlFormatUtil.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
public static YmlError ValidateYml(string content)
{
YmlError result = null;
string[] lines = content.Split('\n');
int index1 = -1, index2 = -1, lineIndex = 1, index = 0;
string startStr = null;
foreach (string line in lines)
{
if (!line.TrimStart().StartsWith("#"))
{
if (line.IndexOf(" ") != -1 && line.Substring(0, line.IndexOf(" ")).IndexOf("#") == -1)
{
result = new YmlError();
result.line = lineIndex;
result.index = content.IndexOf(" ", index);
result.msg = string.Format("第{0}行,位置{1}包含Tab符", lineIndex, line.IndexOf(" "));
break;
}
else if (!string.IsNullOrWhiteSpace(line))
{
index2 = line.IndexOf("#");
if (index2 > 0)
{
startStr = line.Substring(0, index2);
index1 = startStr.IndexOf(":");
if (index1 <= 0)
{
result = new YmlError();
result.line = lineIndex;
result.index = index;
result.msg = string.Format("第{0}行,格式不正确,缺少冒号", lineIndex);
break;
}
}
else
{
index1 = line.IndexOf(":");
if (index1 <= 0)
{
result = new YmlError();
result.line = lineIndex;
result.index = index;
result.msg = string.Format("第{0}行,格式不正确,缺少冒号", lineIndex);
break;
}
}
}
}
lineIndex++;
index += line.Length;
}
return result;
}
19
View Source File : TemplateEngin.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
private static string htmlSyntax(string tplcode, int num) {
while (num-- > 0) {
string[] arr = _reg_syntax.Split(tplcode);
if (arr.Length == 1) break;
for (int a = 1; a < arr.Length; a += 4) {
string tag = string.Concat('<', arr[a]);
string end = string.Concat("</", arr[a], '>');
int fc = 1;
for (int b = a; fc > 0 && b < arr.Length; b += 4) {
if (b > a && arr[a].ToLower() == arr[b].ToLower()) fc++;
int bpos = 0;
while (true) {
int fa = arr[b + 3].IndexOf(tag, bpos);
int fb = arr[b + 3].IndexOf(end, bpos);
if (b == a) {
var z = arr[b + 3].IndexOf("/>");
if ((fb == -1 || z < fb) && z != -1) {
var y = arr[b + 3].Substring(0, z + 2);
if (_reg_htmltag.IsMatch(y) == false)
fb = z - end.Length + 2;
}
}
if (fa == -1 && fb == -1) break;
if (fa != -1 && (fa < fb || fb == -1)) {
fc++;
bpos = fa + tag.Length;
continue;
}
if (fb != -1) fc--;
if (fc <= 0) {
var a1 = arr[a + 1];
var end3 = string.Concat("{/", a1, "}");
if (a1.ToLower() == "else") {
if (_reg_blank.Replace(arr[a - 4 + 3], "").EndsWith("{/if}", StringComparison.CurrentCultureIgnoreCase) == true) {
var idx = arr[a - 4 + 3].IndexOf("{/if}");
arr[a - 4 + 3] = string.Concat(arr[a - 4 + 3].Substring(0, idx), arr[a - 4 + 3].Substring(idx + 5));
//如果 @else="有条件内容",则变换成 elseif 条件内容
if (_reg_blank.Replace(arr[a + 2], "").Length > 0) a1 = "elseif";
end3 = "{/if}";
} else {
arr[a] = string.Concat("指令 @", arr[a + 1], "='", arr[a + 2], "' 没紧接着 if/else 指令之后,无效. <", arr[a]);
arr[a + 1] = arr[a + 2] = string.Empty;
}
}
if (arr[a + 1].Length > 0) {
if (_reg_blank.Replace(arr[a + 2], "").Length > 0 || a1.ToLower() == "else") {
arr[b + 3] = string.Concat(arr[b + 3].Substring(0, fb + end.Length), end3, arr[b + 3].Substring(fb + end.Length));
arr[a] = string.Concat("{", a1, " ", arr[a + 2], "}<", arr[a]);
arr[a + 1] = arr[a + 2] = string.Empty;
} else {
arr[a] = string.Concat('<', arr[a]);
arr[a + 1] = arr[a + 2] = string.Empty;
}
}
break;
}
bpos = fb + end.Length;
}
}
if (fc > 0) {
arr[a] = string.Concat("不严谨的html格式,请检查 ", arr[a], " 的结束标签, @", arr[a + 1], "='", arr[a + 2], "' 指令无效. <", arr[a]);
arr[a + 1] = arr[a + 2] = string.Empty;
}
}
if (arr.Length > 0) tplcode = string.Join(string.Empty, arr);
}
return tplcode;
}
19
View Source File : ConsoleApp.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public static (string info, string warn, string err) ShellRun(string cddir, params string[] bat) {
if (bat == null || bat.Any() == false) return ("", "", "");
if (string.IsNullOrEmpty(cddir)) cddir = Directory.GetCurrentDirectory();
var proc = new System.Diagnostics.Process();
proc.StartInfo = new System.Diagnostics.ProcessStartInfo {
CreateNoWindow = true,
FileName = "cmd.exe",
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardInput = true,
RedirectStandardOutput = true,
WorkingDirectory = cddir
};
proc.Start();
foreach (var cmd in bat)
proc.StandardInput.WriteLine(cmd);
proc.StandardInput.WriteLine("exit");
var outStr = proc.StandardOutput.ReadToEnd();
var errStr = proc.StandardError.ReadToEnd();
proc.Close();
var idx = outStr.IndexOf($">{bat[0]}");
if (idx != -1) {
idx = outStr.IndexOf("\n", idx);
if (idx != -1) outStr = outStr.Substring(idx + 1);
}
idx = outStr.LastIndexOf(">exit");
if (idx != -1) {
idx = outStr.LastIndexOf("\n", idx);
if (idx != -1) outStr = outStr.Remove(idx);
}
outStr = outStr.Trim();
if (outStr == "") outStr = null;
if (errStr == "") errStr = null;
return (outStr, string.IsNullOrEmpty(outStr) ? null : errStr, string.IsNullOrEmpty(outStr) ? errStr : null);
}
19
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, List<string>> ParseRuleFile(string ruleFilePath)
{
Dictionary<string, List<string>> res = new Dictionary<string, List<string>>();
var contents = new StringReader(File.ReadAllText(ruleFilePath));
string line = contents.ReadLine();
while (line != null)
{
try
{
//if the line contains a mitre_technique
if (line.Contains("mitre_technique_id "))
{
List<string> techniques = new List<string>();
//get all indexes from all technique ids and add them all to a list
IEnumerable<int> indexes = Regex.Matches(line, "mitre_technique_id ").Cast<Match>().Select(m => m.Index + "mitre_technique_id ".Length);
foreach (int index in indexes)
techniques.Add(line.Substring(index, line.IndexOfAny(new [] { ',', ';' }, index) - index));
int head = line.IndexOf("msg:\"") + "msg:\"".Length;
int tail = line.IndexOf("\"", head);
string msg = line.Substring(head, tail - head);
head = line.IndexOf("sid:") + "sid:".Length;
tail = line.IndexOfAny(new char[] { ',', ';' }, head);
string sid = line.Substring(head, tail - head);
//for each found technique add the sid along with the message to the content
foreach( string technique in techniques)
{
if (res.ContainsKey(technique))
res[technique].Add($"{sid} - {msg}");
else
res.Add(technique, new List<string> { $"{sid} - {msg}" });
}
}
line = contents.ReadLine();
}
catch (Exception e)
{
Console.WriteLine(line);
Console.WriteLine(e.Message);
line = contents.ReadLine();
}
}
return res;
}
19
View Source File : ChatUtils.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
public static List<string> SplitBySpace(string args)
{
int i = 0;
var argsM = new List<string>();
while (i + 1 < args.Length)
{
if (args[i] == '\'')
{
int endK = i;
bool exit;
do //запускаем поиск след кавычки снова, если после найденной ещё одна
{
exit = true;
endK = args.IndexOf('\'', endK + 1);
if (endK >= 0 && endK + 1 < args.Length && args[endK + 1] == '\'')
{
//это двойная кавычка - пропускаем её
endK++;
exit = false;
}
}
while (!exit);
if (endK >= 0)
{
argsM.Add(args.Substring(i + 1, endK - i - 1).Replace("''", "'"));
i = endK + 1;
continue;
}
}
var ni = args.IndexOf(" ", i);
if (ni >= 0)
{
//условие недобавления для двойного пробела
if (ni > i) argsM.Add(args.Substring(i, ni - i));
i = ni + 1;
continue;
}
else
{
break;
}
}
if (i < args.Length)
{
argsM.Add(args.Substring(i));
}
return argsM;
}
19
View Source File : GameXMLUtils.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
public static string GetByTag(string xml, string tagName, string afterText = null)
{
int after = string.IsNullOrEmpty(afterText) ? 0 : xml.IndexOf(afterText);
if (after < 0) after = 0;
var tagNameB = "<" + tagName + ">";
int pos = xml.IndexOf(tagNameB, after);
if (pos < 0) return null;
pos += tagNameB.Length;
var tagNameE = "</" + tagName + ">";
int posE = xml.IndexOf(tagNameE, pos);
if (posE < 0) return null;
return xml.Substring(pos, posE - pos);
}
19
View Source File : GameXMLUtils.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
public static string ReplaceByTag(string xml, string tagName, string newValue, string afterText = null)
{
int after = string.IsNullOrEmpty(afterText) ? 0 : xml.IndexOf(afterText);
if (after < 0) after = 0;
var tagNameB = "<" + tagName + ">";
int pos = xml.IndexOf(tagNameB, after);
if (pos < 0) return xml;
pos += tagNameB.Length;
var tagNameE = "</" + tagName + ">";
int posE = xml.IndexOf(tagNameE, pos);
if (posE < 0) return xml;
return xml.Substring(0, pos) + newValue + xml.Substring(posE);
}
19
View Source File : GameXMLUtils.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
public static string ReplaceByTag(string xml, string tagName
, Func<string, string> getNewValue)
{
var tagNameB = "<" + tagName + ">";
int pos = xml.IndexOf(tagNameB);
if (pos < 0) return xml;
pos += tagNameB.Length;
var tagNameE = "</" + tagName + ">";
int posE = xml.IndexOf(tagNameE, pos);
if (posE < 0) return xml;
var newValue = getNewValue(xml.Substring(pos, posE - pos));
if (newValue == null) return xml;
return xml.Substring(0, pos) + newValue + xml.Substring(posE);
}
19
View Source File : ChatController.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
public static string ServerCharTranslate(string textChat)
{
int pos = 0;
var clonSpace = textChat.Replace('\r', ' ').Replace('\n', ' ').Replace('\t', ' ').Replace(',', ' ').Replace('.', ' ') + " ";
while ((pos = textChat.IndexOf("OC_", pos)) >= 0)
{
var ep = clonSpace.IndexOf(" ", pos);
var sub = textChat.Substring(pos, ep - pos);
var tr = sub.Translate().ToString();
if (!tr.StartsWith("OC_"))
{
clonSpace = clonSpace.Replace(sub, tr);
textChat = textChat.Replace(sub, tr);
pos += tr.Length;
}
else
pos++;
}
return textChat;
}
19
View Source File : OVRGradleGeneration.cs
License : MIT License
Project Creator : absurd-joy
License : MIT License
Project Creator : absurd-joy
public void OnPostGenerateGradleAndroidProject(string path)
{
UnityEngine.Debug.Log("OVRGradleGeneration triggered.");
var targetOculusPlatform = new List<string>();
if (OVRDeviceSelector.isTargetDeviceQuest)
{
targetOculusPlatform.Add("quest");
}
OVRPlugin.AddCustomMetadata("target_oculus_platform", String.Join("_", targetOculusPlatform.ToArray()));
UnityEngine.Debug.LogFormat("Quest = {0}", OVRDeviceSelector.isTargetDeviceQuest);
#if UNITY_2019_3_OR_NEWER
string gradleBuildPath = Path.Combine(path, "../launcher/build.gradle");
#else
string gradleBuildPath = Path.Combine(path, "build.gradle");
#endif
bool v2SigningEnabled = true;
if (File.Exists(gradleBuildPath))
{
try
{
string gradle = File.ReadAllText(gradleBuildPath);
int v2Signingindex = gradle.IndexOf("v2SigningEnabled false");
if (v2Signingindex != -1)
{
//v2 Signing flag found, ensure the correct value is set based on platform.
if (v2SigningEnabled)
{
gradle = gradle.Replace("v2SigningEnabled false", "v2SigningEnabled true");
System.IO.File.WriteAllText(gradleBuildPath, gradle);
}
}
else
{
//v2 Signing flag missing, add it right after the key store preplacedword and set the value based on platform.
int keyPreplacedIndex = gradle.IndexOf("keyPreplacedword");
if (keyPreplacedIndex != -1)
{
int v2Index = gradle.IndexOf("\n", keyPreplacedIndex) + 1;
if(v2Index != -1)
{
gradle = gradle.Insert(v2Index, "v2SigningEnabled " + (v2SigningEnabled ? "true" : "false") + "\n");
System.IO.File.WriteAllText(gradleBuildPath, gradle);
}
}
}
}
catch (System.Exception e)
{
UnityEngine.Debug.LogWarningFormat("Unable to overwrite build.gradle, error {0}", e.Message);
}
}
else
{
UnityEngine.Debug.LogWarning("Unable to locate build.gradle");
}
PatchAndroidManifest(path);
}
19
View Source File : ActionCommand.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public static bool TryParseV2(string message, HashSet<string> registeredCommands, out ActionCommand command)
{
command = null;
if (string.IsNullOrEmpty(message))
{
return false;
}
try
{
// the message needs to start with the keyword after trim leading space.
message = message.TrimStart();
if (!message.StartsWith(_commandKey))
{
return false;
}
// Get the index of the separator between the command info and the data.
int endIndex = message.IndexOf(_commandKey, _commandKey.Length);
if (endIndex < 0)
{
return false;
}
// Get the command info (command and properties).
int cmdIndex = _commandKey.Length;
string cmdInfo = message.Substring(cmdIndex, endIndex - cmdIndex);
// Get the command name
int spaceIndex = cmdInfo.IndexOf(' ');
string commandName =
spaceIndex < 0
? cmdInfo
: cmdInfo.Substring(0, spaceIndex);
if (registeredCommands.Contains(commandName))
{
// Initialize the command.
command = new ActionCommand(commandName);
}
else
{
return false;
}
// Set the properties.
if (spaceIndex > 0)
{
string propertiesStr = cmdInfo.Substring(spaceIndex + 1).Trim();
string[] splitProperties = propertiesStr.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string propertyStr in splitProperties)
{
string[] pair = propertyStr.Split(new[] { '=' }, count: 2, options: StringSplitOptions.RemoveEmptyEntries);
if (pair.Length == 2)
{
command.Properties[pair[0]] = UnescapeProperty(pair[1]);
}
}
}
command.Data = UnescapeData(message.Substring(endIndex + _commandKey.Length));
return true;
}
catch
{
command = null;
return false;
}
}
19
View Source File : CustomClassificationTagger.cs
License : MIT License
Project Creator : Actipro
License : MIT License
Project Creator : Actipro
public override IEnumerable<TagSnapshotRange<IClreplacedificationTag>> GetTags(NormalizedTextSnapshotRangeCollection snapshotRanges, object parameter) {
// Loop through the requested snapshot ranges...
foreach (TextSnapshotRange snapshotRange in snapshotRanges) {
// If the snapshot range is not zero-length...
if (!snapshotRange.IsZeroLength) {
IEnumerable<TagSnapshotRange<ITokenTag>> tokenTagRanges = tokenTagAggregator.GetTags(snapshotRange);
if (tokenTagRanges != null) {
foreach (TagSnapshotRange<ITokenTag> tokenTagRange in tokenTagRanges) {
if (tokenTagRange.Tag.Token != null) {
switch (tokenTagRange.Tag.Token.Key) {
case "XmlCommentText": {
if (highlightDoreplacedentationComments) {
// Get the text of the token
string text = tokenTagRange.SnapshotRange.Text;
// Look for the text "Actipro"
int index = text.IndexOf("Actipro");
while (index != -1) {
// Add a highlighted range
yield return new TagSnapshotRange<IClreplacedificationTag>(
new TextSnapshotRange(snapshotRange.Snapshot, TextRange.FromSpan(tokenTagRange.SnapshotRange.StartOffset + index, 7)),
new ClreplacedificationTag(ClreplacedificationTypes.SyntaxError)
);
// Look for another match
index = text.IndexOf("Actipro", index + 7);
}
}
break;
}
case "Identifier": {
if (highlightIdentifiers) {
// Get the text of the token
string text = tokenTagRange.SnapshotRange.Text;
// If the text is "Actipro"...
if (text == "Actipro") {
// Add a highlighted range
yield return new TagSnapshotRange<IClreplacedificationTag>(
new TextSnapshotRange(snapshotRange.Snapshot, tokenTagRange.SnapshotRange.TextRange),
new ClreplacedificationTag(ClreplacedificationTypes.SyntaxError)
);
}
}
break;
}
}
}
}
}
}
}
}
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 : Shader.cs
License : The Unlicense
Project Creator : aeroson
License : The Unlicense
Project Creator : aeroson
int GetClosestShaderTypeTagPosition(string source, int offset, ref ShaderType shaderType)
{
int startOfTag = -1;
foreach (ShaderType type in System.Enum.GetValues(typeof(ShaderType)) )
{
string tag = "[" + type.ToString() + "]";
int thisStartOfTag = source.IndexOf(tag, offset);
if (thisStartOfTag != -1)
{
if(startOfTag == -1 || thisStartOfTag<startOfTag)
shaderType = type;
startOfTag = thisStartOfTag;
}
}
return startOfTag;
}
19
View Source File : IconVM.cs
License : MIT License
Project Creator : ahopper
License : MIT License
Project Creator : ahopper
private string GetXmlAttribute(string xml, string name)
{
int i = xml.IndexOf(name);
if (i > -1)
{
int start = xml.IndexOf("\"", i);
if (start > -1 && xml.Length > start + 1)
{
int end = xml.IndexOf("\"", start + 1);
if (end > -1)
{
return xml.Substring(start + 1, end - start - 1);
}
}
}
return "";
}
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 ExtractNextArgument(this string str, ref int startPos)
{
if (string.IsNullOrWhiteSpace(str))
return null;
var inBacktick = false;
var inTripleBacktick = false;
var inQuote = false;
var inEscape = false;
var removeIndices = new List<int>(str.Length - startPos);
var i = startPos;
for (; i < str.Length; i++)
if (!char.IsWhiteSpace(str[i]))
break;
startPos = i;
var endPosition = -1;
var startPosition = startPos;
for (i = startPosition; i < str.Length; i++)
{
if (char.IsWhiteSpace(str[i]) && !inQuote && !inTripleBacktick && !inBacktick && !inEscape)
endPosition = i;
if (str[i] == '\\' && str.Length > i + 1)
{
if (!inEscape && !inBacktick && !inTripleBacktick)
{
inEscape = true;
if (str.IndexOf("\\`", i) == i || str.IndexOf("\\\"", i) == i || str.IndexOf("\\\\", i) == i || (str.Length >= i && char.IsWhiteSpace(str[i + 1])))
removeIndices.Add(i - startPosition);
i++;
}
else if ((inBacktick || inTripleBacktick) && str.IndexOf("\\`", i) == i)
{
inEscape = true;
removeIndices.Add(i - startPosition);
i++;
}
}
if (str[i] == '`' && !inEscape)
{
var tripleBacktick = str.IndexOf("```", i) == i;
if (inTripleBacktick && tripleBacktick)
{
inTripleBacktick = false;
i += 2;
}
else if (!inBacktick && tripleBacktick)
{
inTripleBacktick = true;
i += 2;
}
if (inBacktick && !tripleBacktick)
inBacktick = false;
else if (!inTripleBacktick && tripleBacktick)
inBacktick = true;
}
if (str[i] == '"' && !inEscape && !inBacktick && !inTripleBacktick)
{
removeIndices.Add(i - startPosition);
inQuote = !inQuote;
}
if (inEscape)
inEscape = false;
if (endPosition != -1)
{
startPos = endPosition;
return startPosition != endPosition ? str.Substring(startPosition, endPosition - startPosition).CleanupString(removeIndices) : null;
}
}
startPos = str.Length;
return startPos != startPosition ? str.Substring(startPosition).CleanupString(removeIndices) : null;
}
19
View Source File : LogEntry.cs
License : Apache License 2.0
Project Creator : alaatm
License : Apache License 2.0
Project Creator : alaatm
List<TextSpan> ExtractSpans()
{
var spans = new List<TextSpan>();
var current = 0;
foreach (Match m in _propRegex.Matches(MessageTemplate))
{
var prop = m.Groups[0].Value;
var name = m.Groups[1].Value;
name = name.Contains(':') ? name.Substring(0, name.IndexOf(':')) : name;
var value = Properties.FirstOrDefault(p => p.Name == name)?.Value;
var startIdx = MessageTemplate.IndexOf(prop, current);
var endIdx = startIdx + prop.Length;
var section = MessageTemplate.Substring(current, startIdx - current);
spans.Add(new TextSpan
{
Text = section,
});
if (!string.IsNullOrEmpty(value))
{
var isNumber = double.TryParse(value, out var _);
spans.Add(new TextSpan
{
Kind = isNumber ? "num" : "str",
Text = value,
});
}
else
{
spans.Add(new TextSpan
{
Text = prop,
});
}
current = endIdx;
}
spans.Add(new TextSpan
{
Text = MessageTemplate.Substring(current),
});
var result = spans.Where(p => !string.IsNullOrEmpty(p.Text)).ToList();
return result;
}
19
View Source File : Common.cs
License : MIT License
Project Creator : AlaricGilbert
License : MIT License
Project Creator : AlaricGilbert
public static string GetSign(string url)
{
string result;
string str = url.Substring(url.IndexOf("?", 4) + 1);
List<string> list = str.Split('&').ToList();
list.Sort();
StringBuilder stringBuilder = new StringBuilder();
foreach (string str1 in list)
{
stringBuilder.Append((stringBuilder.Length > 0 ? "&" : string.Empty));
stringBuilder.Append(str1);
}
stringBuilder.Append(AppSecret);
result = MD5.GetMd5String(stringBuilder.ToString()).ToLower();
return result;
}
19
View Source File : TemplateData.cs
License : MIT License
Project Creator : alexismorin
License : MIT License
Project Creator : alexismorin
void FetchSubShaderProperties()
{
Match match = Regex.Match( m_templateBody, @"Preplaced\s*{" );
if( match.Groups.Count == 0 )
{
return;
}
int beginSubShader = m_templateBody.IndexOf( "SubShader" );
int endSubShader = match.Groups[ 0 ].Index;
if( beginSubShader > 0 && endSubShader > 0 && endSubShader > beginSubShader )
{
// ADD A PLACE TO INSERT GRAB PreplacedES
int preplacedIndex = m_templateBody.IndexOf( TemplatesManager.TemplatePreplacedTag );
if( preplacedIndex < 0 )
{
int currIdx = endSubShader - 1;
string identation = string.Empty;
for( ; currIdx > 0; currIdx-- )
{
if( m_templateBody[ currIdx ] != '\n' )
{
identation = m_templateBody[ currIdx ] + identation;
}
else
{
identation = m_templateBody[ currIdx ] + identation;
break;
}
}
if( currIdx > 0 )
{
m_templateBody = m_templateBody.Insert( currIdx, identation + TemplatesManager.TemplatePreplacedTag );
}
}
// GET ALL THE MODULES
string subBody = m_templateBody.Substring( beginSubShader, endSubShader - beginSubShader );
//CULL MODE
{
int cullIdx = subBody.IndexOf( "Cull" );
if( cullIdx > 0 )
{
int end = subBody.IndexOf( TemplatesManager.TemplateNewLine, cullIdx );
string cullParams = subBody.Substring( cullIdx, end - cullIdx );
m_cullModeData.CullModeId = cullParams;
TemplateHelperFunctions.CreateCullMode( cullParams, ref m_cullModeData );
if( m_cullModeData.DataCheck == TemplateDataCheck.Valid )
AddId( cullParams, false, string.Empty );
}
}
//COLOR MASK
{
int colorMaskIdx = subBody.IndexOf( "ColorMask" );
if( colorMaskIdx > 0 )
{
int end = subBody.IndexOf( TemplatesManager.TemplateNewLine, colorMaskIdx );
string colorMaskParams = subBody.Substring( colorMaskIdx, end - colorMaskIdx );
m_colorMaskData.ColorMaskId = colorMaskParams;
TemplateHelperFunctions.CreateColorMask( colorMaskParams, ref m_colorMaskData );
if( m_colorMaskData.DataCheck == TemplateDataCheck.Valid )
AddId( colorMaskParams, false );
}
}
//BlEND MODE
{
int blendModeIdx = subBody.IndexOf( "Blend" );
if( blendModeIdx > 0 )
{
int end = subBody.IndexOf( TemplatesManager.TemplateNewLine, blendModeIdx );
string blendParams = subBody.Substring( blendModeIdx, end - blendModeIdx );
m_blendData.BlendModeId = blendParams;
TemplateHelperFunctions.CreateBlendMode( blendParams, ref m_blendData );
if( m_blendData.ValidBlendMode )
{
AddId( blendParams, false );
}
}
}
//BLEND OP
{
int blendOpIdx = subBody.IndexOf( "BlendOp" );
if( blendOpIdx > 0 )
{
int end = subBody.IndexOf( TemplatesManager.TemplateNewLine, blendOpIdx );
string blendOpParams = subBody.Substring( blendOpIdx, end - blendOpIdx );
BlendData.BlendOpId = blendOpParams;
TemplateHelperFunctions.CreateBlendOp( blendOpParams, ref m_blendData );
if( m_blendData.ValidBlendOp )
{
AddId( blendOpParams, false );
}
}
m_blendData.DataCheck = ( m_blendData.ValidBlendMode || m_blendData.ValidBlendOp ) ? TemplateDataCheck.Valid : TemplateDataCheck.Invalid;
}
//STENCIL
{
int stencilIdx = subBody.IndexOf( "Stencil" );
if( stencilIdx > -1 )
{
int stencilEndIdx = subBody.IndexOf( "}", stencilIdx );
if( stencilEndIdx > 0 )
{
string stencilParams = subBody.Substring( stencilIdx, stencilEndIdx + 1 - stencilIdx );
m_stencilData.StencilBufferId = stencilParams;
TemplateHelperFunctions.CreateStencilOps( stencilParams, ref m_stencilData );
if( m_stencilData.DataCheck == TemplateDataCheck.Valid )
{
AddId( stencilParams, true );
}
}
}
}
//ZWRITE
{
int zWriteOpIdx = subBody.IndexOf( "ZWrite" );
if( zWriteOpIdx > -1 )
{
int zWriteEndIdx = subBody.IndexOf( TemplatesManager.TemplateNewLine, zWriteOpIdx );
if( zWriteEndIdx > 0 )
{
m_depthData.ZWriteModeId = subBody.Substring( zWriteOpIdx, zWriteEndIdx + 1 - zWriteOpIdx );
TemplateHelperFunctions.CreateZWriteMode( m_depthData.ZWriteModeId, ref m_depthData );
if( m_depthData.DataCheck == TemplateDataCheck.Valid )
{
AddId( m_depthData.ZWriteModeId, true );
}
}
}
}
//ZTEST
{
int zTestOpIdx = subBody.IndexOf( "ZTest" );
if( zTestOpIdx > -1 )
{
int zTestEndIdx = subBody.IndexOf( TemplatesManager.TemplateNewLine, zTestOpIdx );
if( zTestEndIdx > 0 )
{
m_depthData.ZTestModeId = subBody.Substring( zTestOpIdx, zTestEndIdx + 1 - zTestOpIdx );
TemplateHelperFunctions.CreateZTestMode( m_depthData.ZTestModeId, ref m_depthData );
if( m_depthData.DataCheck == TemplateDataCheck.Valid )
{
AddId( m_depthData.ZTestModeId, true );
}
}
}
}
//ZOFFSET
{
int zOffsetIdx = subBody.IndexOf( "Offset" );
if( zOffsetIdx > -1 )
{
int zOffsetEndIdx = subBody.IndexOf( TemplatesManager.TemplateNewLine, zOffsetIdx );
if( zOffsetEndIdx > 0 )
{
m_depthData.OffsetId = subBody.Substring( zOffsetIdx, zOffsetEndIdx + 1 - zOffsetIdx );
TemplateHelperFunctions.CreateZOffsetMode( m_depthData.OffsetId, ref m_depthData );
if( m_depthData.DataCheck == TemplateDataCheck.Valid )
{
AddId( m_depthData.OffsetId, true );
}
}
}
m_depthData.SetDataCheck();
}
//TAGS
{
int tagsIdx = subBody.IndexOf( "Tags" );
if( tagsIdx > -1 )
{
int tagsEndIdx = subBody.IndexOf( "}", tagsIdx );
if( tagsEndIdx > -1 )
{
m_tagData.Reset();
m_tagData.TagsId = subBody.Substring( tagsIdx, tagsEndIdx + 1 - tagsIdx );
TemplateHelperFunctions.CreateTags( ref m_tagData, true );
m_tagData.DataCheck = TemplateDataCheck.Valid;
AddId( m_tagData.TagsId, false );
}
else
{
m_tagData.DataCheck = TemplateDataCheck.Invalid;
}
}
else
{
m_tagData.DataCheck = TemplateDataCheck.Invalid;
}
}
}
}
19
View Source File : TemplateData.cs
License : GNU General Public License v3.0
Project Creator : alexismorin
License : GNU General Public License v3.0
Project Creator : alexismorin
void FetchSubShaderProperties()
{
Match match = Regex.Match( m_templateBody, @"Preplaced\s*{" );
if( match.Groups.Count == 0 )
{
return;
}
int beginSubShader = m_templateBody.IndexOf( "SubShader" );
int endSubShader = match.Groups[ 0 ].Index;
if( beginSubShader > 0 && endSubShader > 0 && endSubShader > beginSubShader )
{
// ADD A PLACE TO INSERT GRAB PreplacedES
int preplacedIndex = m_templateBody.IndexOf( TemplatesManager.TemplatePreplacedTag );
if( preplacedIndex < 0 )
{
int currIdx = endSubShader - 1;
string identation = string.Empty;
for( ; currIdx > 0; currIdx-- )
{
if( m_templateBody[ currIdx ] != '\n' )
{
identation = m_templateBody[ currIdx ] + identation;
}
else
{
identation = m_templateBody[ currIdx ] + identation;
break;
}
}
if( currIdx > 0 )
{
m_templateBody = m_templateBody.Insert( currIdx, identation + TemplatesManager.TemplatePreplacedTag );
}
}
// GET ALL THE MODULES
string subBody = m_templateBody.Substring( beginSubShader, endSubShader - beginSubShader );
//CULL MODE
{
int cullIdx = subBody.IndexOf( "Cull" );
if( cullIdx > 0 )
{
int end = subBody.IndexOf( TemplatesManager.TemplateNewLine, cullIdx );
string cullParams = subBody.Substring( cullIdx, end - cullIdx );
m_cullModeData.CullModeId = cullParams;
TemplateHelperFunctions.CreateCullMode( cullParams, ref m_cullModeData );
if( m_cullModeData.DataCheck == TemplateDataCheck.Valid )
AddId( cullParams, false, string.Empty );
}
}
//COLOR MASK
{
int colorMaskIdx = subBody.IndexOf( "ColorMask" );
if( colorMaskIdx > 0 )
{
int end = subBody.IndexOf( TemplatesManager.TemplateNewLine, colorMaskIdx );
string colorMaskParams = subBody.Substring( colorMaskIdx, end - colorMaskIdx );
m_colorMaskData.ColorMaskId = colorMaskParams;
TemplateHelperFunctions.CreateColorMask( colorMaskParams, ref m_colorMaskData );
if( m_colorMaskData.DataCheck == TemplateDataCheck.Valid )
AddId( colorMaskParams, false );
}
}
//BlEND MODE
{
int blendModeIdx = subBody.IndexOf( "Blend" );
if( blendModeIdx > 0 )
{
int end = subBody.IndexOf( TemplatesManager.TemplateNewLine, blendModeIdx );
string blendParams = subBody.Substring( blendModeIdx, end - blendModeIdx );
m_blendData.BlendModeId = blendParams;
TemplateHelperFunctions.CreateBlendMode( blendParams, ref m_blendData );
if( m_blendData.ValidBlendMode )
{
AddId( blendParams, false );
}
}
}
//BLEND OP
{
int blendOpIdx = subBody.IndexOf( "BlendOp" );
if( blendOpIdx > 0 )
{
int end = subBody.IndexOf( TemplatesManager.TemplateNewLine, blendOpIdx );
string blendOpParams = subBody.Substring( blendOpIdx, end - blendOpIdx );
BlendData.BlendOpId = blendOpParams;
TemplateHelperFunctions.CreateBlendOp( blendOpParams, ref m_blendData );
if( m_blendData.ValidBlendOp )
{
AddId( blendOpParams, false );
}
}
m_blendData.DataCheck = ( m_blendData.ValidBlendMode || m_blendData.ValidBlendOp ) ? TemplateDataCheck.Valid : TemplateDataCheck.Invalid;
}
//STENCIL
{
int stencilIdx = subBody.IndexOf( "Stencil" );
if( stencilIdx > -1 )
{
int stencilEndIdx = subBody.IndexOf( "}", stencilIdx );
if( stencilEndIdx > 0 )
{
string stencilParams = subBody.Substring( stencilIdx, stencilEndIdx + 1 - stencilIdx );
m_stencilData.StencilBufferId = stencilParams;
TemplateHelperFunctions.CreateStencilOps( stencilParams, ref m_stencilData );
if( m_stencilData.DataCheck == TemplateDataCheck.Valid )
{
AddId( stencilParams, true );
}
}
}
}
//ZWRITE
{
int zWriteOpIdx = subBody.IndexOf( "ZWrite" );
if( zWriteOpIdx > -1 )
{
int zWriteEndIdx = subBody.IndexOf( TemplatesManager.TemplateNewLine, zWriteOpIdx );
if( zWriteEndIdx > 0 )
{
m_depthData.ZWriteModeId = subBody.Substring( zWriteOpIdx, zWriteEndIdx + 1 - zWriteOpIdx );
TemplateHelperFunctions.CreateZWriteMode( m_depthData.ZWriteModeId, ref m_depthData );
if( m_depthData.DataCheck == TemplateDataCheck.Valid )
{
AddId( m_depthData.ZWriteModeId, true );
}
}
}
}
//ZTEST
{
int zTestOpIdx = subBody.IndexOf( "ZTest" );
if( zTestOpIdx > -1 )
{
int zTestEndIdx = subBody.IndexOf( TemplatesManager.TemplateNewLine, zTestOpIdx );
if( zTestEndIdx > 0 )
{
m_depthData.ZTestModeId = subBody.Substring( zTestOpIdx, zTestEndIdx + 1 - zTestOpIdx );
TemplateHelperFunctions.CreateZTestMode( m_depthData.ZTestModeId, ref m_depthData );
if( m_depthData.DataCheck == TemplateDataCheck.Valid )
{
AddId( m_depthData.ZTestModeId, true );
}
}
}
}
//ZOFFSET
{
int zOffsetIdx = subBody.IndexOf( "Offset" );
if( zOffsetIdx > -1 )
{
int zOffsetEndIdx = subBody.IndexOf( TemplatesManager.TemplateNewLine, zOffsetIdx );
if( zOffsetEndIdx > 0 )
{
m_depthData.OffsetId = subBody.Substring( zOffsetIdx, zOffsetEndIdx + 1 - zOffsetIdx );
TemplateHelperFunctions.CreateZOffsetMode( m_depthData.OffsetId, ref m_depthData );
if( m_depthData.DataCheck == TemplateDataCheck.Valid )
{
AddId( m_depthData.OffsetId, true );
}
}
}
}
//TAGS
{
int tagsIdx = subBody.IndexOf( "Tags" );
if( tagsIdx > -1 )
{
int tagsEndIdx = subBody.IndexOf( "}", tagsIdx );
if( tagsEndIdx > -1 )
{
m_tagData.Reset();
m_tagData.TagsId = subBody.Substring( tagsIdx, tagsEndIdx + 1 - tagsIdx );
TemplateHelperFunctions.CreateTags( ref m_tagData, true );
m_tagData.DataCheck = TemplateDataCheck.Valid;
AddId( m_tagData.TagsId, false );
}
else
{
m_tagData.DataCheck = TemplateDataCheck.Invalid;
}
}
else
{
m_tagData.DataCheck = TemplateDataCheck.Invalid;
}
}
}
}
19
View Source File : SmallFunctions.cs
License : MIT License
Project Creator : Alkl58
License : MIT License
Project Creator : Alkl58
public static string GetBetween(string strSource, string strStart, string strEnd)
{
// This function parses data between two points
if (strSource.Contains(strStart) && strSource.Contains(strEnd))
{
int Start, End;
Start = strSource.IndexOf(strStart, 0) + strStart.Length;
End = strSource.IndexOf(strEnd, Start);
return strSource.Substring(Start, End - Start);
}
return "";
}
19
View Source File : DumpCreator.cs
License : GNU Lesser General Public License v3.0
Project Creator : Alois-xx
License : GNU Lesser General Public License v3.0
Project Creator : Alois-xx
internal string GetDumpFileName(string line)
{
string lret = null;
if (line.Contains(".dmp"))
{
lret = line.Substring(line.IndexOf(" ", line.IndexOf("initiated:") + 1) + 1);
}
return lret;
}
19
View Source File : GiteaAPIWrapper.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
private string GetStringFromHtmlContent(string htmlContent, string inputSearchTextBefore, string inputSearchTextAfter)
{
int start = htmlContent.IndexOf(inputSearchTextBefore);
// Add the lengt of the search string to find the start place for form vlaue
start += inputSearchTextBefore.Length;
// Find the end of the input value content in html (input element with " as end)
int stop = htmlContent.IndexOf(inputSearchTextAfter, start);
if (start > 0 && stop > 0 && stop > start)
{
string formValue = htmlContent.Substring(start, stop - start);
return formValue;
}
return null;
}
19
View Source File : Utilities.cs
License : Apache License 2.0
Project Creator : AmpScm
License : Apache License 2.0
Project Creator : AmpScm
public static string ReplaceNoCase(string strText, string strOldValue, string strNewValue)
{
string strLowerText = strText.ToLower();
string strLowerOldValue = strOldValue.ToLower();
int iCurrentIndex = strLowerText.IndexOf(strLowerOldValue);
if (iCurrentIndex < 0)
{
return strText;
}
int iTextLength = strText.Length;
int iOldValueLength = strOldValue.Length;
int iPreviousIndex = 0;
StringBuilder SB = new StringBuilder(strText.Length);
while (iCurrentIndex >= 0)
{
if (iCurrentIndex > iPreviousIndex)
{
SB.Append(strText.Substring(iPreviousIndex, iCurrentIndex - iPreviousIndex));
}
SB.Append(strNewValue);
iCurrentIndex += iOldValueLength;
iPreviousIndex = iCurrentIndex;
if ((iCurrentIndex + 1) < iTextLength)
{
iCurrentIndex = strLowerText.IndexOf(strLowerOldValue, iCurrentIndex + 1);
}
else
{
break;
}
}
if (iPreviousIndex < strText.Length)
{
SB.Append(strText.Substring(iPreviousIndex));
}
string strResult = SB.ToString();
return strResult;
}
19
View Source File : NgItemWizard.cs
License : MIT License
Project Creator : andfomin
License : MIT License
Project Creator : andfomin
private int FindEndOfMethod(string text, int startPos)
{
var stack = new Stack<int>();
var firstOpening = text.IndexOf(OpeningBrace, startPos);
stack.Push(firstOpening);
var current = firstOpening;
while (stack.Count > 0)
{
var nextOpening = text.IndexOf(OpeningBrace, current + 1);
var nextClosing = text.IndexOf(ClosingBrace, current + 1);
if ((nextOpening > 0) && (nextOpening < nextClosing))
{
stack.Push(nextOpening);
current = nextOpening;
}
else
{
stack.Pop();
current = nextClosing;
}
var stackCount = stack.Count();
}
return current;
}
19
View Source File : NgItemWizard.cs
License : MIT License
Project Creator : andfomin
License : MIT License
Project Creator : andfomin
private bool ModifyStartupCsFile(string projectDirectory)
{
var filePath = Path.Combine(projectDirectory, NgWizardHelper.StartupCsFileName);
if (!File.Exists(filePath))
{
return false;
}
var codeLines = File.ReadAllLines(filePath);
var methodHeaderLine = codeLines
.Where(i => i.Contains("public void") && i.Contains("Configure") && i.Contains("IApplicationBuilder") && i.Contains("IHostingEnvironment"))
.FirstOrDefault()
;
if (String.IsNullOrEmpty(methodHeaderLine))
{
return false;
}
var appPattern = @"(?:IApplicationBuilder)\s+(\w+(?=\)|,|\s))";
var appVariableName = FindMatch(methodHeaderLine, appPattern);
var envPattern = @"(?:IHostingEnvironment)\s+(\w+(?=\)|,|\s))";
var envVariableName = FindMatch(methodHeaderLine, envPattern);
if (String.IsNullOrEmpty(appVariableName) || String.IsNullOrEmpty(envVariableName))
{
return false;
}
var codeText = File.ReadAllText(filePath);
var methodStartPos = codeText.IndexOf(methodHeaderLine);
// MVC and WebAPI projects already have UseStaticFiles() inserted by their templates.
var useStaticFilesPos = codeText.IndexOf($"{appVariableName}.UseStaticFiles", methodStartPos);
var useFileServerPos = codeText.IndexOf($"{appVariableName}.UseFileServer", methodStartPos);
var insertUseStaticFiles = (useStaticFilesPos == -1) && (useFileServerPos == -1);
/* The position of the snippet affects the routing in the project. Middleware handlers are called in the order of registration.
* We serve at "/" in Empty and WebAPI, at "/ng/" in MVC and Razor Pages.
* WebAPI, MVC and Razor Pages have routing, we serve everything else (including 404 at dev time).
* We hijack processing in the Empty project (it has a hardcoded response in app.Run()).
*/
int insertPos = codeText.IndexOf($"{appVariableName}.Run(", methodStartPos);
if (insertPos == -1)
{
insertPos = FindEndOfMethod(codeText, methodStartPos);
}
if (insertPos > 0)
{
insertPos = RewindWhitespaces(codeText, insertPos);
var ngSnippet = LineBreak +
"#region /* Added by the Angular CLI template. --- BEGIN --- */" + LineBreak +
$"if ({envVariableName}.IsDevelopment())" + LineBreak +
"{" + LineBreak +
$"{appVariableName}.UseWebSockets().UseNgProxy();" + LineBreak +
"}" + LineBreak +
"else" + LineBreak +
"{" + LineBreak;
if (insertUseStaticFiles)
{
ngSnippet = ngSnippet +
$"{appVariableName}.UseStaticFiles();" + LineBreak;
}
ngSnippet = ngSnippet +
$"{appVariableName}.UseNgRoute();" + LineBreak +
"}" + LineBreak +
"#endregion /* Added by the Angular CLI template. --- END --- */" + LineBreak + LineBreak;
codeText = codeText.Insert(insertPos, ngSnippet);
File.WriteAllText(filePath, codeText);
return true;
}
return false;
}
19
View Source File : CharacterFinder.cs
License : MIT License
Project Creator : AngryCarrot789
License : MIT License
Project Creator : AngryCarrot789
public static int CustomIndexOf(this string text, string value, int startIndex, bool matchWholeWord)
{
if (matchWholeWord)
{
for (int i = startIndex; i < text.Length && (i = text.IndexOf(value, i)) >= 0; i++)
{
if ((i == 0 || !char.IsLetterOrDigit(text, i - 1)) && (i + value.Length == text.Length || !char.IsLetterOrDigit(text, i + value.Length)))
return i;
}
return -1;
}
else
{
return text.IndexOf(value, startIndex);
}
}
19
View Source File : TokenizerBase.cs
License : Apache License 2.0
Project Creator : AnkiUniversal
License : Apache License 2.0
Project Creator : AnkiUniversal
private List<int> GetSplitPositions(string text)
{
var splitPositions = new List<int>();
int position;
int currentPosition = 0;
while (true)
{
int indexOfMaru = text.IndexOf("。", currentPosition);
int indexOfTen = text.IndexOf("、", currentPosition);
if (indexOfMaru < 0 || indexOfTen < 0)
{
position = Math.Max(indexOfMaru, indexOfTen);
}
else
{
position = Math.Min(indexOfMaru, indexOfTen);
}
if (position >= 0)
{
splitPositions.Add(position);
currentPosition = position + 1;
}
else
{
break;
}
}
return splitPositions;
}
19
View Source File : Configuration.cs
License : GNU General Public License v3.0
Project Creator : anotak
License : GNU General Public License v3.0
Project Creator : anotak
private void InputStructure(IDictionary cs, ref string file, ref string data, ref int pos, ref int line)
{
//string key = "";
StringBuilder keyBuilder = new StringBuilder(64);
// Go through all of the data until
// the end or until the struct closes
// or when an arror occurred
while ((pos < data.Length) && !cpErrorResult)
{
// Get current character
char c = data[pos++];
// Check what character this is
switch (c)
{
case '{': // Begin of new struct
{
// Validate key
string key = keyBuilder.ToString().Trim();
if (ValidateKey(cs, key, file, line))
{
// Parse this struct and add it
IDictionary cs2;
if (cs is ListDictionary) cs2 = new ListDictionary(); else cs2 = new Hashtable();
InputStructure(cs2, ref file, ref data, ref pos, ref line);
if (cs.Contains(key) && (cs[key] is IDictionary))
cs[key] = Combine((IDictionary)cs[key], cs2, (cs is ListDictionary));
else
cs[key] = cs2;
keyBuilder.Length = 0;
}
}
break;
case '}': // End of this struct
// Stop parsing in this struct
return;
case '(': // Function
{
string key = keyBuilder.ToString();
ParseFunction(cs, ref file, ref data, ref pos, ref line, ref key);
keyBuilder.Length = 0;
}
break;
case '=': // replacedignment
// Validate key
{
string key = keyBuilder.ToString().Trim();
if (ValidateKey(cs, key, file, line))
{
// Now parsing replacedignment
object val = Parsereplacedignment(ref file, ref data, ref pos, ref line);
if (!cpErrorResult)
{
cs[key] = val;
keyBuilder.Length = 0;
}
}
}
break;
case ';': // Terminator
// Validate key
if(keyBuilder.Length > 0)
{
string key = keyBuilder.ToString().Trim();
if (ValidateKey(cs, key, file, line))
{
// Add the key with null as value
cs[key] = null;
keyBuilder.Length = 0;
}
}
break;
case '\n': // New line
// Count the line
line++;
// Add this to the key as a space.
// Spaces are not allowed, but it will be trimmed
// when its the first or last character.
keyBuilder.Append(" ");
break;
case '\\': // Possible comment
case '/':
// Backtrack to use previous character also
pos--;
// Check for the line comment //
if(data.Substring(pos, 2) == "//")
{
// Find the next line
int np = data.IndexOf("\n", pos);
// Next line found?
if(np > -1)
{
// Count the line
line++;
// Skip everything on this line
pos = np + 1;
}
else
{
// No end of line
// Skip everything else
pos = data.Length + 1;
}
}
// Check for the block comment /* */
else if(data.Substring(pos, 2) == "/*")
{
// Find the next closing block comment
int np = data.IndexOf("*/", pos);
// Closing block comment found?
if(np > -1)
{
// Count the lines in the block comment
string blockdata = data.Substring(pos, np - pos + 2);
line += (blockdata.Split("\n".ToCharArray()).Length - 1);
// Skip everything in this block
pos = np + 2;
}
else
{
// No end of line
// Skip everything else
pos = data.Length + 1;
}
}
else
{
// No whitespace
pos++;
}
break;
case '\t':
case '\r':
break;
default: // Everything else
// Add character to key
keyBuilder.Append(c.ToString(CultureInfo.InvariantCulture));
break;
}
}
}
19
View Source File : UniversalParser.cs
License : GNU General Public License v3.0
Project Creator : anotak
License : GNU General Public License v3.0
Project Creator : anotak
private UniversalCollection InputStructure(ref string data, ref int pos, ref int line)
{
char c = '\0'; // current data character
int pm = PM_NOTHING; // current parse mode
//string key = "", val = ""; // current key and value beign built
bool escape = false; // escape sequence?
bool endofstruct = false; // true as soon as this level struct ends
UniversalCollection cs = new UniversalCollection();
StringBuilder keysb = new StringBuilder(32);
StringBuilder valsb = new StringBuilder(32);
// Go through all of the data until
// the end or until the struct closes
// or when an arror occurred
while ((pos < data.Length) && (cpErrorResult == 0) && (endofstruct == false))
{
// Get current character
c = data[pos];
// ================ What parse mode are we at?
if(pm == PM_NOTHING)
{
// Now check what character this is
switch(c)
{
case '{': // Begin of new struct
// Validate key
{
string key = keysb.ToString().Trim();
if (ValidateKey(key, line))
{
// Next character
pos++;
// Parse this struct and add it
cs.Add(new UniversalEntry(key, InputStructure(ref data, ref pos, ref line)));
// Check the last character
pos--;
// Reset the key
keysb.Length = 0;
}
}
// Leave switch
break;
case '}': // End of this struct
// Stop parsing in this struct
endofstruct = true;
// Leave the loop
break;
case '=': // replacedignment
// Validate key
if(ValidateKey(keysb.ToString().Trim(), line))
{
// Now parsing replacedignment
pm = PM_replacedIGNMENT;
}
// Leave switch
break;
case ';': // Terminator
// Validate key
if(ValidateKey(keysb.ToString().Trim(), line))
{
// Error: No value
RaiseError(line, ERROR_KEYWITHOUTVALUE);
}
// Leave switch
break;
case '\n': // New line
// Count the line
line++;
// Add this to the key as a space.
// Spaces are not allowed, but it will be trimmed
// when its the first or last character.
keysb.Append(' ');
// Leave switch
break;
case '\\': // Possible comment
case '/':
// Check for the line comment //
if(data.Substring(pos, 2) == "//")
{
// Find the next line
int np = data.IndexOf("\n", pos);
// Next line found?
if(np > -1)
{
// Count the line
line++;
// Skip everything on this line
pos = np;
}
else
{
// No end of line
// Skip everything else
pos = data.Length;
}
}
// Check for the block comment /* */
else if(data.Substring(pos, 2) == "/*")
{
// Find the next closing block comment
int np = data.IndexOf("*/", pos);
// Closing block comment found?
if(np > -1)
{
// Count the lines in the block comment
string blockdata = data.Substring(pos, np - pos + 2);
line += (blockdata.Split("\n".ToCharArray()).Length - 1);
// Skip everything in this block
pos = np + 1;
}
else
{
// No end of line
// Skip everything else
pos = data.Length;
}
}
// Leave switch
break;
default: // Everything else
// Add character to key
keysb.Append(char.ToLowerInvariant(c));
// Leave switch
break;
}
}
// ================ Parsing an replacedignment
else if(pm == PM_replacedIGNMENT)
{
// Check for string opening
if(c == '\"')
{
// Now parsing string
pm = PM_STRING;
}
// Check for numeric character
//else if("0123456789-.&".IndexOf(c.ToString(CultureInfo.InvariantCulture)) > -1)
else if ((c >= '0' && c <= '9') || c == '&' || c == '-' || c == '.')
{
// Now parsing number
pm = PM_NUMBER;
// Go one byte back, because this
// byte is part of the number!
pos--;
}
// Check for new line
else if(c == '\n')
{
// Count the new line
line++;
}
// Check if replacedignment ends
else if(c == ';')
{
// End of replacedignment
pm = PM_NOTHING;
// Remove this if it causes problems
keysb.Length = 0;
valsb.Length = 0;
}
// Otherwise (if not whitespace) it will be a keyword
else if((c != ' ') && (c != '\t'))
{
// Now parsing a keyword
pm = PM_KEYWORD;
// Go one byte back, because this
// byte is part of the keyword!
pos--;
}
}
// ================ Parsing a number
else if(pm == PM_NUMBER)
{
// Check if number ends here
if(c == ';')
{
string val = valsb.ToString().Trim();
string key = keysb.ToString().Trim();
// Hexadecimal?
if ((val.Length > 2) && val.StartsWith("0x", StringComparison.InvariantCultureIgnoreCase))
{
int ival = 0;
long lval = 0;
// Convert to int
try
{
// Convert to value
ival = System.Convert.ToInt32(val.Substring(2), 16);
// Add it to struct
cs.Add(new UniversalEntry(key, ival));
}
catch(System.OverflowException)
{
// Too large for Int32, try Int64
try
{
// Convert to value
lval = System.Convert.ToInt64(val.Substring(2), 16);
// Add it to struct
cs.Add(new UniversalEntry(key, lval));
}
catch(System.OverflowException)
{
// Too large for Int64, return error
RaiseError(line, ERROR_VALUETOOBIG);
}
catch(System.FormatException)
{
// ERROR: Invalid value in replacedignment
RaiseError(line, ERROR_VALUEINVALID);
}
}
catch(System.FormatException)
{
// ERROR: Invalid value in replacedignment
RaiseError(line, ERROR_VALUEINVALID);
}
}
// Floating point?
else if(val.IndexOf(".") > -1)
{
float fval = 0;
// Convert to float (remove the f first)
try { fval = System.Convert.ToSingle(val, CultureInfo.InvariantCulture); }
catch(System.FormatException)
{
// ERROR: Invalid value in replacedignment
RaiseError(line, ERROR_VALUEINVALID);
}
// Add it to struct
cs.Add(new UniversalEntry(key, fval));
}
else
{
int ival = 0;
long lval = 0;
// Convert to int
try
{
// Convert to value
ival = System.Convert.ToInt32(val, CultureInfo.InvariantCulture);
// Add it to struct
cs.Add(new UniversalEntry(key, ival));
}
catch(System.OverflowException)
{
// Too large for Int32, try Int64
try
{
// Convert to value
lval = System.Convert.ToInt64(val, CultureInfo.InvariantCulture);
// Add it to struct
cs.Add(new UniversalEntry(key, lval));
}
catch(System.OverflowException)
{
// Too large for Int64, return error
RaiseError(line, ERROR_VALUETOOBIG);
}
catch(System.FormatException)
{
// ERROR: Invalid value in replacedignment
RaiseError(line, ERROR_VALUEINVALID);
}
}
catch(System.FormatException)
{
// ERROR: Invalid value in replacedignment
RaiseError(line, ERROR_VALUEINVALID);
}
}
// Reset key and value
keysb.Length = 0;
valsb.Length = 0;
// End of replacedignment
pm = PM_NOTHING;
}
// Check for new line
else if(c == '\n')
{
// Count the new line
line++;
}
// Everything else is part of the value
else
{
valsb.Append(char.ToLowerInvariant(c));
}
}
// ================ Parsing a string
else if(pm == PM_STRING)
{
// Check if in an escape sequence
if(escape)
{
// What character?
switch(c)
{
case '\\': valsb.Append('\\'); break;
case 'n': valsb.Append('\n'); break;
case '\"': valsb.Append('\"'); break;
case 'r': valsb.Append('\r'); break;
case 't': valsb.Append('\t'); break;
default:
// Is it a number?
//if("0123456789".IndexOf(c.ToString(CultureInfo.InvariantCulture)) > -1)
if(c >= '0' && c <= '9')
{
int vv = 0;
char vc = '0';
// Convert the next 3 characters to a number
string v = data.Substring(pos, 3);
try { vv = System.Convert.ToInt32(v.Trim(), CultureInfo.InvariantCulture); }
catch(System.FormatException)
{
// ERROR: Invalid value in replacedignment
RaiseError(line, ERROR_VALUEINVALID);
}
// Convert the number to a char
try { vc = System.Convert.ToChar(vv, CultureInfo.InvariantCulture); }
catch(System.FormatException)
{
// ERROR: Invalid value in replacedignment
RaiseError(line, ERROR_VALUEINVALID);
}
// Add the char
valsb.Append(Char.ToLowerInvariant(vc));
}
else
{
// Add the character as it is
valsb.Append(c);
}
// Leave switch
break;
}
// End of escape sequence
escape = false;
}
else
{
// Check for sequence start
if(c == '\\')
{
// Next character is of escape sequence
escape = true;
}
// Check if string ends
else if(c == '\"')
{
// Add string to struct
cs.Add(new UniversalEntry(keysb.ToString().Trim(), valsb.ToString()));
// End of replacedignment
pm = PM_replacedIGNMENT;
// Reset key and value
keysb.Length = 0;
valsb.Length = 0;
}
// Check for new line
else if(c == '\n')
{
// Count the new line
line++;
}
// Everything else is just part of string
else
{
// Add to value
valsb.Append(c);
}
}
}
// ================ Parsing a keyword
else if(pm == PM_KEYWORD)
{
// Check if keyword ends
if(c == ';')
{
// Add to the struct depending on the keyword
switch(valsb.ToString().Trim().ToLowerInvariant())
{
case "true":
// Add boolean true
cs.Add(new UniversalEntry(keysb.ToString().Trim(), true));
break;
case "false":
// Add boolean false
cs.Add(new UniversalEntry(keysb.ToString().Trim(), false));
break;
default:
// Unknown keyword
RaiseError(line, ERROR_KEYWORDUNKNOWN);
break;
}
// End of replacedignment
pm = PM_NOTHING;
// Reset key and value
keysb.Length = 0;
valsb.Length = 0;
}
// Check for new line
else if(c == '\n')
{
// Count the new line
line++;
}
// Everything else is just part of keyword
else
{
// Add to value
valsb.Append(c);
}
}
// Next character
pos++;
}
// Return the parsed result
return cs;
}
19
View Source File : UTF8String.cs
License : GNU General Public License v3.0
Project Creator : anydream
License : GNU General Public License v3.0
Project Creator : anydream
public int IndexOf(string value, int startIndex) {
return String.IndexOf(value, startIndex);
}
19
View Source File : Options.cs
License : MIT License
Project Creator : aolszowka
License : MIT License
Project Creator : aolszowka
private static string GetArgumentName (int index, int maxIndex, string description)
{
if (description == null)
return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
string[] nameStart;
if (maxIndex == 1)
nameStart = new string[]{"{0:", "{"};
else
nameStart = new string[]{"{" + index + ":"};
for (int i = 0; i < nameStart.Length; ++i) {
int start, j = 0;
do {
start = description.IndexOf (nameStart [i], j);
} while (start >= 0 && j != 0 ? description [j++ - 1] == '{' : false);
if (start == -1)
continue;
int end = description.IndexOf ("}", start);
if (end == -1)
continue;
return description.Substring (start + nameStart [i].Length, end - start - nameStart [i].Length);
}
return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
}
19
View Source File : DatabaseLogAnalyzer.cs
License : MIT License
Project Creator : ap0405140
License : MIT License
Project Creator : ap0405140
private List<DatabaseLog> ReadLogDML()
{
List<DatabaseLog> dmllog, tmplog;
int i;
string databasename, schemaname, tablename;
DataTable dtTables, dtTemp;
DBLOG_DML[] tablelist;
List<FLOG> dtLoglist;
databasename = DB.DatabaseName;
schemaname = "";
tablename = "";
if (_objectname.Length > 0)
{
schemaname = _objectname.Substring(0, _objectname.IndexOf(".", 0));
tablename = _objectname.Substring(_objectname.IndexOf(".", 0) + 1, _objectname.Length - _objectname.IndexOf(".", 0) - 1);
}
// get DML Transaction list
_tsql = "if object_id('tempdb..#TransactionList') is not null drop table #TransactionList; ";
DB.ExecuteSQL(_tsql, false);
_tsql = "set transaction isolation level read uncommitted; "
+ "select 'TransactionID'=a.[Transaction ID], "
+ " 'BeginTime'=isnull(min(a.[Begin Time]),max(a.[End Time])), "
+ " 'EndTime'=isnull(max(a.[End Time]),min(a.[Begin Time])), "
+ " 'BeginLSN'=min([Current LSN]), "
+ " 'EndLSN'=max([Current LSN]) "
+ " into #TransactionList "
+ " from sys.fn_dblog(null,null) a "
+ " where a.[Transaction ID]<>N'0000:00000000' "
+ " and exists(select 1 from sys.fn_dblog(null,null) b where b.[Transaction ID]=a.[Transaction ID] and b.Operation=N'LOP_COMMIT_XACT') "
+ " group by a.[Transaction ID] "
+ " having cast(min(a.[Begin Time]) as datetime) between '" + _starttime + "' and '" + _endtime + "' "
+ " or cast(max(a.[End Time]) as datetime) between '" + _starttime + "' and '" + _endtime + "' ";
DB.ExecuteSQL(_tsql, false);
ReadPercent = ReadPercent + 5;
// get StartLSN and EndLSN
_tsql = "select 'StartLSN'=cast(cast(convert(varbinary,substring(t.StartLSN,1,8),2) as bigint) as varchar)+':'+cast(cast(convert(varbinary,substring(t.StartLSN,10,8),2) as bigint) as varchar)+':'+cast(cast(convert(varbinary,substring(t.StartLSN,19,4),2) as bigint) as varchar), "
+ " 'EndLSN'=cast(cast(convert(varbinary,substring(t.EndLSN,1,8),2) as bigint) as varchar)+':'+cast(cast(convert(varbinary,substring(t.EndLSN,10,8),2) as bigint) as varchar)+':'+cast(cast(convert(varbinary,substring(t.EndLSN,19,4),2) as bigint) as varchar), "
+ " 'EndLSNvar'=EndLSN "
+ " from (select 'StartLSN'=cast(min(BeginLSN) as varchar),'EndLSN'=cast(max(EndLSN) as varchar) from #TransactionList) t ";
dtTemp = DB.Query(_tsql, false);
if (dtTemp != null && dtTemp.Rows.Count > 0)
{
_startLSN = "'" + dtTemp.Rows[0]["StartLSN"].ToString() + "'";
_endLSN = "'" + dtTemp.Rows[0]["EndLSN"].ToString() + "'";
_endLSN_var = "'" + dtTemp.Rows[0]["EndLSNvar"].ToString() + "'";
}
else
{
_startLSN = "null";
_endLSN = "null";
_endLSN_var = "";
}
// get DML original log list
_tsql = "if object_id('tempdb..#LogList') is not null drop table #LogList; ";
DB.ExecuteSQL(_tsql, false);
_tsql = "select *,istail=cast(0 as bit) "
+ " into #LogList "
+ " from sys.fn_dblog(null,null) t "
+ " where 1=2; ";
DB.ExecuteSQL(_tsql, false);
_tsql = "set transaction isolation level read uncommitted; "
+ " insert into #LogList "
+ " output inserted.* "
+ "select *,istail=0 "
+ " from sys.fn_dblog(" + _startLSN + ", " + _endLSN + ") t "
+ " where [Transaction ID] in(select [TransactionID] from #TransactionList) "
+ " and [Context] in('LCX_HEAP','LCX_CLUSTERED','LCX_MARK_AS_GHOST','LCX_TEXT_TREE','LCX_TEXT_MIX') "
+ " and [Operation] in('LOP_INSERT_ROWS','LOP_DELETE_ROWS','LOP_MODIFY_ROW','LOP_MODIFY_COLUMNS') "
+ " and [AllocUnitName]<>'Unknown Alloc Unit' "
+ " and [AllocUnitName] not like 'sys.%' "
+ " and [AllocUnitName] is not null ";
if (_objectname.Length > 0)
{
_tsql = _tsql + " and case when parsename([AllocUnitName],3) is not null then parsename([AllocUnitName],2) else parsename([AllocUnitName],1) end='" + tablename + "' "
+ " and case when parsename([AllocUnitName],3) is not null then parsename([AllocUnitName],3) else parsename([AllocUnitName],2) end='" + schemaname + "' ";
}
_tsql = _tsql
+ "union all "
+ "select *,istail=1 "
+ " from sys.fn_dblog(null,null) t "
+ " where [Current LSN]>" + _endLSN_var
+ " and [Context] in('LCX_HEAP','LCX_CLUSTERED','LCX_MARK_AS_GHOST','LCX_TEXT_TREE','LCX_TEXT_MIX') "
+ " and [Operation] in('LOP_MODIFY_ROW','LOP_MODIFY_COLUMNS') "
+ " and [AllocUnitName]<>'Unknown Alloc Unit' "
+ " and [AllocUnitName] not like 'sys.%' "
+ " and [AllocUnitName] is not null ";
if (_objectname.Length > 0)
{
_tsql = _tsql + " and case when parsename([AllocUnitName],3) is not null then parsename([AllocUnitName],2) else parsename([AllocUnitName],1) end='" + tablename + "' "
+ " and case when parsename([AllocUnitName],3) is not null then parsename([AllocUnitName],3) else parsename([AllocUnitName],2) end='" + schemaname + "' ";
}
dtLoglist = DB.Query<FLOG>(_tsql, false);
_tsql = $"alter table #LogList add constraint pk#LogList{Guid.NewGuid().ToString().Replace("-", "")} primary key clustered ([Current LSN]); ";
DB.ExecuteSQL(_tsql, false);
// get table list
_tsql = "select distinct 'TableName'=case when parsename([AllocUnitName],3) is not null then parsename([AllocUnitName],2) else parsename([AllocUnitName],1) end, "
+ " 'SchemaName'=case when parsename([AllocUnitName],3) is not null then parsename([AllocUnitName],3) else parsename([AllocUnitName],2) end "
+ " from #LogList "
+ " where istail=0; ";
dtTables = DB.Query(_tsql, false);
ReadPercent = ReadPercent + 5;
tablelist = new DBLOG_DML[dtTables.Rows.Count];
dmllog = new List<DatabaseLog>();
i = 0;
foreach (DataRow dr in dtTables.Rows)
{
tablename = dr["TableName"].ToString();
schemaname = dr["SchemaName"].ToString();
tablelist[i] = new DBLOG_DML(databasename, schemaname, tablename, DB, LogFile);
tablelist[i].dtLogs = dtLoglist.Where(p => p.AllocUnitName == $"{schemaname}.{tablename}"
|| p.AllocUnitName.StartsWith($"{schemaname}.{tablename}.")).ToList();
#if DEBUG
FCommon.WriteTextFile(LogFile, $"Start replacedysis Log for [{schemaname}].[{tablename}]. ");
#endif
tmplog = tablelist[i].replacedyzeLog(_startLSN, _endLSN);
dmllog.AddRange(tmplog);
ReadPercent = ReadPercent + Convert.ToInt32(Math.Floor((tablelist[i].dtLogs.Count * 1.0) / (dtLoglist.Count * 1.0) * 85.0));
#if DEBUG
FCommon.WriteTextFile(LogFile, $"End replacedysis Log for [{schemaname}].[{tablename}]. ");
#endif
i = i + 1;
}
dmllog = dmllog.OrderBy(p => p.TransactionID).ToList();
ReadPercent = 95;
return dmllog;
}
19
View Source File : OptionConverter.cs
License : Apache License 2.0
Project Creator : apache
License : Apache License 2.0
Project Creator : apache
public static string SubsreplaceduteVariables(string value, System.Collections.IDictionary props)
{
StringBuilder buf = new StringBuilder();
int i = 0;
int j, k;
while(true)
{
j = value.IndexOf(DELIM_START, i);
if (j == -1)
{
if (i == 0)
{
return value;
}
else
{
buf.Append(value.Substring(i, value.Length - i));
return buf.ToString();
}
}
else
{
buf.Append(value.Substring(i, j - i));
k = value.IndexOf(DELIM_STOP, j);
if (k == -1)
{
throw new LogException("[" + value + "] has no closing brace. Opening brace at position [" + j + "]");
}
else
{
j += DELIM_START_LEN;
string key = value.Substring(j, k - j);
string replacement = props[key] as string;
if (replacement != null)
{
buf.Append(replacement);
}
i = k + DELIM_STOP_LEN;
}
}
}
}
19
View Source File : Transform.cs
License : Apache License 2.0
Project Creator : apache
License : Apache License 2.0
Project Creator : apache
public static void WriteEscapedXmlString(XmlWriter writer, string textData, string invalidCharReplacement)
{
string stringData = MaskXmlInvalidCharacters(textData, invalidCharReplacement);
// Write either escaped text or CDATA sections
int weightCData = 12 * (1 + CountSubstrings(stringData, CDATA_END));
int weightStringEscapes = 3*(CountSubstrings(stringData, "<") + CountSubstrings(stringData, ">")) + 4*CountSubstrings(stringData, "&");
if (weightStringEscapes <= weightCData)
{
// Write string using string escapes
writer.WriteString(stringData);
}
else
{
// Write string using CDATA section
int end = stringData.IndexOf(CDATA_END);
if (end < 0)
{
writer.WriteCData(stringData);
}
else
{
int start = 0;
while (end > -1)
{
writer.WriteCData(stringData.Substring(start, end - start));
if (end == stringData.Length - 3)
{
start = stringData.Length;
writer.WriteString(CDATA_END);
break;
}
else
{
writer.WriteString(CDATA_UNESCAPABLE_TOKEN);
start = end + 2;
end = stringData.IndexOf(CDATA_END, start);
}
}
if (start < stringData.Length)
{
writer.WriteCData(stringData.Substring(start));
}
}
}
}
19
View Source File : Transform.cs
License : Apache License 2.0
Project Creator : apache
License : Apache License 2.0
Project Creator : apache
private static int CountSubstrings(string text, string substring)
{
int count = 0;
int offset = 0;
int length = text.Length;
int substringLength = substring.Length;
if (length == 0)
{
return 0;
}
if (substringLength == 0)
{
return 0;
}
while(offset < length)
{
int index = text.IndexOf(substring, offset);
if (index == -1)
{
break;
}
count++;
offset = index + substringLength;
}
return count;
}
19
View Source File : ExcelVBAProject.cs
License : Apache License 2.0
Project Creator : Appdynamics
License : Apache License 2.0
Project Creator : Appdynamics
private void ReadModules()
{
foreach (var modul in Modules)
{
var stream = Doreplacedent.Storage.SubStorage["VBA"].DataStreams[modul.streamName];
var byCode = VBACompression.DecompressPart(stream, (int)modul.ModuleOffset);
string code = Encoding.GetEncoding(CodePage).GetString(byCode);
int pos=0;
while(pos+9<code.Length && code.Substring(pos,9)=="Attribute")
{
int linePos=code.IndexOf("\r\n",pos);
string[] lineSplit;
if(linePos>0)
{
lineSplit = code.Substring(pos + 9, linePos - pos - 9).Split('=');
}
else
{
lineSplit=code.Substring(pos+9).Split(new char[]{'='},1);
}
if (lineSplit.Length > 1)
{
lineSplit[1] = lineSplit[1].Trim();
var attr =
new ExcelVbaModuleAttribute()
{
Name = lineSplit[0].Trim(),
DataType = lineSplit[1].StartsWith("\"") ? eAttributeDataType.String : eAttributeDataType.NonString,
Value = lineSplit[1].StartsWith("\"") ? lineSplit[1].Substring(1, lineSplit[1].Length - 2) : lineSplit[1]
};
modul.Attributes._list.Add(attr);
}
pos = linePos + 2;
}
modul.Code=code.Substring(pos);
}
}
19
View Source File : ExcelWorkbook.cs
License : Apache License 2.0
Project Creator : Appdynamics
License : Apache License 2.0
Project Creator : Appdynamics
internal void GetDefinedNames()
{
XmlNodeList nl = WorkbookXml.SelectNodes("//d:definedNames/d:definedName", NameSpaceManager);
if (nl != null)
{
foreach (XmlElement elem in nl)
{
string fullAddress = elem.InnerText;
int localSheetID;
ExcelWorksheet nameWorksheet;
if(!int.TryParse(elem.GetAttribute("localSheetId"), NumberStyles.Number, CultureInfo.InvariantCulture, out localSheetID))
{
localSheetID = -1;
nameWorksheet=null;
}
else
{
nameWorksheet=Worksheets[localSheetID + _package._worksheetAdd];
}
var addressType = ExcelAddressBase.IsValid(fullAddress);
ExcelRangeBase range;
ExcelNamedRange namedRange;
if (fullAddress.IndexOf("[") == 0)
{
int start = fullAddress.IndexOf("[");
int end = fullAddress.IndexOf("]", start);
if (start >= 0 && end >= 0)
{
string externalIndex = fullAddress.Substring(start + 1, end - start - 1);
int index;
if (int.TryParse(externalIndex, NumberStyles.Any, CultureInfo.InvariantCulture, out index))
{
if (index > 0 && index <= _externalReferences.Count)
{
fullAddress = fullAddress.Substring(0, start) + "[" + _externalReferences[index - 1] + "]" + fullAddress.Substring(end + 1);
}
}
}
}
if (addressType == ExcelAddressBase.AddressType.Invalid || addressType == ExcelAddressBase.AddressType.InternalName || addressType == ExcelAddressBase.AddressType.ExternalName || addressType==ExcelAddressBase.AddressType.Formula || addressType==ExcelAddressBase.AddressType.ExternalAddress) //A value or a formula
{
double value;
range = new ExcelRangeBase(this, nameWorksheet, elem.GetAttribute("name"), true);
if (nameWorksheet == null)
{
namedRange = _names.Add(elem.GetAttribute("name"), range);
}
else
{
namedRange = nameWorksheet.Names.Add(elem.GetAttribute("name"), range);
}
if (Utils.ConvertUtil._invariantCompareInfo.IsPrefix(fullAddress, "\"")) //String value
{
namedRange.NameValue = fullAddress.Substring(1,fullAddress.Length-2);
}
else if (double.TryParse(fullAddress, NumberStyles.Number, CultureInfo.InvariantCulture, out value))
{
namedRange.NameValue = value;
}
else
{
//if (addressType == ExcelAddressBase.AddressType.ExternalAddress || addressType == ExcelAddressBase.AddressType.ExternalName)
//{
// var r = new ExcelAddress(fullAddress);
// namedRange.NameFormula = '\'[' + r._wb
//}
//else
//{
namedRange.NameFormula = fullAddress;
//}
}
}
else
{
ExcelAddress addr = new ExcelAddress(fullAddress, _package, null);
if (localSheetID > -1)
{
if (string.IsNullOrEmpty(addr._ws))
{
namedRange = Worksheets[localSheetID + _package._worksheetAdd].Names.Add(elem.GetAttribute("name"), new ExcelRangeBase(this, Worksheets[localSheetID + _package._worksheetAdd], fullAddress, false));
}
else
{
namedRange = Worksheets[localSheetID + _package._worksheetAdd].Names.Add(elem.GetAttribute("name"), new ExcelRangeBase(this, Worksheets[addr._ws], fullAddress, false));
}
}
else
{
var ws = Worksheets[addr._ws];
namedRange = _names.Add(elem.GetAttribute("name"), new ExcelRangeBase(this, ws, fullAddress, false));
}
}
if (elem.GetAttribute("hidden") == "1" && namedRange != null) namedRange.IsNameHidden = true;
if(!string.IsNullOrEmpty(elem.GetAttribute("comment"))) namedRange.NameComment=elem.GetAttribute("comment");
}
}
}
19
View Source File : ExcelAddress.cs
License : Apache License 2.0
Project Creator : Appdynamics
License : Apache License 2.0
Project Creator : Appdynamics
private void SetWbWs(string address)
{
int pos;
if (address[0] == '[')
{
pos = address.IndexOf("]");
_wb = address.Substring(1, pos - 1);
_ws = address.Substring(pos + 1);
}
else
{
_wb = "";
_ws = address;
}
if(_ws.StartsWith("'"))
{
pos = _ws.IndexOf("'",1);
while(pos>0 && pos+1<_ws.Length && _ws[pos+1]=='\'')
{
_ws = _ws.Substring(0, pos) + _ws.Substring(pos+1);
pos = _ws.IndexOf("'", pos+1);
}
if (pos>0)
{
_address = _ws.Substring(pos+2);
_ws = _ws.Substring(1, pos-1);
return;
}
}
pos = _ws.IndexOf("!");
if (pos==0)
{
_address = _ws.Substring(1);
_ws = _wb;
_wb = "";
}
else if (pos > -1)
{
_address = _ws.Substring(pos + 1);
_ws = _ws.Substring(0, pos);
}
else
{
_address = address;
}
}
19
View Source File : StringExtensions.cs
License : MIT License
Project Creator : aprilyush
License : MIT License
Project Creator : aprilyush
public static String Substring(this String str, String after, String? before = null, Int32 startIndex = 0, Int32[]? positions = null)
{
if (String.IsNullOrEmpty(str)) return str;
if (String.IsNullOrEmpty(after) && String.IsNullOrEmpty(before)) return str;
/*
* 1,只有start,从该字符串之后部分
* 2,只有end,从开头到该字符串之前
* 3,同时start和end,取中间部分
*/
var p = -1;
if (!String.IsNullOrEmpty(after))
{
p = str.IndexOf(after, startIndex);
if (p < 0) return null;
p += after.Length;
// 记录位置
if (positions != null && positions.Length > 0) positions[0] = p;
}
if (String.IsNullOrEmpty(before)) return str.Substring(p);
var f = str.IndexOf(before, p >= 0 ? p : startIndex);
if (f < 0) return null;
// 记录位置
if (positions != null && positions.Length > 1) positions[1] = f;
if (p >= 0)
return str.Substring(p, f - p);
else
return str.Substring(0, f);
}
19
View Source File : StringExtensions.cs
License : MIT License
Project Creator : arcusmaximus
License : MIT License
Project Creator : arcusmaximus
public static List<string> Split(this string str, string separator, int? maxItems = null)
{
List<string> result = new List<string>();
int start = 0;
int end;
while (start <= str.Length)
{
if (start < str.Length && (maxItems == null || result.Count < maxItems.Value - 1))
{
end = str.IndexOf(separator, start);
if (end < 0)
end = str.Length;
}
else
{
end = str.Length;
}
result.Add(str.Substring(start, end - start));
start = end + separator.Length;
}
return result;
}
19
View Source File : QlieScript.cs
License : MIT License
Project Creator : arcusmaximus
License : MIT License
Project Creator : arcusmaximus
private IEnumerable<Range> GetCommandArgumentRanges(int linePos, string line)
{
int start = line.IndexOf(",");
while (start >= 0 && start < line.Length)
{
start++;
int end = line.IndexOf(",", start);
if (end < 0)
end = line.Length;
yield return new Range(linePos + start, end - start, ScriptStringType.Message);
start = end;
}
}
19
View Source File : Proxy_Back.aspx.cs
License : GNU General Public License v3.0
Project Creator : ardatdev
License : GNU General Public License v3.0
Project Creator : ardatdev
protected void Page_Load(object sender, EventArgs e)
{
string url = Request.QueryString["url"];
if (url != null)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url.Trim());
WebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string htmlText = reader.ReadToEnd();
reader.Close();
response.Close();
string a = "href=\"/";
int link = htmlText.IndexOf(a);
while (link >= 0)
{
htmlText = htmlText.Replace("\"/", "\"" + url);
if (a.Length < htmlText.Length)
{
link = htmlText.IndexOf(a, a.Length);
}
else
{
link = -1;
}
}
Web_Context.Text = htmlText;
}
}
19
View Source File : AvaloneEditColorizer.cs
License : GNU General Public License v3.0
Project Creator : armandoalonso
License : GNU General Public License v3.0
Project Creator : armandoalonso
protected override void ColorizeLine(DoreplacedentLine line)
{
int lineStartOffset = line.Offset;
string text = CurrentContext.Doreplacedent.GetText(line);
int start = 0;
int index;
while ((index = text.IndexOf("AvalonEdit", start)) >= 0)
{
base.ChangeLinePart(
lineStartOffset + index, // startOffset
lineStartOffset + index + 10, // endOffset
(VisualLineElement element) =>
{
// This lambda gets called once for every VisualLineElement
// between the specified offsets.
Typeface tf = element.TextRunProperties.Typeface;
// Replace the typeface with a modified version of
// the same typeface
element.TextRunProperties.SetTypeface(new Typeface(
tf.FontFamily,
FontStyles.Italic,
FontWeights.Bold,
tf.Stretch
));
});
start = index + 1; // search for next occurrence
}
}
19
View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : ASCOMInitiative
License : GNU General Public License v3.0
Project Creator : ASCOMInitiative
private static void SetAcl(string uri, string userName)
{
try
{
string command = $"http add urlacl url={uri} user={userName}";
TL.LogMessage("SetAcl", $"Enable arguments: {command}");
// Parse out the port number and resource value
int doubleSlashIndex = uri.IndexOf("//");
int colonIndex;
if (uri.Contains("[")) // The URI contains an IPv6 address
{
colonIndex = uri.IndexOf("]:", doubleSlashIndex + 2) + 1;
}
else // A host name or IPv4 address
{
colonIndex = uri.IndexOf(":", doubleSlashIndex + 2);
}
string portAndUri = uri.Substring(colonIndex + 1);
TL.LogMessage("SetAcl", $"Colon index: {colonIndex}, Port and URI: {portAndUri}");
string netshCommand = "";
foreach (IPAddress ipAddress in HostPc.IpV4Addresses)
{
TL.LogMessage("SetAcl", $"Found IP Network Address: {ipAddress}");
netshCommand += $@"http delete urlacl url=http://{ipAddress}:{portAndUri}" + "\r\n";
TL.LogMessage("SetAcl", $"Sending UrlAcl Delete command to NetSh: {netshCommand}");
}
// Remove the URL ACL if it exists
//SendNetshCommand(netshCommand);
TL.BlankLine();
//netshCommand = "";
foreach (IPAddress ipAddress in HostPc.IpV6Addresses)
{
TL.LogMessage("SetAcl", $"Found IP Network Address: {ipAddress}");
netshCommand += $@"http delete urlacl url=http://[{ipAddress}]:{portAndUri}" + "\r\n";
TL.LogMessage("SetAcl", $"Sending UrlAcl Delete command to NetSh: {netshCommand}");
}
// Remove the URL ACL if it exists
//SendNetshCommand(netshCommand);
TL.BlankLine();
//netshCommand = "";
// Remove localhost entry if present
string localHostCommand = $@"http delete urlacl url=http://127.0.0.1:{portAndUri}" + "\r\n";
TL.LogMessage("SetAcl", $"Sending UrlAcl Delete command to NetSh: {localHostCommand}");
netshCommand += localHostCommand;
// Remove + wild card entry if present
string plusCommand = $@"http delete urlacl url=http://+:{portAndUri}" + "\r\n";
TL.LogMessage("SetAcl", $"Sending UrlAcl Delete command to NetSh: {plusCommand}");
netshCommand += plusCommand;
// Remove * wild card entry if present
string starCommand = $@"http delete urlacl url=http://*:{portAndUri}" + "\r\n";
TL.LogMessage("SetAcl", $"Sending UrlAcl Delete command to NetSh: {starCommand}");
netshCommand += starCommand;
// Now send the new UrlAcl
TL.LogMessage("SetAcl", $"Sending new UrlAcl command to NetSh: {command}");
netshCommand += command + "\r\n";
TL.LogMessage("SetAcl", $"NetSh command length: {netshCommand.Length} NetSh Command: {netshCommand}");
SendNetshCommand(netshCommand);
}
catch (Exception ex)
{
TL.LogMessageCrLf("SetAcl", $"Process exception: {ex}");
}
}
See More Examples