public async Task AddTaskAsyncShouldReturnPostedResult() { var functionsManager = new FunctionsManager("component", "statemachine"); var xcEvent = new object(); var publicMember = new object(); var internalMember = new object(); var context = new object(); var sender = Substitute.For <ISender>(); var task = functionsManager.AddTaskAsync(xcEvent, publicMember, internalMember, context, sender, "function"); var enqueuedParameter = functionsManager.GetTask(); var functionResult = new FunctionResult() { ComponentName = "component", StateMachineName = "statemachine", PublicMember = "{}", InternalMember = "{}", Senders = null, RequestId = enqueuedParameter.RequestId, }; functionsManager.AddTaskResult(functionResult); var publishedResult = await task; Assert.AreEqual(functionResult, publishedResult); }
public void Setup() { FunctionsManager.Initialize(); SpriteManager.Initialize(); AudioManager.Initialize(); CharacterNameManager.Initialize(); }
public void ObjectsHaveNoPropertyToDeserializeSoIgnoringThemInsteadOfThrowing() { var functionResult = new FunctionResult() { PublicMember = new JObject(), InternalMember = new JObject() }; var sender = new object(); var context = new object(); var publicMember = new object(); var internalMember = new object(); var functionsManager = new FunctionsManager("component", "statemachine"); functionsManager.AddTask(new object(), publicMember, internalMember, context, sender); Assert.DoesNotThrow(() => { functionsManager.ApplyFunctionResult(functionResult, publicMember, internalMember, context, sender); }); }
/// <summary> /// Loads all the functions using the given file name. /// </summary> /// <param name="fileName">The file name.</param> /// <param name="functionsName">The functions name.</param> private void LoadFunctions(string fileName, string functionsName) { string ext = Path.GetExtension(fileName); string folder = "LUA"; Functions.Type scriptType = Functions.Type.Lua; if (string.Compare(".cs", ext, true) == 0) { folder = "CSharp"; scriptType = Functions.Type.CSharp; } LoadTextFile( folder, fileName, (filePath) => { if (File.Exists(filePath)) { string text = File.ReadAllText(filePath); FunctionsManager.Get(functionsName).LoadScript(text, functionsName, scriptType); } else { UnityDebugger.Debugger.LogError(folder == "CSharp" ? "CSharp" : "LUA", "file " + filePath + " not found"); } }); }
public void AddTaskResultShouldThrowValidationExceptionWhenInvalidRequestId() { var sender = new object(); var functionResult = new FunctionResult() { RequestId = "unknown request id" }; var functionsManager = new FunctionsManager("component", "statemachine"); functionsManager.AddTask(new object(), new object(), new object(), new object(), sender, "function"); while (true) { var postedTask = functionsManager.GetTask(); if (postedTask != null) { break; } Thread.Sleep(TimeSpan.FromSeconds(1)); } var exception = Assert.Throws <ValidationException>(() => functionsManager.AddTaskResult(functionResult)); Assert.IsTrue(exception.Message.Contains("unknown request id"), "Exception message should show where is the problem"); }
public void ApplyPostedResultShouldWorkWithJObjects() { var publicMemberBefore = new PublicMember() { State = "before" }; var publicMemberAfter = new JObject(); publicMemberAfter.Add("State", new JValue("after")); var functionResult = new FunctionResult() { PublicMember = publicMemberAfter, }; var sender = new object(); var context = new object(); var internalMember = new object(); var functionsManager = new FunctionsManager("component", "statemachine"); functionsManager.AddTask(new object(), publicMemberBefore, internalMember, context, sender); functionsManager.ApplyFunctionResult(functionResult, publicMemberBefore, new object(), context, sender); Assert.AreEqual("after", publicMemberBefore.State); }
/// <summary> /// Fire the event named actionName, resulting in all lua functions being called. /// This one reduces GC bloat. /// </summary> /// <param name="actionName">Name of the action being triggered.</param> /// <param name="target">Object, passed to LUA function as 1-argument.</param> /// <param name="parameters">Parameters in question. First one must be target instance. </param> public void Trigger(string actionName, params object[] parameters) { List <string> actions; if (actionsList.TryGetValue(actionName, out actions) && actions != null) { FunctionsManager.Get(parameters[0].GetType().Name).Call(actions, parameters); } }
private void LoadFunctions(List <string> allowedTypes) { _functionsPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\ToolManager\"; CentralLogging.AppDebugLogger.WriteLine("Searching functions at: " + _functionsPath, Logging.LogLevel.Information); _functionManager = new FunctionsManager(_functionsPath + "functions.json", allowedTypes); _functionManager.Load(); }
public static FunctionElement createElement(FunctionsManager managerT, String title) { manager = managerT; element = new FunctionElement(manager); SmallDialog_FunctionsConfig dialog = new SmallDialog_FunctionsConfig(title); dialog.ShowDialog(); return(element); }
public void NullFunctionResultThrowsValidationException() { var functionsManager = new FunctionsManager("component", "statemachine"); var exception = Assert.Throws <ValidationException>(() => functionsManager.AddTaskResult(null)); Assert.IsTrue(exception.Message.Contains("null"), "Exception message should show where is the problem"); }
/// <summary> /// Fire the event named actionName, resulting in all lua functions being called. /// This one reduces GC bloat. /// </summary> /// <param name="actionName">Name of the action being triggered.</param> /// <param name="target">Object, passed to LUA function as 1-argument.</param> /// <param name="parameters">Parameters in question. First one must be target instance. </param> public void Trigger(string actionName, params object[] parameters) { if (!actionsList.ContainsKey(actionName) || actionsList[actionName] == null) { } else { FunctionsManager.Get(parameters[0].GetType().Name).Call(actionsList[actionName], parameters); } }
/// <summary> /// Fire the event named actionName, resulting in all lua functions being called. /// </summary> /// <param name="actionName">Name of the action being triggered.</param> /// <param name="target">Object, passed to LUA function as 1-argument.</param> /// <param name="deltaTime">Time since last Trigger of this event.</param> public void Trigger <T>(string actionName, T target, params object[] parameters) { if (!actionsList.ContainsKey(actionName) || actionsList[actionName] == null) { } else { FunctionsManager.Get(target.GetType().Name).CallWithInstance(actionsList[actionName], target, parameters); } }
public void NullContextThrowsValidationException() { var functionsManager = new FunctionsManager("component", "statemachine"); var exception = Assert.ThrowsAsync <ValidationException>(() => functionsManager. AddTaskAsync(new object(), new object(), new object(), null, new object(), "function")); Assert.IsTrue(exception.Message.Contains("Context"), "Exception message should show where is the problem"); }
/// <summary> /// Loads all the functions using the given file name. /// </summary> /// <param name="fileName">The file name.</param> /// <param name="functionsName">The functions name.</param> private void LoadFunctions(string fileName, string functionsName) { LoadTextFile( "LUA", fileName, (filePath) => { string text = File.ReadAllText(filePath); FunctionsManager.Get(functionsName).LoadScript(text, functionsName); }); }
/// <summary> /// Loads the script file in the given location. /// </summary> /// <param name="file">The file name.</param> /// <param name="functionsName">The functions name.</param> public void LoadFunctionsInFile(FileInfo file, string functionsName) { LoadTextFile( file.DirectoryName, file.Name, (filePath) => { StreamReader reader = new StreamReader(file.OpenRead()); string text = reader.ReadToEnd(); FunctionsManager.Get(functionsName).LoadScript(text, functionsName, file.Extension == ".lua" ? Functions.Type.Lua : Functions.Type.CSharp); }); }
//设置地图单元 public static void configElement(FunctionElement elementT, String title) { if (elementT == null) { Console.WriteLine("error in configElement"); return; } manager = (FunctionsManager)elementT.parent; element = elementT; SmallDialog_FunctionsConfig dialog = new SmallDialog_FunctionsConfig(title); dialog.textBox_name.Text = element.name; dialog.textBox_Commet.Text = element.commet; dialog.showParamsList(); dialog.ShowDialog(); }
public void Init() { FunctionsManager.Initialize(); FunctionsManager.ScheduledEvent.LoadScript(LuaFunctionString, "ScheduledEvent", Functions.Type.Lua); PrototypeManager.Initialize(); JToken reader = JToken.Parse(JsonPrototypeString); PrototypeManager.ScheduledEvent.Add(new ScheduledEvent("ping_log", evt => UnityDebugger.Debugger.LogFormat("Scheduler", "Event {0} fired", evt.Name))); PrototypeManager.ScheduledEvent.LoadJsonPrototypes((JProperty)reader.First); // The problem with unit testing singletons ///scheduler = Scheduler.Scheduler.Current; scheduler = new Scheduler.Scheduler(); callback = evt => UnityDebugger.Debugger.LogFormat("SchedulerTest", "Event {0} fired", evt.Name); }
public async Task AddTaskAsyncShouldReturnErrorResultIfTimeout() { FunctionsFactory.Instance.Configuration.TimeoutInMillis = 1; var functionsManager = new FunctionsManager("component", "statemachine"); var xcEvent = new object(); var publicMember = new object(); var internalMember = new object(); var context = new object(); var sender = Substitute.For <ISender>(); var publishedResult = await functionsManager.AddTaskAsync(xcEvent, publicMember, internalMember, context, sender, "function"); Assert.IsTrue(publishedResult.IsError); Assert.IsTrue(publishedResult.ErrorMessage.Contains("Timeout")); FunctionsFactory.Instance.Configuration.TimeoutInMillis = null; }
//生成函数体 private void genFunctionToHead(FileStream fs, FunctionsManager functionManager) { for (int i = 0; i < functionManager.getElementCount(); i++) { FunctionElement fun = (FunctionElement)functionManager.getElement(i); String strParams = " ("; ArrayList paramList = (ArrayList)fun.getValue(); for (int j = 0; j < paramList.Count; j++) { strParams += "p" + j; if (j < paramList.Count - 1) { strParams += ","; } } strParams += ");"; IOUtil.writeTextLine(fs, "host " + fun.name + strParams); } }
public void Awake() { if (Instance == null || Instance == this) { Instance = this; } else { UnityDebugger.Debugger.LogError("Two 'MainMenuController' exist, deleting the new version rather than the old."); Destroy(this.gameObject); } PrototypeManager.Initialize(); FunctionsManager.Initialize(); SpriteManager.Initialize(); AudioManager.Initialize(); // Load Mods and Settings on awake rather than on Starts ModsManager = new ModsManager(); Settings.LoadSettings(); }
/// <summary> /// Loads the base and the mods scripts. /// </summary> /// <param name="mods">The mods directories.</param> /// <param name="fileName">The file name.</param> private void LoadFunctionScripts(string functionsName, string fileName) { string filePath = Path.Combine(Application.streamingAssetsPath, "LUA"); filePath = Path.Combine(filePath, fileName); if (File.Exists(filePath)) { string text = File.ReadAllText(filePath); FunctionsManager.Get(functionsName).LoadScript(text, functionsName); } foreach (DirectoryInfo mod in mods) { filePath = Path.Combine(mod.FullName, fileName); if (File.Exists(filePath)) { string text = File.ReadAllText(filePath); FunctionsManager.Get(functionsName).LoadScript(text, functionsName); } } }
public void OnEnable() { if (Instance == null || Instance == this) { Instance = this; } else { UnityDebugger.Debugger.LogError("WorldController", "There should never be two world controllers."); } FunctionsManager.Initialize(); PrototypeManager.Initialize(); CharacterNameManager.Initialize(); SpriteManager.Initialize(); AudioManager.Initialize(); // FIXME: Do something real here. This is just to show how to register a C# event prototype for the Scheduler. PrototypeManager.ScheduledEvent.Add( new ScheduledEvent( "ping_log", (evt) => UnityDebugger.Debugger.LogFormat("Scheduler", "Event {0} fired", evt.Name))); ModsManager = new ModsManager(); // Reload incase any mods have changed settings Settings.LoadSettings(); if (SceneController.LoadWorldFromFileName != null) { CreateWorldFromSaveFile(SceneController.LoadWorldFromFileName); SceneController.LoadWorldFromFileName = null; } else { CreateEmptyWorld(); } SoundController = new SoundController(World); }
public void ApplyFunctionResultShouldThrowValidationExceptionWhenDeserializationFails() { var sender = new object(); var publicMemberBefore = new PublicMember() { State = "before" }; var publicMemberAfter = new JObject(); publicMemberAfter.Add("State", new JValue("after")); var functionResult = new FunctionResult() { PublicMember = "Hello", }; var functionsManager = new FunctionsManager("component", "statemachine"); functionsManager.AddTask(new object(), new object(), new object(), new object(), sender, "function"); while (true) { var postedTask = functionsManager.GetTask(); if (postedTask != null) { break; } Thread.Sleep(TimeSpan.FromSeconds(1)); } var exception = Assert.Throws <ValidationException>(() => functionsManager.ApplyFunctionResult(functionResult, publicMemberBefore, new object(), new object(), sender)); Assert.IsTrue(exception.Message.Contains("Hello"), "Exception message should show where is the problem"); }
public void ApplyFunctionResultShouldThrowInvalidSenderValidationException() { var sender = new object(); var functionResult = new FunctionResult() { Senders = new List <SenderResult>() { new SenderResult { SenderName = "UnknownSender", SenderParameter = "{ \"Value\": \"undo\" }", UseContext = false }, }, }; var functionsManager = new FunctionsManager("component", "statemachine"); functionsManager.AddTask(new object(), new object(), new object(), new object(), sender, "function"); while (true) { var postedTask = functionsManager.GetTask(); if (postedTask != null) { break; } Thread.Sleep(TimeSpan.FromSeconds(1)); } var exception = Assert.Throws <ValidationException>(() => functionsManager.ApplyFunctionResult(functionResult, new object(), new object(), new object(), sender)); Assert.IsTrue(exception.Message.Contains("UnknownSender"), "Exception message should show where is the problem"); }
public void AddTaskShouldPutTaskOnQueue() { var functionsManager = new FunctionsManager("component", "statemachine"); var xcEvent = new object(); var publicMember = new object(); var internalMember = new object(); var context = new object(); var sender = new object(); functionsManager.AddTask(xcEvent, publicMember, internalMember, context, sender, "function"); var enqueuedParameter = functionsManager.GetTask(); Assert.AreEqual(xcEvent, enqueuedParameter.Event); Assert.AreEqual(publicMember, enqueuedParameter.PublicMember); Assert.AreEqual(internalMember, enqueuedParameter.InternalMember); Assert.AreEqual(context, enqueuedParameter.Context); Assert.AreEqual("component", enqueuedParameter.ComponentName); Assert.AreEqual("statemachine", enqueuedParameter.StateMachineName); Assert.AreEqual("function", enqueuedParameter.FunctionName); Assert.IsNotNull(enqueuedParameter.RequestId); }
public void SetClosedAction(string funcName) { Closed = () => FunctionsManager.Get("ModDialogBox").Call(funcName, Result); }
/// <summary> /// Loads the Mod Dialog Box from the XML file. /// </summary> /// <param name="file">The FileInfo object that references to the XML file.</param> public void LoadFromXML(FileInfo file) { // TODO: Find a better way to do this. Not user friendly/Expansible. // ModDialogBox -> Dialog Background // |-> Title // |-> Content Content = transform.GetChild(0).GetChild(1); controls = new Dictionary <string, DialogControl>(); XmlSerializer serializer = new XmlSerializer(typeof(ModDialogBoxInformation)); try { ModDialogBoxInformation dialogBoxInfo = (ModDialogBoxInformation)serializer.Deserialize(file.OpenRead()); Title = dialogBoxInfo.title; foreach (DialogComponent gameObjectInfo in dialogBoxInfo.content) { // Implement new DialogComponents in here. switch (gameObjectInfo.ObjectType) { case "Text": GameObject textObject = (GameObject)Instantiate(Resources.Load("Prefab/DialogBoxPrefabs/DialogText"), Content); textObject.GetComponent <Text>().text = (string)gameObjectInfo.data; textObject.GetComponent <RectTransform>().anchoredPosition = gameObjectInfo.position; break; case "Input": GameObject inputObject = (GameObject)Instantiate(Resources.Load("Prefab/DialogBoxPrefabs/DialogInputComponent"), Content); inputObject.GetComponent <RectTransform>().anchoredPosition = gameObjectInfo.position; inputObject.GetComponent <RectTransform>().sizeDelta = gameObjectInfo.size; controls[gameObjectInfo.name] = inputObject.GetComponent <DialogControl>(); break; case "Image": GameObject imageObject = (GameObject)Instantiate(Resources.Load("Prefab/DialogBoxPrefabs/DialogImage"), Content); Texture2D imageTexture = new Texture2D((int)gameObjectInfo.size.x, (int)gameObjectInfo.size.y); try { imageTexture.LoadImage(File.ReadAllBytes(Path.Combine(Application.streamingAssetsPath, (string)gameObjectInfo.data))); Sprite imageSprite = Sprite.Create(imageTexture, new Rect(0, 0, gameObjectInfo.size.x, gameObjectInfo.size.y), Vector2.zero); imageObject.GetComponent <Image>().sprite = imageSprite; imageObject.GetComponent <RectTransform>().anchoredPosition = gameObjectInfo.position; imageObject.GetComponent <RectTransform>().sizeDelta = gameObjectInfo.size; controls[gameObjectInfo.name] = imageObject.GetComponent <DialogControl>(); } catch (System.Exception error) { Debug.ULogErrorChannel("ModDialogBox", "Error converting image:" + error.Message); return; } break; case "Button": GameObject buttonObject = (GameObject)Instantiate(Resources.Load("Prefab/DialogBoxPrefabs/DialogButton")); buttonObject.GetComponent <RectTransform>().anchoredPosition = gameObjectInfo.position; buttonObject.GetComponent <RectTransform>().sizeDelta = gameObjectInfo.size; buttonObject.GetComponentInChildren <Text>().text = (string)gameObjectInfo.data; buttonObject.GetComponent <DialogButton>().buttonName = gameObjectInfo.name; controls[gameObjectInfo.name] = buttonObject.GetComponent <DialogButton>(); break; } } // Enable dialog buttons from the list of buttons. foreach (DialogBoxResult buttons in dialogBoxInfo.buttons) { switch (buttons) { case DialogBoxResult.Yes: gameObject.transform.GetChild(0).transform.Find("Buttons/btnYes").gameObject.SetActive(true); break; case DialogBoxResult.No: gameObject.transform.GetChild(0).transform.Find("Buttons/btnNo").gameObject.SetActive(true); break; case DialogBoxResult.Cancel: gameObject.transform.GetChild(0).transform.Find("Buttons/btnCancel").gameObject.SetActive(true); break; case DialogBoxResult.Okay: gameObject.transform.GetChild(0).transform.Find("Buttons/btnOK").gameObject.SetActive(true); break; } } EventActions eventActions = new EventActions(); foreach (KeyValuePair <string, string> pair in dialogBoxInfo.Actions) { eventActions.Register(pair.Key, pair.Value); } events = eventActions; FunctionsManager.Get("ModDialogBox").RegisterGlobal(typeof(ModDialogBox)); extraData = new List <object>(); } catch (System.Exception error) { Debug.ULogErrorChannel("ModDialogBox", "Error deserializing data:" + error.Message); } }
public async Task AddTaskShouldApplyPostedResultAndCallSenders() { var functionsManager = new FunctionsManager("component", "statemachine"); var xcEvent = new object(); var publicMember = new PublicMember() { State = "before" }; var internalMember = new object(); var context = new object(); var sender = Substitute.For <ISender>(); var task = functionsManager.AddTask(xcEvent, publicMember, internalMember, context, sender, "function"); Task.Run(() => { while (true) { var postedTask = functionsManager.GetTask(); if (postedTask != null) { var functionResult = new FunctionResult() { ComponentName = "component", StateMachineName = "statemachine", PublicMember = "{ \"State\": \"after\" }", Senders = new List <SenderResult> { new SenderResult { SenderName = "Do", SenderParameter = "{ \"Value\": \"do\" }", UseContext = true }, new SenderResult { SenderName = "Undo", SenderParameter = "{ \"Value\": \"undo\" }", UseContext = false }, new SenderResult { SenderName = "Reply", UseContext = true } }, RequestId = postedTask.RequestId, }; functionsManager.AddTaskResult(functionResult); break; } Thread.Sleep(TimeSpan.FromSeconds(1)); } }); await task; Assert.AreEqual("after", publicMember.State); sender.Received().Do(context, Arg.Is <DoEvent>(evt => evt.Value == "do"), null); sender.Received().SendEvent(Arg.Is <UndoEvent>(evt => evt.Value == "undo")); sender.Received().Reply(context, Arg.Any <object>(), null); }