// Methods /// <summary> /// Called by Unity. /// </summary> public void Awake() { // Create our script domain domain = ScriptDomain.CreateDomain("ScriptDomain", true); // Find start positions startPosition = tankObject.transform.position; startRotation = tankObject.transform.rotation; // Add listener for new button CodeUI.onNewClicked += (CodeUI ui) => { // Load new file ui.codeEditor.text = Resources.Load <TextAsset>(newTemplate).text; }; // Add listener for example button CodeUI.onLoadClicked += (CodeUI ui) => { // Load example file ui.codeEditor.text = Resources.Load <TextAsset>(exampleTemplate).text; }; CodeUI.onCompileClicked += (CodeUI ui) => { // Try to run the script RunTankScript(ui.codeEditor.text); }; }
/// <summary> /// Called by Unity. /// </summary> public void Start() { // Create domain domain = ScriptDomain.CreateDomain("Example Domain"); // Compile and load code ScriptAssembly assembly = domain.CompileAndLoadSource(sourceCode, ScriptSecurityMode.UseSettings); // Check for compiler errors if (domain.CompileResult.Success == false) { // Get all errors foreach (CompilationError error in domain.CompileResult.Errors) { if (error.IsError == true) { Debug.LogError(error.ToString()); } else if (error.IsWarning == true) { Debug.LogWarning(error.ToString()); } } } }
public ScriptAssembly(ScriptDomain scriptDomain, string path) { this.scriptDomain = scriptDomain; this.path = path; lazyAssembly = new Utility.Lazy <Assembly>(this.LoadAssembly); }
static void MonoMessageHandler(EMonoScriptDomain target, EMonoScriptMsgID msgid, IntPtr buffer, int length) { byte[] data = new byte[length]; if (length != 0) { Marshal.Copy(buffer, data, 0, length); } int tid = (int)target; switch (msgid) { case EMonoScriptMsgID.ScriptMsgIDInitialize: AppDomainSetup setup = new AppDomainSetup(); setup.ApplicationBase = new SourceFileInfo("mono/lib/" + (target == EMonoScriptDomain.ScriptDomainServer ? "server" : "client"), "GAME").FullName; AppDomain aDomain = AppDomain.CreateDomain(domainName[tid], null, setup); DomainInterface dInterface = (DomainInterface)aDomain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, typeof(DomainInterface).FullName); scriptDomains[tid] = new ScriptDomain() { Domain = aDomain, Interface = dInterface }; break; default: Debug.DevMsg("[Source.Host.exe] Recieved Mono message, target: {0}, id: {1}, length: {2}\n", target, msgid, length); break; } }
/// <summary> /// Called by Unity. /// </summary> public void Start() { // Create domain domain = ScriptDomain.CreateDomain("Example Domain"); // Compile and load code - Note that we use 'CompileAndLoadMainSource' which is the same as 'CompileAndLoadSource' but returns the main type in the compiled assembly ScriptType type = domain.CompileAndLoadMainSource(sourceCode, ScriptSecurityMode.UseSettings); // Get the property value from a property with the name 'ExampleProperty' and cast it to a string value // Note that only static properties can be accessed via a 'ScriptType' instance. A 'ScriptProxy' is required for instance properties string propertyString = (string)type.PropertiesStatic["ExampleProperty"]; // Check that the string we read has the expected value Debug.Log(propertyString == "Hello World"); // Set a property value with the name 'ExampleProperty' // Note that this will throw an 'TargetException' because the specified property does not define a 'set' accessor type.PropertiesStatic["ExampleProperty"] = "Goodbye World"; // The safe version will handle any exceptions thrown when trying to access the property and return null if that is the case. propertyString = (string)type.SafePropertiesStatic["ExampleProperty"]; type.SafePropertiesStatic["ExampleProperty"] = propertyString; }
public void ExecuteCode() { /*try * {*/ robotManagementCode = GetRobotManagementClass(); ScriptDomain domain = ScriptDomain.CreateDomain("MyDomain"); ScriptType type = domain.CompileAndLoadMainSource(robotManagementCode); ScriptProxy proxy = type.CreateInstance(robot); Tuple <bool, string> result = (Tuple <bool, string>)proxy.Call("isTaskCompleted"); if (result.Item1) { UI.ResultField.text = "<color=green>Задание выполнено!</color>"; Canvas.GetComponent <TaskCompletingActions>().MakeActions(taskNumber); UI.CloseTaskButton.transform.localScale = new Vector3(0, 0, 0); } else { UI.ResultField.text = "Есть ошибки. Попробуй ещё раз!"; } UI.OutputField.text = result.Item2; //} /*catch * { * Debug.Log("Exception!!!"); * UI.ResultField.text = "Есть ошибки. Попробуй ещё раз!"; * }*/ }
/// <summary> /// Called by Unity. /// </summary> public void Start() { // Create domain domain = ScriptDomain.CreateDomain("Example Domain"); // We will be accessing the compiler service so make sure it is available // This is only a demonstration and passing 'true' to the 'CreateDomain' method will ensure that the compiler service is initialized if (domain.IsCompilerServiceInitialized == false) { throw new InvalidOperationException("Compiler service is not initialized"); } // Add a reference to 'System.Core' - 'HashSet<>' is defined in 'System.Core.dll' Assembly systemCoreAssembly = typeof(System.Collections.Generic.HashSet <>).Assembly; // Add a compiler reference domain.RoslynCompilerService.ReferenceAssemblies.Add(AssemblyReference.FromAssembly(systemCoreAssembly)); // Add a reference to an unloaded assembly via file path string referenceAssemblyPath = "path/to/reference/assembly.dll"; // Add a compiler reference domain.RoslynCompilerService.ReferenceAssemblies.Add(AssemblyReference.FromNameOrFile(referenceAssemblyPath)); }
/// <summary> /// Called by Unity. /// </summary> public IEnumerator Start() { // Create domain domain = ScriptDomain.CreateDomain("Example Domain"); // Compile and load code AsyncCompileOperation compileRequest = domain.CompileAndLoadSourceAsync(sourceCode, ScriptSecurityMode.UseSettings); // Wait for operation to complete yield return(compileRequest); // Check for compiler errors if (compileRequest.IsSuccessful == false) { // Get all errors foreach (CompilationError error in compileRequest.CompileDomain.CompileResult.Errors) { if (error.IsError == true) { Debug.LogError(error.ToString()); } else if (error.IsWarning == true) { Debug.LogWarning(error.ToString()); } } } }
/// <summary> /// Called by Unity. /// </summary> public void Start() { // Create domain domain = ScriptDomain.CreateDomain("Example Domain"); // Compile and load code - Note that we use 'CompileAndLoadMainSource' which is the same as 'CompileAndLoadSource' but returns the main type in the compiled assembly ScriptType type = domain.CompileAndLoadMainSource(sourceCode, ScriptSecurityMode.UseSettings); // Get the field value from a field with the name 'exampleField' and cast it to a string value // Note that only static fields can be accessed via a 'ScriptType' instance. A 'ScriptProxy' is required for instance fields string fieldString = (string)type.FieldsStatic["exampleField"]; // Check that the string we read has the expected value Debug.Log(fieldString == "Hello World"); // Set a field value with the name 'exampleField' // An exception may occur if the assigned type canot be implicitly converted to the actual field type type.FieldsStatic["exampleField"] = "Goodbye World"; // The safe version will handle any exceptions thrown when trying to access the field and return null if that is the case. fieldString = (string)type.SafeFieldsStatic["exampleField"]; type.SafeFieldsStatic["exampleField"] = fieldString; }
/// <summary> /// Called by Unity. /// </summary> public void Start() { // Create the domain domain = ScriptDomain.CreateDomain("MazeCrawlerCode", true); // Support netstandard try { IMetadataReferenceProvider reference = AssemblyReference.FromNameOrFile("netstandard"); if (reference.TryResolveReference() == true) { domain.RoslynCompilerService.ReferenceAssemblies.Add(reference); } } catch { } // Add assembly reference to Assembly-CSharp domain.RoslynCompilerService.ReferenceAssemblies.Add(AssemblyReference.FromAssembly(typeof(MazeCrawlerExample).Assembly)); domain.RoslynCompilerService.ReferenceAssemblies.Add(AssemblyReference.FromAssembly(typeof(UnityEngine.Object).Assembly)); domain.RoslynCompilerService.ReferenceAssemblies.Add(AssemblyReference.FromAssembly(typeof(Stack <>).Assembly)); domain.RoslynCompilerService.ReferenceAssemblies.Add(AssemblyReference.FromAssembly(typeof(HashSet <>).Assembly)); if (showCompletedCodeOnStartup == true) { // Load the solution code runCrawlerInput.text = mazeCodeSolution.text; } else { // Load the template code runCrawlerInput.text = mazeCodeTemplate.text; } }
/// <summary> /// Called by Unity. /// </summary> public void Start() { // Create domain domain = ScriptDomain.CreateDomain("Example Domain"); // Compile and load code - Note that we use 'CompileAndLoadMainSource' which is the same as 'CompileAndLoadSource' but returns the main type in the compiled assembly ScriptType type = domain.CompileAndLoadMainSource(sourceCode, ScriptSecurityMode.UseSettings); // Create an instance of 'Example' ScriptProxy proxy = type.CreateInstance(); // Create an instance of 'Example' using the overload constructor proxy = type.CreateInstance(); // Call the method called 'ExampleMethod' and pass the string argument 'World' // Note that any exceptions thrown by the target method will not be caught proxy.Call("ExampleMethod", "World"); // Call the method called 'ExampleMethod' and pass the string argument 'Safe World' // Note that any exceptions thrown by the target method will handled as indicated by the 'Safe' name proxy.SafeCall("ExampleMethod", "Safe World"); }
/// <summary> /// Called by Unity. /// </summary> public void Start() { // Create domain domain = ScriptDomain.CreateDomain("Example Domain"); // Add define symbols to compile code in different configurations domain.RoslynCompilerService.DefineSymbols.Add("DEBUG"); domain.RoslynCompilerService.DefineSymbols.Add("UNITY_EDITOR"); }
void Start() { // Create our domain domain = ScriptDomain.CreateDomain("EvalDomain", true); // Create our evaluator evaluator = new ScriptEvaluator(domain); // Add a using statement for UnityEngine. This will allow us ti access all types under the UnityEngine namespace evaluator.AddUsing("UnityEngine"); }
void Start() { // Should we enable the compiler for our domain // This is requried if we want to load C# scripts as opposed to assemblies bool initCompiler = true; // Create our domain domain = ScriptDomain.CreateDomain("ModDomain", initCompiler); if (domain == null) { Debug.LogError("Failed to create ScriptDomain"); } }
/// <summary> /// Called by Unity. /// </summary> public void Start() { // Create domain domain = ScriptDomain.CreateDomain("Example Domain"); // Security load mode // ScriptSecurityMode.EnsureLoad - Do not perform and code validation and just load the assembly // ScriptSecurityMode.EnsureSecurity - Perform full code validation and discard the assembly if verification fails // ScriptSecurityMode.UseSettings - Use the RoslynC# settings to determine which action to take ScriptSecurityMode securityMode = ScriptSecurityMode.UseSettings; // Load an assembly - The assembly may be verified using active security restriction depending upon the security mod specified // If an assembly fails verification then it will not be loaded and the load method will return null ScriptAssembly assembly = domain.LoadAssembly("path/to/assembly.dll", securityMode); }
/// <summary> /// Called by Unity. /// </summary> public void Start() { // Should the script domain initialize the roslyn compiler service. If this is disabled then you will not be able to compile C# code, only load managed assemblies. bool initCompiler = true; // Should the script domain be made active when created. The active domain can be accessed via 'ScriptDomain.Active' bool makeActiveDomain = true; // The app domain where all code should be loaded and executed. Note that you will need to manually handle domain assembly references // You can also pass null to 'CreateDomain' AppDomain appDomain = AppDomain.CurrentDomain; // Create a script domain. We use this domain to compile and load scripts and assemblies domain = ScriptDomain.CreateDomain("Example Domain", initCompiler, makeActiveDomain, appDomain); }
void Start() { // Should we enable the compiler for our domain // This is requried if we want to load C# scripts as opposed to assemblies bool initCompiler = true; // Create our domain domain = ScriptDomain.CreateDomain("ModDomain", initCompiler); // Load the source code into our domain // The code must be compiled before it can be loaded ScriptType type = domain.CompileAndLoadScriptSource(sourceCode); // Print the type to the console Debug.Log(type.ToString()); }
public IEnumerator RunAsync(string source, TextMeshProUGUI textUI, List <int> list, List <double> listD) { LoadingCircle.UpdateLoad(true); Debug.Log(source); ScriptDomain domain = ScriptDomain.CreateDomain("resposta"); AsyncCompileOperation compileRequest = domain.CompileAndLoadSourceAsync(source, ScriptSecurityMode.UseSettings); // Wait for operation to complete yield return(compileRequest); // Check for compiler errors if (compileRequest.IsSuccessful == false) { // Get all errors foreach (CompilationError error in compileRequest.CompileDomain.CompileResult.Errors) { if (error.IsError == true) { Debug.LogError(error.ToString()); textUI.text = error.ToString(); } else if (error.IsWarning == true) { Debug.LogWarning(error.ToString()); } } } else { type = compileRequest.CompiledType; proxy = type.CreateInstance(this.gameObject); proxy.Fields["_inputs"] = list; proxy.Fields["_Dinputs"] = listD; proxy.Call(initBlock.name); if ((string)proxy.Fields["_loopError"] != null) { textUI.text = (string)proxy.Fields["_loopError"]; } else { textUI.text = (string)proxy.Fields["_output"]; } } LoadingCircle.UpdateLoad(false); }
protected override void Dispose(bool disposing) { if (!IsDisposed) { try { lazyAssembly.Dispose(); scriptDomain = null; lazyAssembly = null; path = null; } finally { base.Dispose(disposing); } } }
void Start() { // Should we enable the compiler for our domain // This is requried if we want to load C# scripts as opposed to assemblies bool initCompiler = true; // Create our domain domain = ScriptDomain.CreateDomain("ModDomain", initCompiler); // Load the source code into our domain ScriptType type = domain.CompileAndLoadScriptSource(sourceCode); // Create an instance of our type ScriptProxy proxy = type.CreateInstance(); // Call the test method proxy.Call("TestMethod"); }
void Start() { // Should we enable the compiler for our domain // This is requried if we want to load C# scripts as opposed to assemblies bool initCompiler = true; // Create our domain domain = ScriptDomain.CreateDomain("ModDomain", initCompiler); // Load an assembly into our domain // This assumes that a file called 'ModAssembly.dll' is next to the game .exe file ScriptAssembly assembly = domain.LoadAssembly("ModAssembly.dll"); // List all types in the assembly foreach (ScriptType type in assembly.FindAllTypes()) { Debug.Log(type.ToString()); } }
// Methods /// <summary> /// Called by Unity. /// </summary> public void Awake() { GameObject.Find("ErrorShowLine").GetComponent <Image>().color = new Color(0, 0, 0, 0.3f); QualitySettings.vSyncCount = 0; Application.targetFrameRate = 30; stopObject.SetActive(false); //ctrManagerObject = tankObject.GetComponent<CtrManagerObject>(); //if(ScriptDomain.Active== null){ // Debug.Log("333333333333"); //} // Create our script domain domain = ScriptDomain.CreateDomain("ScriptDomain", true); // Find start positions startPosition = tankObject.transform.position; startRotation = tankObject.transform.rotation; // Add listener for new button CodeUI.onNewClicked += (CodeUI ui) => { //Debug.Log("ddddddddd"); // Load new file ui.codeEditor.text = Resources.Load <TextAsset>(newTemplate).text; }; // Add listener for example button CodeUI.onLoadClicked += (CodeUI ui) => { // Load example file ui.codeEditor.text = Resources.Load <TextAsset>(exampleTemplate).text; }; CodeUI.onCompileClicked += (CodeUI ui) => { //ctrManagerObject.mouseDrag = false; // Try to run the script RunTankScript(ui.codeEditor.text); }; }
/// <summary> /// Called by Unity. /// </summary> public void Start() { // Create domain domain = ScriptDomain.CreateDomain("Example Domain"); // Compile and load code - Note that we use 'CompileAndLoadMainSource' which is the same as 'CompileAndLoadSource' but returns the main type in the compiled assembly ScriptAssembly assembly = domain.CompileAndLoadSource(sourceCode, ScriptSecurityMode.UseSettings); // Find all types ScriptType type = assembly.FindType("Example"); ScriptType behaviourType = assembly.FindSubTypeOf <MonoBehaviour>("ExampleBehaviour"); ScriptType scriptableType = assembly.FindSubTypeOf <ScriptableObject>("ExampleScriptable"); // Create an instance of 'Example' ScriptProxy proxy = type.CreateInstance(); // Create an instance of 'Example' using the overload constructor proxy = type.CreateInstance(null, "Hello World"); // Create an instance of 'ExampleBehaviour' // Note that we need to pass a game object to attach the component to because it inherits from 'MonoBehaviour' // Failing to provide a valid game object will case the result to be null // Awake, OnEnable, Start and other Unity callbacks will be triggered as you would expect ScriptProxy behaviourProxy = behaviourType.CreateInstance(gameObject); // Both outputs will be 'true' Debug.Log(behaviourProxy.IsMonoBehaviour); Debug.Log(behaviourProxy.IsUnityObject); // Create an instance of 'ExampleScriptable' // this is much the same as creating a normal instance however it will be constructed using 'ScriptableObject.CreateInstance' because it inherits from 'ScriptableObject' ScriptProxy scriptableProxy = scriptableType.CreateInstance(); // Both outputs will be 'true' Debug.Log(scriptableType.IsScriptableObject); Debug.Log(scriptableType.IsUnityObject); }
/// <summary> /// Called by Unity. /// </summary> public IEnumerator Start() { // Create domain domain = ScriptDomain.CreateDomain("Example Domain"); // Security load mode // ScriptSecurityMode.EnsureLoad - Do not perform and code validation and just load the assembly // ScriptSecurityMode.EnsureSecurity - Perform full code validation and discard the assembly if verification fails // ScriptSecurityMode.UseSettings - Use the RoslynC# settings to determine which action to take ScriptSecurityMode securityMode = ScriptSecurityMode.UseSettings; // Load an assembly async - The assembly may be verified using active security restriction depending upon the security mod specified // If an assembly fails verification then it will not be loaded and the load operation will contain failure information AsyncLoadOperation assemblyLoad = domain.LoadAssemblyAsync("path/to/assembly.dll", securityMode); // Wait for request to complete yield return(assemblyLoad); // Get the loaded assembly - This will be null if the load or security validation failed ScriptAssembly assembly = assemblyLoad.LoadedAssembly; }
/// <summary> /// Called by Unity. /// </summary> public void Start() { // Create domain domain = ScriptDomain.CreateDomain("Example Domain"); // Compile and load code - Note that we use 'CompileAndLoadMainSource' which is the same as 'CompileAndLoadSource' but returns the main type in the compiled assembly ScriptAssembly assembly = domain.CompileAndLoadSource(sourceCode, ScriptSecurityMode.UseSettings); // Should the search include types or members that are private or internal bool includeNonPublic = true; // Find all types in the assembly foreach (ScriptType type in assembly.FindAllTypes(includeNonPublic)) { Debug.Log("FindAllTypes: " + type.FullName); } // Find all types in the assembly without allocating return arrays foreach (ScriptType type in assembly.EnumerateAllTypes(includeNonPublic)) { Debug.Log("EnumerateAllTypes: " + type.FullName); } // Find all types that inherit from a specified type foreach (ScriptType type in assembly.EnumerateAllSubTypesOf <MonoBehaviour>(includeNonPublic)) { Debug.Log("EnumerateSubTypesOf<MonoBehaviour>: " + type.FullName); } // Alternative shorthand for built in unity base types assembly.EnumerateAllMonoBehaviourTypes(includeNonPublic); assembly.EnumerateAllScriptableObjectTypes(includeNonPublic); // Find all unity types, ie: types that inherit from UnityEngine.Object assembly.EnumerateAllUnityTypes(includeNonPublic); }
void Start() { // Should we enable the compiler for our domain // This is required if we want to load C# scripts as opposed to assemblies. bool initCompiler = true; // Create our domain domain = ScriptDomain.CreateDomain("ModDomain", initCompiler); // Load the source code into our domain ScriptType type = domain.CompileAndLoadScriptSource(sourceCode); // Create an instance of our type - We need to pass a game object because 'Test' inherits from monobehaviour ScriptProxy proxy = type.CreateInstance(gameObject); // Coroutines are supported by default (true) but support can be disabled by specifying 'false' as the value. // Any method that returns 'IEnumerator' will be called as a coroutine. proxy.supportCoroutines = true; // Call the test method as a coroutine proxy.Call("TestMethod"); }
// Start is called before the first frame update IEnumerator Start() { ScriptDomain domain = ScriptDomain.CreateDomain("MyDomain", true); string source = ConnectionManager.ToCode(begin.GetComponent <RectTransform> ()) + "}}}"; string reference = "UnityEngine.dll"; using (UnityWebRequest uwr = UnityWebRequest.Get(Application.streamingAssetsPath + "/bin/Data/Managed" + "/" + reference)) { yield return(uwr.SendWebRequest()); if (uwr.isNetworkError || uwr.isHttpError) { Debug.Log("www error:" + uwr.error + " " + ("jar:file://" + Application.dataPath + "!/assets/" + reference)); } else { Debug.Log("1"); domain.RoslynCompilerService.ReferenceAssemblies.Add(AssemblyReference.FromImage(uwr.downloadHandler.data)); Debug.Log(uwr.downloadHandler.data); ScriptType type = domain.CompileAndLoadMainSource(source); } } }
public bool UpdateScript(Ship ship, StarSystem starSystem, string code) { if (domain != null) { domain.Dispose(); } domain = ScriptDomain.CreateDomain("ShipDomain", true); //domain.RoslynCompilerService.ReferenceAssemblies.Add(typeof(UnityEngine.Object).Assembly); //domain.RoslynCompilerService.ReferenceAssemblies.Add(typeof(Ship).Assembly); //domain.RoslynCompilerService.ReferenceAssemblies.Add(typeof(StarSystem).Assembly); //domain.RoslynCompilerService.ReferenceAssemblies.Add(typeof(LandableObject).Assembly); type = domain.CompileAndLoadMainSource(@code); if (proxy != null && !proxy.IsDisposed) { Debug.Log(proxy.IsDisposed); proxy.Dispose(); } Debug.Log(gameObject.name); Debug.Log(type.Name); proxy = type.CreateInstance(gameObject); Debug.Log(gameObject.name); if (type != null) { proxy.Fields["ship"] = ship; proxy.Fields["starSystem"] = starSystem; return(true); } else { return(false); } }
// Methods /// <summary> /// Called by Unity. /// </summary> public void Awake() { QualitySettings.vSyncCount = 0; Application.targetFrameRate = 30; //if(ScriptDomain.Active== null){ // Debug.Log("333333333333"); //} // Create our script domain domain = ScriptDomain.CreateDomain("ScriptDomain", true); // Find start positions startPosition = tankObject.transform.position; startRotation = tankObject.transform.rotation; // Add listener for new button CodeUI.onNewClicked += (CodeUI ui) => { Debug.Log("ddddddddd"); // Load new file ui.codeEditor.text = Resources.Load <TextAsset>(newTemplate).text; }; // Add listener for example button CodeUI.onLoadClicked += (CodeUI ui) => { // Load example file ui.codeEditor.text = Resources.Load <TextAsset>(exampleTemplate).text; }; CodeUI.onCompileClicked += (CodeUI ui) => { // Try to run the script RunTankScript(ui.codeEditor.text); }; }
/// <summary> /// Called by Unity. /// </summary> public void Start() { // Create the domain domain = ScriptDomain.CreateDomain("MazeCrawlerCode", true); // Add assembly references foreach (AssemblyReferenceAsset reference in assemblyReferences) { domain.RoslynCompilerService.ReferenceAssemblies.Add(reference); } if (showCompletedCodeOnStartup == true) { // Load the solution code runCrawlerInput.text = mazeCodeSolution.text; } else { // Load the template code runCrawlerInput.text = mazeCodeTemplate.text; } }
// interal ctor only internal ScriptAssembly(ScriptDomain container, IAssembly cciAssembly) { if (container == null || cciAssembly == null) throw new ArgumentNullException(); _container = container; _cciAssembly = cciAssembly; _id = GetKey(this); }
/// <summary> /// Parse domain element. /// </summary> /// <param name="domainEle">Domain element.</param> /// <param name="domainType">Domain type.</param> /// <param name="nsmgr">Xml name space manager.</param> /// <returns>Domain list.</returns> private static DomainConfigList ParseDomain(XmlElement domainEle, ScriptDomain domainType, XmlNamespaceManager nsmgr) { DomainConfigList domainList = new DomainConfigList(); domainList.Domain = domainType; XmlNode scriptsNode = domainEle.SelectSingleNode(@"tts:scripts", nsmgr); ParseScriptSection(scriptsNode, domainType, domainList.Items); if (domainEle.HasAttribute("sharedWithNormalDomain")) { domainList.SharedWithNormalDomain = bool.Parse(domainEle.GetAttribute("sharedWithNormalDomain")); } return domainList; }
/// <summary> /// Parse scripts element. /// </summary> /// <param name="scriptsNode">Xml node.</param> /// <param name="domainType">Domain type.</param> /// <param name="items">Script range items.</param> private static void ParseScriptSection(XmlNode scriptsNode, ScriptDomain domainType, Collection<ScriptRangeItem> items) { Debug.Assert(scriptsNode != null); Debug.Assert(items != null); foreach (XmlNode node in scriptsNode.ChildNodes) { XmlElement scriptEle = node as XmlElement; string startSentenceId = scriptEle.GetAttribute("from"); if (string.IsNullOrEmpty(startSentenceId)) { string message = Helper.NeutralFormat("Empty start sentence id"); throw new InvalidDataException(message); } string endSentenceId = scriptEle.GetAttribute("to"); if (string.IsNullOrEmpty(endSentenceId)) { string message = Helper.NeutralFormat("Empty end sentence id"); throw new InvalidDataException(message); } if (string.Compare(startSentenceId, endSentenceId, StringComparison.Ordinal) > 0) { string message = Helper.NeutralFormat("Start Sentence Id = [{0}] is not " + "less than End Sentence Id [{1}]", startSentenceId, endSentenceId); throw new InvalidDataException(message); } ScriptRangeItem item; item.StartSentenceId = startSentenceId; item.EndSentenceId = endSentenceId; item.Domain = domainType; items.Add(item); } }