internal IncludePredicate(string platform, string architecture, string flavor, string defines) { _platform = (platform == null || platform.Length == 0) ? null : platform; _architecture = (architecture == null || architecture.Length == 0) ? null : architecture; _flavor = (flavor == null || flavor.Length == 0) ? null : flavor; _conditionParser = (defines == null || defines.Length == 0) ? null : new ConditionParser(defines.Split(new char[] { ';' })); }
public static ConditionExpression ParseCondition (string condition) { ConditionParser parser = new ConditionParser (condition); ConditionExpression e = parser.ParseExpression (); if (!parser.tokenizer.IsEOF ()) throw new ExpressionParseException (String.Format ("Unexpected token found, {0}, in condition \"{1}\"", parser.tokenizer.Token, condition)); return e; }
public void UnbalancedParenthesis3Test() { ConditionParser.ParseExpression("(1))"); }
public void UnbalancedParenthesis3Test() { Assert.Throws <ConditionParseException>(() => ConditionParser.ParseExpression("(1))")); }
public ModelReaderOptions(String platform, String architecture, String flavor, Boolean treatFxInternalAsPublic, String defines) : this() { Platform = platform; Architecture = architecture; Flavor = flavor; TreatFxInternalAsPublic = treatFxInternalAsPublic; if (defines != null && defines.Length > 0) _conditionParser = new ConditionParser(defines.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)); }
static public void RunFromList(List <string> cmd, Loop caller = null) { //if still waiting for response, stop waiting, run new script if (StatusMonitor.CurrentStatus == "WAITFORRESP") { StatusMonitor.CurrentStatus = "NORMAL"; cache.Clear(); } //interpret script file bool skip = false; //decide whether the line should be skipped under the current scope bool inloop = false; List <string> loopblock = new List <string>(); int bracketcount = 0; int numLine = 0; string line; foreach (string ln in cmd) { numLine++; line = ln.Trim(); if (line == "" || line.StartsWith("#")) { } else if (!line.StartsWith("*") && StatusMonitor.CurrentStatus == "WAITFORRESP" && caller == null) { cache.Add(line); } else { line = line.TrimStart('*'); try { //handle looping codes if (!inloop && line == "@{") { inloop = true; bracketcount++; } else if (inloop && line.EndsWith("{")) { bracketcount++; loopblock.Add(line); } else if (inloop && line == "}") { bracketcount--; if (bracketcount == 0) { inloop = false; new Loop(new List <string>(loopblock)); loopblock.Clear(); } else { loopblock.Add(line); } } else if (inloop) { loopblock.Add(line); } else if (line == "}") //end of conditional region { skip = false; } else if (line == "}ELSE{") // flip condition { skip = !skip; } else if (!skip) { if (line.EndsWith("{")) //start of conditional region { skip = !ConditionParser.Parse(line.Trim('{')); } else { foreach (KeyValuePair <string, string> var in localVars) { line = line.Replace(var.Key, var.Value); } if (!ScriptEngine.Run(line, caller)) { break; } } } } catch { Notifier.ErrorMsg("Unable to parse script at line " + numLine.ToString() + ":\n" + ln); } } } //clean up variables localVars.Clear(); }
public void InvalidNumberWithUnaryMinusTest() { ConditionParser.ParseExpression("-a31"); }
public void MethodWithLogEventInfoTest() { var factories = SetupConditionMethods(); Assert.Equal(true, ConditionParser.ParseExpression("IsValid()", factories).Evaluate(CreateWellKnownContext())); }
private static async Task GetToResidential(uint aetheryteId) { if (!ConditionParser.HasAetheryte(aetheryteId)) { return; } if (!WorldManager.TeleportById(aetheryteId)) { return; } do { await Coroutine.Sleep(2000); } while (Core.Me.IsCasting); await Coroutine.Sleep(2000); if (CommonBehaviors.IsLoading) { await Coroutine.Wait(-1, () => !CommonBehaviors.IsLoading); } await Coroutine.Wait(10000, () => GameObjectManager.GetObjectByNPCId(aetheryteId) != null); await Coroutine.Sleep(2000); var unit = GameObjectManager.GetObjectByNPCId(aetheryteId); if (!unit.IsWithinInteractRange) { Log($"Not in range {unit.Distance2D()}"); var target = unit.Location; if (WorldManager.RawZoneId == 129) { target = new Vector3(-89.30112f, 18.80033f, -2.019181f); } else if (WorldManager.RawZoneId == 628) { target = new Vector3(48.03579f, 4.549999f, -31.83851f); } //await CommonTasks.MoveAndStop(new MoveToParameters(target.FanOutRandom(2f), unit.Name), 2f, true); await Navigation.GetTo(WorldManager.ZoneId, target); /* Navigator.PlayerMover.MoveTowards(target); * while (!unit.IsWithinInteractRange) * { * Navigator.PlayerMover.MoveTowards(target); * await Coroutine.Sleep(100); * } * * Navigator.PlayerMover.MoveStop();*/ } else { Log($"In range {unit.Distance2D()}"); } unit.Target(); unit.Interact(); await Coroutine.Wait(5000, () => SelectString.IsOpen); if (SelectString.IsOpen) { if (Translator.Language == Language.Chn) { SelectString.ClickLineContains("冒险者住宅区传送"); } else { SelectString.ClickLineContains("Residential"); } } await Coroutine.Sleep(500); await Coroutine.Wait(5000, () => SelectString.IsOpen); }
public void UnrecognizedMethod() { ConditionParser.ParseExpression("unrecognized-method()"); }
public void ParseNullText() { Assert.IsNull(ConditionParser.ParseExpression(null)); }
public void UnrecognizedPunctuation() { ConditionParser.ParseExpression("#"); }
public void UnrecognizedUnicodeChar2() { ConditionParser.ParseExpression("\u0015"); }
public void UnrecognizedToken() { ConditionParser.ParseExpression("somecompletelyunrecognizedtoken"); }
public void UnclosedString() { ConditionParser.ParseExpression("'Hello world"); }
public void InvalidNumberTest() { ConditionParser.ParseExpression("-123.4a"); }
public override void Start() { Poi.Current = null; //setup navigation manager Navigator.NavigationProvider = new DDNavigationProvider(new ServiceNavigationProvider()); Navigator.PlayerMover = new SlideMover(); TreeHooks.Instance.ClearAll(); _tasks = new TaskManagerProvider(); _tasks.Add(new LoadingHandler()); _tasks.Add(new DeathWindowHandler()); _tasks.Add(new SideStepTask()); //not sure if i want the trap handler to be above combat or not _tasks.Add(new TrapHandler()); //pomanders for sure need to happen before combat so that we can correctly apply Lust for bosses _tasks.Add(new Pomanders()); _tasks.Add(new CombatHandler()); _tasks.Add(new LobbyHandler()); _tasks.Add(new GetToCaptiain()); _tasks.Add(new POTDEntrance()); _tasks.Add(new CarnOfReturn()); _tasks.Add(new FloorExit()); _tasks.Add(new Loot()); _tasks.Add(new StuckDetection()); _tasks.Add(new POTDNavigation()); _tasks.Add(new BaseLogicHandler()); Settings.Instance.Stop = false; if (!Core.Me.IsDow()) { Logger.Error("Please change to a DOW class"); _root = new ActionAlwaysFail(); return; } //setup combat manager CombatTargeting.Instance.Provider = new DDCombatTargetingProvider(); GameSettingsManager.FaceTargetOnAction = true; if (Constants.Lang == Language.Chn) { //回避 - sidestep //Zekken if (PluginManager.Plugins.Any(i => (i.Plugin.Name.Contains("Zekken") || i.Plugin.Name.Contains("技能躲避")) && i.Enabled)) { Logger.Error("禁用 AOE技能躲避插件 - Zekken"); _root = new ActionAlwaysFail(); return; } } if (PluginManager.Plugins.Any(i => i.Plugin.Name == "Zekken" && i.Enabled)) { Logger.Error( "Zekken is currently turned on, It will interfere with DeepDive & SideStep. Please Turn it off and restart the bot."); _root = new ActionAlwaysFail(); return; } if (!ConditionParser.IsQuestCompleted(67092)) { Logger.Error("You must complete \"The House That Death Built\" to run this base."); Logger.Error( "Please switch to \"Order Bot\" and run the profile: \\BotBases\\DeepDive\\Profiles\\PotD_Unlock.xml"); _root = new ActionAlwaysFail(); return; } StopPlz = false; SetupSettings(); _root = new ActionRunCoroutine(async x => { if (StopPlz) { return(false); } if (!_init) { ff14bot.Helpers.Logging.Write($"DeepDive is waiting on Initialization to finish"); return(true); } if (await _tasks.Run()) { await Coroutine.Yield(); } else { Logger.Warn($"No tasks ran"); await Coroutine.Sleep(1000); } return(true); }); }
public void ParseEmptyText() { ConditionParser.ParseExpression(""); }
private static LayoutRenderer ParseLayoutRenderer(ConfigurationItemFactory configurationItemFactory, SimpleStringReader stringReader) { int ch = stringReader.Read(); Debug.Assert(ch == '{', "'{' expected in layout specification"); string name = ParseLayoutRendererName(stringReader); var layoutRenderer = GetLayoutRenderer(configurationItemFactory, name); var wrappers = new Dictionary <Type, LayoutRenderer>(); var orderedWrappers = new List <LayoutRenderer>(); ch = stringReader.Read(); while (ch != -1 && ch != '}') { string parameterName = ParseParameterName(stringReader).Trim(); if (stringReader.Peek() == '=') { stringReader.Read(); // skip the '=' PropertyInfo propertyInfo; LayoutRenderer parameterTarget = layoutRenderer; if (!PropertyHelper.TryGetPropertyInfo(layoutRenderer, parameterName, out propertyInfo)) { Type wrapperType; if (configurationItemFactory.AmbientProperties.TryGetDefinition(parameterName, out wrapperType)) { LayoutRenderer wrapperRenderer; if (!wrappers.TryGetValue(wrapperType, out wrapperRenderer)) { wrapperRenderer = configurationItemFactory.AmbientProperties.CreateInstance(parameterName); wrappers[wrapperType] = wrapperRenderer; orderedWrappers.Add(wrapperRenderer); } if (!PropertyHelper.TryGetPropertyInfo(wrapperRenderer, parameterName, out propertyInfo)) { propertyInfo = null; } else { parameterTarget = wrapperRenderer; } } } if (propertyInfo == null) { ParseParameterValue(stringReader); } else { if (typeof(Layout).IsAssignableFrom(propertyInfo.PropertyType)) { var nestedLayout = new SimpleLayout(); string txt; LayoutRenderer[] renderers = CompileLayout(configurationItemFactory, stringReader, true, out txt); nestedLayout.SetRenderers(renderers, txt); propertyInfo.SetValue(parameterTarget, nestedLayout, null); } else if (typeof(ConditionExpression).IsAssignableFrom(propertyInfo.PropertyType)) { var conditionExpression = ConditionParser.ParseExpression(stringReader, configurationItemFactory); propertyInfo.SetValue(parameterTarget, conditionExpression, null); } else { string value = ParseParameterValue(stringReader); PropertyHelper.SetPropertyFromString(parameterTarget, parameterName, value, configurationItemFactory); } } } else { SetDefaultPropertyValue(configurationItemFactory, layoutRenderer, parameterName); } ch = stringReader.Read(); } layoutRenderer = ApplyWrappers(configurationItemFactory, layoutRenderer, orderedWrappers); return(layoutRenderer); }
public void NullLiteralTest() { Assert.AreEqual("null", ConditionParser.ParseExpression("null").ToString()); }
public void TypePromotionNegativeTest2() { var factories = SetupConditionMethods(); Assert.Throws <ConditionEvaluationException>(() => ConditionParser.ParseExpression("GetGuid() == ToInt16(1)", factories).Evaluate(CreateWellKnownContext())); }
static public string Parse(string val) { string value = val; //booleans if (value == "TRUE") { return("TRUE"); } if (value == "FALSE") { return("FALSE"); } //variables //user defined foreach (KeyValuePair <string, string> pair in Configuration.usrDef) { value = value.Replace("{" + pair.Key + "}", pair.Value); } //system defined variables value = value.Replace("{STATUS}", StatusMonitor.CurrentStatus); value = value.Replace("{PosX}", ScriptEngine.GetParent().Location.X.ToString()); value = value.Replace("{PosY}", ScriptEngine.GetParent().Location.Y.ToString()); value = value.Replace("{Width}", ScriptEngine.GetParent().Size.Width.ToString()); value = value.Replace("{Height}", ScriptEngine.GetParent().Size.Height.ToString()); //system defined time variables DateTime now = DateTime.Now; CultureInfo cult = new CultureInfo(Configuration.culture); value = value.Replace("{s}", now.ToString("%s", cult)); value = value.Replace("{m}", now.ToString("%m", cult)); value = value.Replace("{h}", now.ToString("%h", cult)); value = value.Replace("{t}", now.ToString("tt", cult)); value = value.Replace("{D}", now.ToString("d", cult)); value = value.Replace("{M}", now.ToString("MMMM", cult)); value = value.Replace("{Y}", now.ToString("yyy", cult)); value = value.Replace("{d}", now.ToString("dddd", cult)); if (value.IndexOfAny(logicop) == -1 && value.IndexOfAny(op) == -1) //if there are no operators, then the value is either a string, a number or the value of another variable { if (value.Contains("\"")) { return(value.Trim().Trim('\"')); } else if (Configuration.usrDef.ContainsKey(value.Trim())) { return(Configuration.usrDef[value.Trim()]); } else { return(value); } } else { if (value.IndexOf('(') != -1) { tmp = value.Substring(value.LastIndexOf("("), value.IndexOf(")") - value.LastIndexOf("(") + 1); return(Parse(value.Replace(tmp, Parse(tmp.Trim(brac))))); } if (value.IndexOfAny(logicop) != -1) { return(ConditionParser.Parse(value).ToString().ToUpper()); } else { if (value.IndexOf('+') != -1) { try { return((Convert.ToInt32(Parse(value.Split('+')[0].Trim())) + Convert.ToInt32(Parse(value.Split('+')[1].Trim()))).ToString()); } catch { return(Parse(value.Split('+')[0].Trim()) + Parse(value.Split('+')[1].Trim())); } } if (value.IndexOf('-') != -1) { try { return((Convert.ToInt32(Parse(value.Split('-')[0].Trim())) - Convert.ToInt32(Parse(value.Split('-')[1].Trim()))).ToString()); } catch { return(Parse(value.Split('-')[0].Trim()) + "-" + Parse(value.Split('-')[1].Trim())); } } if (value.IndexOf('*') != -1) { try { return((Convert.ToInt32(Parse(value.Split('*')[0].Trim())) * Convert.ToInt32(Parse(value.Split('*')[1].Trim()))).ToString()); } catch { return(Parse(value.Split('*')[0].Trim()) + "*" + Parse(value.Split('*')[1].Trim())); } } if (value.IndexOf('/') != -1) { try { return((Convert.ToInt32(Parse(value.Split('/')[0].Trim())) / Convert.ToInt32(Parse(value.Split('/')[1].Trim()))).ToString()); } catch { return(Parse(value.Split('/')[0].Trim()) + "/" + Parse(value.Split('/')[1].Trim())); } } if (value.IndexOf('^') != -1) { try { return((Convert.ToInt32(Parse(value.Split('^')[0].Trim())) ^ Convert.ToInt32(Parse(value.Split('^')[1].Trim()))).ToString()); } catch { return(Parse(value.Split('^')[0].Trim()) + "^" + Parse(value.Split('^')[1].Trim())); } } } } return(value); }
private static void ConfigureLogging() { var config = clusterConfig.Logging; var loggingConfig = new LoggingConfiguration(); if (config != null) { // parse level var level = !string.IsNullOrEmpty(config.Level) ? LogLevel.FromString(config.Level) : LogLevel.Info; var layout = "[${longdate}] [${level:format=FirstCharacter:uppercase=true}] [${logger:shortName=true}] ${message} ${exception:format=ToString,StackTrace}"; if (config.EnableConsoleLog) { if (config.EnableConsoleColors) { var target = new ColoredConsoleTarget("console") { Layout = layout }; target.RowHighlightingRules.Add(new ConsoleRowHighlightingRule( ConditionParser.ParseExpression("level == LogLevel.Trace"), ConsoleOutputColor.DarkMagenta, ConsoleOutputColor.NoChange)); target.RowHighlightingRules.Add(new ConsoleRowHighlightingRule( ConditionParser.ParseExpression("level == LogLevel.Debug"), ConsoleOutputColor.Gray, ConsoleOutputColor.NoChange)); target.RowHighlightingRules.Add(new ConsoleRowHighlightingRule( ConditionParser.ParseExpression("level == LogLevel.Info"), ConsoleOutputColor.White, ConsoleOutputColor.NoChange)); target.RowHighlightingRules.Add(new ConsoleRowHighlightingRule( ConditionParser.ParseExpression("level == LogLevel.Warn"), ConsoleOutputColor.Yellow, ConsoleOutputColor.NoChange)); target.RowHighlightingRules.Add(new ConsoleRowHighlightingRule( ConditionParser.ParseExpression("level == LogLevel.Error"), ConsoleOutputColor.Red, ConsoleOutputColor.NoChange)); target.RowHighlightingRules.Add(new ConsoleRowHighlightingRule( ConditionParser.ParseExpression("level == LogLevel.Fatal"), ConsoleOutputColor.DarkRed, ConsoleOutputColor.White)); loggingConfig.AddTarget(target); loggingConfig.AddRule(level, LogLevel.Fatal, target); } else { var target = new ConsoleTarget("console") { Layout = layout }; loggingConfig.AddTarget(target); loggingConfig.AddRule(level, LogLevel.Fatal, target); } } if (!string.IsNullOrEmpty(config.LogFile)) { var target = new FileTarget("file") { FileName = GetLogPath(config, config.LogFile), FileNameKind = FilePathKind.Unknown, Layout = layout }; loggingConfig.AddTarget(target); loggingConfig.AddRule(level, LogLevel.Fatal, target); } if (config.PerPoolLogFile) { foreach (var poolConfig in clusterConfig.Pools) { var target = new FileTarget(poolConfig.Id) { FileName = GetLogPath(config, poolConfig.Id + ".log"), FileNameKind = FilePathKind.Unknown, Layout = layout }; loggingConfig.AddTarget(target); loggingConfig.AddRule(level, LogLevel.Fatal, target, poolConfig.Id); } } } LogManager.Configuration = loggingConfig; logger = LogManager.GetCurrentClassLogger(); }
public void NotTest() { Assert.Equal("(not True)", ConditionParser.ParseExpression("not true").ToString()); Assert.Equal("(not (not True))", ConditionParser.ParseExpression("not not true").ToString()); Assert.Equal("(not (not (not True)))", ConditionParser.ParseExpression("not not not true").ToString()); }
static public bool Run(string script, Loop caller = null) { if (StatusMonitor.waiting && !script.StartsWith("*")) { StatusMonitor.pausedScr.Add(script); return(true); } DbgOutput.Write(script); List <string> cachecopy; string _script = script.Trim().TrimStart('*'); if (_script == "" || _script.StartsWith("#")) { return(true); } if (_script.StartsWith("@")) { new Loop(_script.Trim('@')); return(true); } if (_script.Contains("?")) { if (!_script.Split('?')[0].Contains(":")) // this is added because sometimes the argument for a command contains ? { if (!ConditionParser.Parse(_script.Split('?')[0])) { return(true); } else { _script = script.Split('?')[1]; } } } if (_script.Contains(";")) { RunFromList(new List <string>(_script.Split(';'))); return(true); } if (_script.Contains("=") && !_script.Contains("?") && !_script.Contains(":")) { //local variable if (_script.StartsWith("$")) { if (localVars.ContainsKey(_script.Split('=')[0].Trim())) { localVars[_script.Split('=')[0].Trim()] = ValueParser.Parse(_script.Substring(_script.IndexOf('=') + 1, _script.Length - _script.IndexOf('=') - 1).Trim()); } else { localVars.Add(_script.Split('=')[0].Trim(), ValueParser.Parse(_script.Substring(_script.IndexOf('=') + 1, _script.Length - _script.IndexOf('=') - 1).Trim())); } } else if (Configuration.usrDef.ContainsKey(_script.Split('=')[0].Trim())) { Configuration.usrDef[_script.Split('=')[0].Trim()] = ValueParser.Parse(_script.Substring(_script.IndexOf('=') + 1, _script.Length - _script.IndexOf('=') - 1).Trim()); } else { Configuration.usrDef.Add(_script.Split('=')[0].Trim(), ValueParser.Parse(_script.Substring(_script.IndexOf('=') + 1, _script.Length - _script.IndexOf('=') - 1).Trim())); } return(true); } Script scr = new Script(_script); switch (scr.Command.Trim()) { case "": break; case "WAIT": if (caller != null) { System.Threading.Thread.Sleep(Convert.ToInt32(scr.Args)); } else { StatusMonitor.waiting = true; StatusMonitor.waittime = Convert.ToInt32(scr.Args); } break; case "WAITFORRESP": StatusMonitor.CurrentStatus = "WAITFORRESP"; break; case "END": return(false); case "BREAK": if (caller != null) { caller.Break(); } break; case "SHOWFRM": if (!parent.Visible) { frm.ShowForm(); } break; case "HIDEFRM": if (parent.Visible) { frm.HideForm(); StatusMonitor.CurrentStatus = "HIDDEN"; } break; case "CLOSEFRM": frm.CloseForm(); break; case "RESTART": Application.Restart(); break; case "EXEC": if (scr.Args.Contains("$")) { if (scr.Args.Split('$')[0].Trim().EndsWith(".exe") && !scr.Args.Trim().StartsWith("*")) { IOChannel Eng = new IOChannel(scr.Args.Split('$')[0].Trim(), scr.Args.Split('$')[0].Trim(), scr.Args.Split('$')[1].Trim()); Eng.Start(); } else { Process.Start(scr.Args.Split('$')[0].Trim().Trim('*'), scr.Args.Split('$')[1].Trim()); } } else { if (scr.Args.Trim().EndsWith(".exe") && !scr.Args.Trim().StartsWith("*")) { IOChannel Eng = new IOChannel(scr.Args.Trim(), scr.Args.Trim(), ""); Eng.Start(); } else { Process.Start(scr.Args.Trim().Trim('*')); } } break; //case "LOCK": // StatusMonitor.LockedStatus.Push(StatusMonitor.CurrentStatus); // break; //case "JOIN": // if (StatusMonitor.LockedStatus.Count != 0) // { // StatusMonitor.CurrentStatus = StatusMonitor.LockedStatus.Pop(); // if (StatusMonitor.CurrentStatus != "WAITFORRESP") // { // StatusMonitor.waitingforresp = false; // cachecopy = new List<string>(cache); // foreach (string line in cachecopy) // { // DbgOutput.Write(line); // } // RunFromList(cachecopy); // foreach (string line in cachecopy) // { // cache.Remove(line); // } // } // } // break; case "IMG": StatusMonitor.currentAniFrames.Clear(); frm.PutImg(scr.Args.Trim()); break; case "_IMG": //internal use only, for putting animation frames frm.PutImg(scr.Args.Trim()); break; case "ANIMATE": StatusMonitor.currentAniFrames.Clear(); StatusMonitor.currentFrame = 0; foreach (string path in Directory.EnumerateFiles(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\Media\img\" + scr.Args.Trim().Trim('\\') + @"\", "*.png", SearchOption.TopDirectoryOnly)) { StatusMonitor.currentAniFrames.Add(path.Replace(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\Media\img\", "")); } break; case "MSG": Notifier.ShowMsg(scr.Args); break; case "POSX": frm.PosX(Convert.ToInt32(scr.Args.Trim())); break; case "POSY": frm.PosY(Convert.ToInt32(scr.Args.Trim())); break; case "ACTIVATE": frm.Activate(); break; case "ERROR": Notifier.ErrorMsg(scr.Args); break; case "SCRIPT": if (scr.Args.Contains(".")) { RunFromFile(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\Scripts\" + scr.Args.Split('.')[0].Trim(), scr.Args.Split('.')[1]); } else { RunFromFile(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\Scripts\" + scr.Args.Trim()); } break; case "STATUS": StatusMonitor.CurrentStatus = scr.Args.Trim(); if (StatusMonitor.CurrentStatus != "WAITFORRESP") { cachecopy = new List <string>(cache); foreach (string line in cachecopy) { DbgOutput.Write(line); cache.Remove(line); } RunFromList(cachecopy); } break; case "SOUND": SoundPlayer.Play(scr.Args.Trim()); break; default: try { IOChannel Eng = new IOChannel(scr.Command.Trim(), Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"\Routines\" + scr.Command.Trim() + ".exe", scr.Args); Eng.Start(); } catch { Notifier.ErrorMsg("Unable to " + scr.Command.Trim() + " " + scr.Args.Trim() + ". \nMake sure all necessary files are under \"Routines\"."); } break; } return(true); }
public void LogLevelWithoutAName() { ConditionParser.ParseExpression("LogLevel.'somestring'"); }
private bool ShouldPurchaseItem(ShopPurchase shopPurchase) { if (shopPurchase.IgnoreItem) { return(false); } var info = Data.ShopItemMap[shopPurchase.ShopItem]; var itemData = info.ItemData; var itemCount = itemData.ItemCount(); // check inventory count if (itemCount >= shopPurchase.MaxCount) { return(false); } if (ConditionParser.FreeItemSlots() == 0 && itemCount == 0) { return(false); } // check cost switch (info.ShopJob) { case ShopJob.Crafter: { switch (info.ShopType) { case ShopType.Yellow50: if (Memory.Scrips.YellowCrafter < info.Cost) { return(false); } break; #if RB_CN case ShopType.Yellow58: if (Memory.Scrips.YellowCrafter < info.Cost) { return(false); } break; #endif case ShopType.Yellow61: if (Memory.Scrips.YellowCrafter < info.Cost) { return(false); } break; case ShopType.Yellow70: if (Memory.Scrips.YellowCrafter < info.Cost) { return(false); } break; case ShopType.White80: if (Memory.Scrips.WhiteCrafter < info.Cost) { return(false); } break; } } break; case ShopJob.Gatherer: { switch (info.ShopType) { case ShopType.Yellow50: if (Memory.Scrips.YellowGatherer < info.Cost) { return(false); } break; #if RB_CN case ShopType.Yellow58: if (Memory.Scrips.YellowGatherer < info.Cost) { return(false); } break; #endif case ShopType.Yellow61: if (Memory.Scrips.YellowGatherer < info.Cost) { return(false); } break; case ShopType.Yellow70: if (Memory.Scrips.YellowGatherer < info.Cost) { return(false); } break; case ShopType.White80: if (Memory.Scrips.WhiteGatherer < info.Cost) { return(false); } break; } } break; } return(true); }
private static LayoutRenderer ParseLayoutRenderer(ConfigurationItemFactory configurationItemFactory, SimpleStringReader sr) { int ch = sr.Read(); Debug.Assert(ch == '{', "'{' expected in layout specification"); string name = ParseLayoutRendererName(sr); LayoutRenderer lr = configurationItemFactory.LayoutRenderers.CreateInstance(name); var wrappers = new Dictionary <Type, LayoutRenderer>(); var orderedWrappers = new List <LayoutRenderer>(); ch = sr.Read(); while (ch != -1 && ch != '}') { string parameterName = ParseParameterName(sr).Trim(); if (sr.Peek() == '=') { sr.Read(); // skip the '=' PropertyInfo pi; LayoutRenderer parameterTarget = lr; if (!PropertyHelper.TryGetPropertyInfo(lr, parameterName, out pi)) { Type wrapperType; if (configurationItemFactory.AmbientProperties.TryGetDefinition(parameterName, out wrapperType)) { LayoutRenderer wrapperRenderer; if (!wrappers.TryGetValue(wrapperType, out wrapperRenderer)) { wrapperRenderer = configurationItemFactory.AmbientProperties.CreateInstance(parameterName); wrappers[wrapperType] = wrapperRenderer; orderedWrappers.Add(wrapperRenderer); } if (!PropertyHelper.TryGetPropertyInfo(wrapperRenderer, parameterName, out pi)) { pi = null; } else { parameterTarget = wrapperRenderer; } } } if (pi == null) { ParseParameterValue(sr); } else { if (typeof(Layout).IsAssignableFrom(pi.PropertyType)) { var nestedLayout = new SimpleLayout(); string txt; LayoutRenderer[] renderers = CompileLayout(configurationItemFactory, sr, true, out txt); nestedLayout.SetRenderers(renderers, txt); pi.SetValue(parameterTarget, nestedLayout, null); } else if (typeof(ConditionExpression).IsAssignableFrom(pi.PropertyType)) { var conditionExpression = ConditionParser.ParseExpression(sr, configurationItemFactory); pi.SetValue(parameterTarget, conditionExpression, null); } else { string value = ParseParameterValue(sr); PropertyHelper.SetPropertyFromString(parameterTarget, parameterName, value, configurationItemFactory); } } } else { // what we've just read is not a parameterName, but a value // assign it to a default property (denoted by empty string) PropertyInfo pi; if (PropertyHelper.TryGetPropertyInfo(lr, string.Empty, out pi)) { if (typeof(SimpleLayout) == pi.PropertyType) { pi.SetValue(lr, new SimpleLayout(parameterName), null); } else { string value = parameterName; PropertyHelper.SetPropertyFromString(lr, pi.Name, value, configurationItemFactory); } } else { InternalLogger.Warn("{0} has no default property", lr.GetType().FullName); } } ch = sr.Read(); } lr = ApplyWrappers(configurationItemFactory, lr, orderedWrappers); return(lr); }
public void ExtraParenthesisTest() { Assert.Equal("3.141592", ConditionParser.ParseExpression("(((3.141592)))").ToString()); }
/// <summary> /// Setup all the logging targets and rules. Call only once, usually at the start of the program. /// </summary> public static void Initialize() { Directory.CreateDirectory(Constants.LogDirectory); LoggingConfiguration loggingConfiguration = new LoggingConfiguration(); // Setup and layout formatting for the console ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget() { Name = Constants.ApplicationNameFormatted, //Layout = "${message}" // Match the console target format with file targets. It looks cluttered on small terminals Layout = "${longdate} [${pad:padCharacter= :padding=5:fixedLength=true:alignmentOnTruncation=Right:${uppercase:${level}}}] [${callsite:includeNamespace=false:cleanNamesOfAnonymousDelegates=true:cleanNamesOfAsyncContinuations=true}] ${message}" }; // Override the trace color ConsoleRowHighlightingRule consoleTarget_RowRules_Trace = new ConsoleRowHighlightingRule() { Condition = ConditionParser.ParseExpression("level == LogLevel.Trace"), ForegroundColor = ConsoleOutputColor.Gray }; consoleTarget.RowHighlightingRules.Add(consoleTarget_RowRules_Trace); // Override the debug color ConsoleRowHighlightingRule consoleTarget_RowRules_Debug = new ConsoleRowHighlightingRule() { Condition = ConditionParser.ParseExpression("level == LogLevel.Debug"), ForegroundColor = ConsoleOutputColor.Gray }; consoleTarget.RowHighlightingRules.Add(consoleTarget_RowRules_Debug); // Override the info color ConsoleRowHighlightingRule consoleTarget_RowRules_Info = new ConsoleRowHighlightingRule() { Condition = ConditionParser.ParseExpression("level == LogLevel.Info"), ForegroundColor = ConsoleOutputColor.White }; consoleTarget.RowHighlightingRules.Add(consoleTarget_RowRules_Info); // Override the warn color ConsoleRowHighlightingRule consoleTarget_RowRules_Warn = new ConsoleRowHighlightingRule() { Condition = ConditionParser.ParseExpression("level == LogLevel.Warn"), ForegroundColor = ConsoleOutputColor.Yellow }; consoleTarget.RowHighlightingRules.Add(consoleTarget_RowRules_Warn); // Override the error color ConsoleRowHighlightingRule consoleTarget_RowRules_Error = new ConsoleRowHighlightingRule() { Condition = ConditionParser.ParseExpression("level == LogLevel.Error"), ForegroundColor = ConsoleOutputColor.Red }; consoleTarget.RowHighlightingRules.Add(consoleTarget_RowRules_Error); // Override the fatal color ConsoleRowHighlightingRule consoleTarget_RowRules_Fatal = new ConsoleRowHighlightingRule() { Condition = ConditionParser.ParseExpression("level == LogLevel.Fatal"), ForegroundColor = ConsoleOutputColor.Red }; consoleTarget.RowHighlightingRules.Add(consoleTarget_RowRules_Fatal); // Add consoleTarget to the overall configuration loggingConfiguration.AddTarget(consoleTarget); loggingConfiguration.AddRule(LogLevel.Trace, LogLevel.Fatal, Constants.ApplicationNameFormatted); // ================================= // All messages from Trace to Warn levels write to the general file FileTarget fileTarget_General = new FileTarget() { Name = Constants.ApplicationNameFormatted, FileName = Path.Combine(Constants.LogDirectory, "General.log"), Layout = "${longdate} [${pad:padCharacter= :padding=5:fixedLength=true:alignmentOnTruncation=Right:${uppercase:${level}}}] [${callsite:includeNamespace=false:cleanNamesOfAnonymousDelegates=true:cleanNamesOfAsyncContinuations=true}] ${message}", ArchiveFileName = Path.Combine(Constants.LogDirectory, "General{#}.Archive.log"), ArchiveEvery = FileArchivePeriod.Day, ArchiveNumbering = ArchiveNumberingMode.Rolling, MaxArchiveFiles = 7, ConcurrentWrites = false }; // Limit how often the file will get written to disk. // Default: BufferSize = 50 (log events), FlushTimeout = 5000 (milliseconds) BufferingTargetWrapper fileAsyncTargetWrapper_General = new BufferingTargetWrapper { Name = Constants.ApplicationNameFormatted, WrappedTarget = fileTarget_General, BufferSize = 50, FlushTimeout = 5000, SlidingTimeout = false }; loggingConfiguration.AddTarget(fileAsyncTargetWrapper_General); loggingConfiguration.AddRule(LogLevel.Trace, LogLevel.Warn, Constants.ApplicationNameFormatted); // All messages from Warn to Fatal levels write to the error file with advanced trace information FileTarget fileTarget_Error = new FileTarget() { Name = Constants.ApplicationNameFormatted, FileName = Path.Combine(Constants.LogDirectory, "Error.log"), Layout = "${longdate} [${pad:padCharacter= :padding=5:fixedLength=true:alignmentOnTruncation=Right:${uppercase:${level}}}] [${callsite:includeSourcePath=true:cleanNamesOfAnonymousDelegates=true:cleanNamesOfAsyncContinuations=true}:${callsite-linenumber}; ${stacktrace}] ${message}${exception:format=ToString,StackTrace}", ArchiveFileName = Path.Combine(Constants.LogDirectory, "Error{#}.Archive.log"), ArchiveEvery = FileArchivePeriod.Day, ArchiveNumbering = ArchiveNumberingMode.Rolling, MaxArchiveFiles = 7, ConcurrentWrites = false }; loggingConfiguration.AddTarget(fileTarget_Error); loggingConfiguration.AddRule(LogLevel.Error, LogLevel.Fatal, Constants.ApplicationNameFormatted); // Apply all the custom configurations to the LogManager LogManager.Configuration = loggingConfiguration; // Setup logger factory InitializeDatabaseFactory(); Log.Info("Logging initialization finished."); }
public DiscordMessageService(ConditionParser conditionParser, DiscordClient discordClient, IOptions <Configuration> configuration) { _conditionParser = conditionParser; _discordClient = discordClient; _configuration = configuration.Value; }
private bool ShouldPurchaseItem(ShopPurchase shopPurchase) { var info = Data.ShopItemMap[shopPurchase.ShopItem]; var itemData = info.ItemData; var itemCount = itemData.ItemCount(); // check inventory count if (itemCount >= shopPurchase.MaxCount) { return(false); } if (ConditionParser.FreeItemSlots() == 0 && itemCount == 0) { return(false); } // check cost switch (info.ShopType) { case ShopType.RedCrafter50: if (Memory.Scrips.RedCrafter < info.Cost) { return(false); } break; case ShopType.RedCrafter61: if (Memory.Scrips.RedCrafter < info.Cost) { return(false); } break; case ShopType.YellowCrafterItems: if (Memory.Scrips.YellowCrafter < info.Cost) { return(false); } break; case ShopType.RedGatherer50: if (Memory.Scrips.RedGatherer < info.Cost) { return(false); } break; case ShopType.RedGatherer61: if (Memory.Scrips.RedGatherer < info.Cost) { return(false); } break; case ShopType.YellowGathererItems: if (Memory.Scrips.YellowGatherer < info.Cost) { return(false); } break; } return(true); }
public ConditionParserError(ConditionParser parser, string message) : base(String.Format("{0}: '{1}'", message, parser.ToString())) { }
public void UnbalancedParenthesis1Test() { ConditionParser.ParseExpression("check("); }