public object Build( XmlUtilities.XmlModule moduleToBuild, out bool success) { var node = moduleToBuild.OwningNode; var xmlLocation = moduleToBuild.Locations[XmlUtilities.XmlModule.OutputFile]; var xmlPath = xmlLocation.GetSinglePath(); if (null == xmlPath) { throw new Bam.Core.Exception("XML output path was not set"); } // dependency checking { var outputFiles = new Bam.Core.StringArray(); outputFiles.Add(xmlPath); if (!RequiresBuilding(outputFiles, new Bam.Core.StringArray())) { Bam.Core.Log.DebugMessage("'{0}' is up-to-date", node.UniqueModuleName); success = true; return null; } } Bam.Core.Log.Info("Writing XML file '{0}'", xmlPath); // create all directories required var dirsToCreate = moduleToBuild.Locations.FilterByType(Bam.Core.ScaffoldLocation.ETypeHint.Directory, Bam.Core.Location.EExists.WillExist); foreach (var dir in dirsToCreate) { var dirPath = dir.GetSinglePath(); NativeBuilder.MakeDirectory(dirPath); } // serialize the XML to disk var settings = new System.Xml.XmlWriterSettings(); settings.CheckCharacters = true; settings.CloseOutput = true; settings.ConformanceLevel = System.Xml.ConformanceLevel.Auto; settings.Indent = true; settings.IndentChars = new string(' ', 4); settings.NewLineChars = "\n"; settings.NewLineHandling = System.Xml.NewLineHandling.None; settings.NewLineOnAttributes = false; settings.OmitXmlDeclaration = false; settings.Encoding = new System.Text.UTF8Encoding(false); // do not write BOM using (var xmlWriter = System.Xml.XmlWriter.Create(xmlPath, settings)) { moduleToBuild.Document.WriteTo(xmlWriter); xmlWriter.WriteWhitespace(settings.NewLineChars); } success = true; return null; }
public object Build( XmlUtilities.XmlModule moduleToBuild, out bool success) { var isPlist = moduleToBuild is XmlUtilities.OSXPlistModule; var locationMap = moduleToBuild.Locations; var outputDir = locationMap[XmlUtilities.OSXPlistModule.OutputDir]; var outputDirPath = outputDir.GetSingleRawPath(); if (!System.IO.Directory.Exists(outputDirPath)) { System.IO.Directory.CreateDirectory(outputDirPath); } var xmlFileLoc = locationMap[XmlUtilities.XmlModule.OutputFile]; var xmlFilePath = xmlFileLoc.GetSingleRawPath(); // write a script that can be invoked by the MakeFile to generate the XML file var shellScriptLeafName = isPlist ? "writePList.py" : "writeXMLFile.py"; var shellScriptLoc = Bam.Core.FileLocation.Get(outputDir, shellScriptLeafName, Bam.Core.Location.EExists.WillExist); var shellScriptPath = shellScriptLoc.GetSingleRawPath(); XmlUtilities.XmlDocumentToPythonScript.Write(moduleToBuild.Document, shellScriptPath, xmlFilePath); var node = moduleToBuild.OwningNode; var makeFile = new MakeFile(node, this.topLevelMakeFilePath); var dirsToCreate = moduleToBuild.Locations.FilterByType(Bam.Core.ScaffoldLocation.ETypeHint.Directory, Bam.Core.Location.EExists.WillExist); var recipe = new Bam.Core.StringArray(); recipe.Add(System.String.Format("$(shell python {0})", shellScriptPath)); var rule = new MakeFileRule( moduleToBuild, XmlUtilities.XmlModule.OutputFile, node.UniqueModuleName, dirsToCreate, null, null, recipe); rule.OutputLocationKeys = new Bam.Core.Array<Bam.Core.LocationKey>(XmlUtilities.XmlModule.OutputFile); makeFile.RuleArray.Add(rule); var makeFilePath = MakeFileBuilder.GetMakeFilePathName(node); System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(makeFilePath)); using (var makeFileWriter = new System.IO.StreamWriter(makeFilePath)) { makeFile.Write(makeFileWriter); } var exportedTargets = makeFile.ExportedTargets; var exportedVariables = makeFile.ExportedVariables; var returnData = new MakeFileData(makeFilePath, exportedTargets, exportedVariables, null); success = true; return returnData; }
public object Build( XmlUtilities.XmlModule moduleToBuild, out bool success) { var isPlist = moduleToBuild is XmlUtilities.OSXPlistModule; var node = moduleToBuild.OwningNode; var locationMap = moduleToBuild.Locations; var outputDir = locationMap[XmlUtilities.OSXPlistModule.OutputDir]; var outputDirPath = outputDir.GetSingleRawPath(); if (!System.IO.Directory.Exists(outputDirPath)) { System.IO.Directory.CreateDirectory(outputDirPath); } var outputXMLLoc = locationMap[XmlUtilities.XmlModule.OutputFile]; var outputXMLPath = outputXMLLoc.GetSingleRawPath(); var targetNode = node.ExternalDependents[0]; var targetData = targetNode.Data as QMakeData; // write a script that can be invoked by QMake to generate the XML file var shellScriptLeafName = isPlist ? "writePList.py" : "writeXMLFile.py"; var shellScriptLoc = Bam.Core.FileLocation.Get(outputDir, shellScriptLeafName, Bam.Core.Location.EExists.WillExist); var shellScriptPath = shellScriptLoc.GetSingleRawPath(); XmlUtilities.XmlDocumentToPythonScript.Write(moduleToBuild.Document, shellScriptPath, outputXMLPath); if (null == targetData.CustomRules) { targetData.CustomRules = new Bam.Core.StringArray(); } targetData.CustomRules.Add("xmlTarget.target=" + outputXMLPath); targetData.CustomRules.Add("xmlTarget.depends=FORCE"); targetData.CustomRules.Add("xmlTarget.commands=python " + shellScriptPath); targetData.CustomRules.Add("PRE_TARGETDEPS+=" + outputXMLPath); targetData.CustomRules.Add("QMAKE_EXTRA_TARGETS+=xmlTarget"); // TODO: the Plist file is not always copied - find out why if (isPlist) { // TODO: I'd rather this be an explicit option if (null == targetData.CustomRules) { targetData.CustomRules = new Bam.Core.StringArray(); } targetData.CustomRules.Add("QMAKE_INFO_PLIST=" + outputXMLPath); } success = true; return null; }
public object Build( XmlUtilities.TextFileModule moduleToBuild, out bool success) { var node = moduleToBuild.OwningNode; var outputLoc = moduleToBuild.Locations[XmlUtilities.TextFileModule.OutputFile]; var outputPath = outputLoc.GetSinglePath(); if (null == outputPath) { throw new Bam.Core.Exception("Text output path was not set"); } // dependency checking { var outputFiles = new Bam.Core.StringArray(); outputFiles.Add(outputPath); if (!RequiresBuilding(outputFiles, new Bam.Core.StringArray())) { Bam.Core.Log.DebugMessage("'{0}' is up-to-date", node.UniqueModuleName); success = true; return null; } } Bam.Core.Log.Info("Writing text file '{0}'", outputPath); // create all directories required var dirsToCreate = moduleToBuild.Locations.FilterByType(Bam.Core.ScaffoldLocation.ETypeHint.Directory, Bam.Core.Location.EExists.WillExist); foreach (var dir in dirsToCreate) { var dirPath = dir.GetSinglePath(); NativeBuilder.MakeDirectory(dirPath); } using (var writer = new System.IO.StreamWriter(outputPath, false, System.Text.Encoding.ASCII)) { var content = moduleToBuild.Content.ToString(); writer.Write(content); } success = true; return null; }
public object Build( XmlUtilities.TextFileModule moduleToBuild, out bool success) { var node = moduleToBuild.OwningNode; var targetNode = node.ExternalDependents[0]; var project = this.Workspace.GetProject(targetNode); var baseTarget = (Bam.Core.BaseTarget)targetNode.Target; var configuration = project.BuildConfigurations.Get(baseTarget.ConfigurationName('='), targetNode.ModuleName); var outputFileLoc = moduleToBuild.Locations[XmlUtilities.TextFileModule.OutputFile]; var outputFilePath = outputFileLoc.GetSingleRawPath(); var moduleName = node.ModuleName; var fileRef = project.FileReferences.Get(moduleName, PBXFileReference.EType.Text, outputFilePath, project.RootUri); var sourcesBuildPhase = project.SourceBuildPhases.Get("MiscSources", moduleName); var data = project.BuildFiles.Get(moduleName, fileRef, sourcesBuildPhase); if (null == data) { throw new Bam.Core.Exception("Build file not available"); } var content = moduleToBuild.Content.ToString(); string shellScriptName = "Writing text file for " + targetNode.UniqueModuleName; var shellScriptBuildPhase = project.ShellScriptBuildPhases.Get(shellScriptName, node.ModuleName); shellScriptBuildPhase.OutputPaths.Add(outputFilePath); shellScriptBuildPhase.ShellScriptLines.Add(System.String.Format("if [ \\\"${{CONFIGURATION}}\\\" = \\\"{0}\\\" ]; then", configuration.Name)); foreach (var line in content.Split('\n')) { var escapedLine = line.Replace("\"", "\\\""); shellScriptBuildPhase.ShellScriptLines.Add(System.String.Format("echo \\\"{0}\\\" >> $SCRIPT_OUTPUT_FILE_0", escapedLine)); } shellScriptBuildPhase.ShellScriptLines.Add("fi"); // is this a post action? { // because this is performed AFTER the application, we can directly add to the build phases var nativeTarget = targetNode.Data as PBXNativeTarget; nativeTarget.BuildPhases.Insert(0, shellScriptBuildPhase); } success = true; return data; }
public object Build( XmlUtilities.TextFileModule moduleToBuild, out bool success) { var node = moduleToBuild.OwningNode; var locationMap = moduleToBuild.Locations; var outputDir = locationMap[XmlUtilities.TextFileModule.OutputDir]; var outputDirPath = outputDir.GetSingleRawPath(); if (!System.IO.Directory.Exists(outputDirPath)) { System.IO.Directory.CreateDirectory(outputDirPath); } var outputFileLoc = locationMap[XmlUtilities.TextFileModule.OutputFile]; var outputFilePath = outputFileLoc.GetSingleRawPath(); var targetNode = node.ExternalDependents[0]; var targetData = targetNode.Data as QMakeData; // write a script that can be invoked by QMake to generate the text file var shellScriptLeafName = "writeTextFile.py"; var shellScriptLoc = Bam.Core.FileLocation.Get(outputDir, shellScriptLeafName, Bam.Core.Location.EExists.WillExist); var shellScriptPath = shellScriptLoc.GetSingleRawPath(); XmlUtilities.TextToPythonScript.Write(moduleToBuild.Content, shellScriptPath, outputFilePath); if (null == targetData.CustomRules) { targetData.CustomRules = new Bam.Core.StringArray(); } targetData.CustomRules.Add("writeTextFileTarget.target=" + outputFilePath.Replace('\\', '/')); targetData.CustomRules.Add("writeTextFileTarget.depends=FORCE"); targetData.CustomRules.Add("writeTextFileTarget.commands=python " + shellScriptPath.Replace('\\', '/')); targetData.CustomRules.Add("PRE_TARGETDEPS+=" + outputFilePath.Replace('\\', '/')); targetData.CustomRules.Add("QMAKE_EXTRA_TARGETS+=writeTextFileTarget"); success = true; return null; }
private void GetInternalDependencies(string dependencyPath) { var networkDependency = new NetworkDependency { name = AppodealDependencyUtils.GetConfigName(dependencyPath) }; #region iOSInternalDependencies var sourcesiOS = new List <string>(); string podName = null; string version = null; string minTargetSdk = null; XmlUtilities.ParseXmlTextFileElements(dependencyPath, (reader, elementName, isStart, parentElementName, elementNameStack) => { if (elementName == "dependencies" && parentElementName == "" || elementName == "iosPods" && (parentElementName == "dependencies" || parentElementName == "")) { return(true); } if (elementName == "iosPod" && parentElementName == "iosPods") { if (isStart) { podName = reader.GetAttribute("name"); version = reader.GetAttribute("version"); minTargetSdk = reader.GetAttribute("minTargetSdk"); sourcesiOS = new List <string>(); if (podName == null) { Debug.Log( $"Pod name not specified while reading {dependencyPath}:{reader.LineNumber}\n"); return(false); } } else { if (podName != null && version != null && minTargetSdk != null) { if (!podName.Contains(AppodealDependencyUtils.APDAppodealAdExchangeAdapter)) { networkDependency.ios_info = new NetworkDependency.iOSDependency(podName, version, AppodealDependencyUtils.GetiOSContent(dependencyPath)); } } } return(true); } if (elementName == "sources" && parentElementName == "iosPod") { return(true); } if (elementName == "sources" && parentElementName == "iosPods") { if (isStart) { sourcesiOS = new List <string>(); } else { using (var enumerator = sourcesiOS.GetEnumerator()) { while (enumerator.MoveNext()) { var current = enumerator.Current; Debug.Log(current); } } } return(true); } if (!(elementName == "source") || !(parentElementName == "sources")) { return(false); } if (isStart && reader.Read() && reader.NodeType == XmlNodeType.Text) { sourcesiOS.Add(reader.ReadContentAsString()); } return(true); }); #endregion #region AndroidInternalDependencies var sources = new List <string>(); string specName; XmlUtilities.ParseXmlTextFileElements(dependencyPath, (reader, elementName, isStart, parentElementName, elementNameStack) => { if (elementName == "dependencies" && parentElementName == "" || elementName == "androidPackages" && (parentElementName == "dependencies" || parentElementName == "")) { return(true); } if (elementName == "androidPackage" && parentElementName == "androidPackages") { if (isStart) { specName = reader.GetAttribute("spec"); sources = new List <string>(); if (specName == null) { Debug.Log( $"Pod name not specified while reading {dependencyPath}:{reader.LineNumber}\n"); return(false); } foreach (var s in new List <string> { "vast", "nast", "mraid", "appodealx", "appodeal" }) { if (!specName.Contains(s)) { if (specName.Contains(AppodealDependencyUtils.Replace_dependency_value)) { networkDependency.android_info = new NetworkDependency.AndroidDependency( AppodealDependencyUtils.GetAndroidDependencyName(specName), AppodealDependencyUtils.GetAndroidDependencyVersion(specName), AppodealDependencyUtils.GetAndroidContent(dependencyPath)); } else if (specName.Contains(AppodealDependencyUtils.Replace_dependency_core)) { networkDependency.android_info = new NetworkDependency.AndroidDependency( "appodeal", AppodealDependencyUtils.GetAndroidDependencyCoreVersion(specName), AppodealDependencyUtils.GetAndroidContent(dependencyPath)); } } else { return(false); } } } return(true); } if (elementName == "sources" && parentElementName == "androidPackage") { return(true); } if (elementName == "sources" && parentElementName == "androidPackages") { if (isStart) { sources = new List <string>(); } else { using (var enumerator = sources.GetEnumerator()) { while (enumerator.MoveNext()) { var current = enumerator.Current; Debug.Log(current); } } } return(true); } if (elementName != "source" || parentElementName != "sources") { return(false); } if (isStart && reader.Read() && reader.NodeType == XmlNodeType.Text) { sources.Add(reader.ReadContentAsString()); } return(true); }); #endregion if (!string.IsNullOrEmpty(networkDependency.name)) { internalDependencies.Add(networkDependency.name, networkDependency); } }
public object Build( XmlUtilities.XmlModule moduleToBuild, out bool success) { // TODO: might have to implement PList specific Build functions var isPList = moduleToBuild is XmlUtilities.OSXPlistModule; var node = moduleToBuild.OwningNode; var targetNode = node.ExternalDependents[0]; var project = this.Workspace.GetProject(targetNode); var baseTarget = (Bam.Core.BaseTarget)targetNode.Target; var configuration = project.BuildConfigurations.Get(baseTarget.ConfigurationName('='), targetNode.ModuleName); var xmlFileLoc = moduleToBuild.Locations[XmlUtilities.XmlModule.OutputFile]; var xmlFilePath = xmlFileLoc.GetSingleRawPath(); // serialize the XML to memory var settings = new System.Xml.XmlWriterSettings(); settings.CheckCharacters = true; settings.CloseOutput = true; settings.ConformanceLevel = System.Xml.ConformanceLevel.Auto; settings.Indent = true; settings.IndentChars = new string(' ', 4); settings.NewLineChars = "\n"; settings.NewLineHandling = System.Xml.NewLineHandling.None; settings.NewLineOnAttributes = false; settings.OmitXmlDeclaration = false; settings.Encoding = new System.Text.UTF8Encoding(false); // do not write BOM var xmlString = new System.Text.StringBuilder(); using (var xmlWriter = System.Xml.XmlWriter.Create(xmlString, settings)) { moduleToBuild.Document.WriteTo(xmlWriter); xmlWriter.WriteWhitespace(settings.NewLineChars); } string shellScriptName; if (isPList) { shellScriptName = "Writing PList for " + targetNode.UniqueModuleName; } else { shellScriptName = "Writing XML file for " + targetNode.UniqueModuleName; } var writeXMLShellScriptBuildPhase = project.ShellScriptBuildPhases.Get(shellScriptName, node.ModuleName); writeXMLShellScriptBuildPhase.OutputPaths.Add(xmlFilePath); writeXMLShellScriptBuildPhase.ShellScriptLines.Add(System.String.Format("if [ \\\"${{CONFIGURATION}}\\\" = \\\"{0}\\\" ]; then", configuration.Name)); foreach (var line in xmlString.ToString().Split('\n')) { var escapedLine = line.Replace("\"", "\\\""); writeXMLShellScriptBuildPhase.ShellScriptLines.Add(System.String.Format("echo \\\"{0}\\\" >> $SCRIPT_OUTPUT_FILE_0", escapedLine)); } writeXMLShellScriptBuildPhase.ShellScriptLines.Add("fi"); if (isPList) { // because this is performed AFTER the application, we can directly add to the build phases var nativeTarget = targetNode.Data as PBXNativeTarget; nativeTarget.BuildPhases.Insert(0, writeXMLShellScriptBuildPhase); // add the Info.plist into the FileReferences var fileRef = project.FileReferences.Get(targetNode.ModuleName, PBXFileReference.EType.PList, xmlFilePath, project.RootUri); nativeTarget.Group.Children.AddUnique(fileRef); // add to the build configuration var baseTarget2 = (Bam.Core.BaseTarget)moduleToBuild.OwningNode.Target; var buildConfiguration = project.BuildConfigurations.Get(baseTarget2.ConfigurationName('='), targetNode.ModuleName); buildConfiguration.Options["INFOPLIST_FILE"].AddUnique(xmlFilePath); } success = true; return null; }
//---------------------------------------------------------------------------------------// public override ExperimentResultInfo Execute(ExperimentSpecification experimentSpecification) { const string STRLOG_MethodName = "Execute"; Logfile.WriteCalled(STRLOG_ClassName, STRLOG_MethodName); // // Determine how long it actually take to execute // DateTime startDateTime = DateTime.Now; // Typecast the specification so that it can be used here Specification specification = (Specification)experimentSpecification; // // Log the specification // string logMessage = STRLOG_SetupId + specification.SetupId; Logfile.Write(logMessage); // // Create an instance of the result info ready to fill in // ResultInfo resultInfo = new ResultInfo(); resultInfo.statusCode = StatusCodes.Running; // // Initialise variables used in the state machine // try { // // First, check to see if the LabEquipment is online // LabEquipmentStatus labEquipmentStatus = this.equipmentServiceProxy.GetLabEquipmentStatus(); if (labEquipmentStatus.online == false) { throw new Exception(labEquipmentStatus.statusMessage); } // // Run the state machine to execute the experiment specification // States_Execute state = States_Execute.sCompleted; if (smTable_Execute.Length > 0) { state = smTable_Execute[0].currentState; } while (state != States_Execute.sCompleted) { // // Find table entry // int index = -1; for (int i = 0; i < smTable_Execute.Length; i++) { if (smTable_Execute[i].currentState == state) { // Entry found index = i; break; } } if (index == -1) { throw new ArgumentOutOfRangeException(state.ToString(), STRERR_StateNotFound); } // // Get table entry and save next state // SMTableEntry_Execute entry = smTable_Execute[index]; States_Execute nextState = entry.nextState; logMessage = " [ " + STRLOG_MethodName + ": " + entry.currentState.ToString() + " ]"; Logfile.Write(logMessage); Trace.WriteLine(logMessage); // // Check if experiment was cancelled // if (this.cancelExperiment != null && this.cancelExperiment.IsCancelled == true && resultInfo.statusCode == StatusCodes.Running) { // // Experiment was cancelled // resultInfo.statusCode = StatusCodes.Cancelled; state = entry.exitState; continue; } // // Process non-XML commands // switch (entry.currentState) { case States_Execute.sSuspendPowerdown: if (this.equipmentServiceProxy.SuspendPowerdown() == false) { // // Command execution failed // resultInfo.statusCode = StatusCodes.Failed; resultInfo.errorMessage = STRERR_SuspendPowerdown; state = entry.exitState; } else { state = nextState; } continue; case States_Execute.sResumePowerdown: if (this.equipmentServiceProxy.ResumePowerdown() == false) { // // Command execution failed // resultInfo.statusCode = StatusCodes.Failed; resultInfo.errorMessage = STRERR_ResumePowerdown; state = entry.exitState; } else { state = nextState; } continue; default: break; } // // Add command arguments where required // switch (entry.currentState) { case States_Execute.sStartExecution: entry.commandArguments[0, 1] = specification.ToString(); break; default: break; } // // Execute command and check response success // XmlDocument xmlRequestDocument = CreateXmlRequestDocument(entry.equipmentCommand, entry.commandArguments); string xmlResponse = this.equipmentServiceProxy.ExecuteRequest(xmlRequestDocument.InnerXml); XmlNode xmlResponseNode = CreateXmlResponseNode(xmlResponse); if (XmlUtilities.GetBoolValue(xmlResponseNode, LabServerEngine.Consts.STRXML_RspSuccess, false) == false) { // // Command execution failed // resultInfo.statusCode = StatusCodes.Failed; resultInfo.errorMessage = XmlUtilities.GetXmlValue(xmlResponseNode, LabServerEngine.Consts.STRXML_RspErrorMessage, true); state = entry.exitState; continue; } // // Extract response values where required // switch (entry.currentState) { case States_Execute.sGetExecutionStatus: // // Get the execution status // string strExecutionStatus = XmlUtilities.GetXmlValue(xmlResponseNode, Consts.STRXML_RspExecutionStatus, false); Trace.WriteLine("ExecutionStatus: " + strExecutionStatus); // // Get the execution time remaining // int executionTimeRemaining = XmlUtilities.GetIntValue(xmlResponseNode, Consts.STRXML_RspExecutionTimeRemaining, -1); Trace.WriteLine("ExecutionTimeRemaining: " + executionTimeRemaining.ToString()); // // Convert to an ExecutionStatus enum type // ExecutionStatus executionStatus = (ExecutionStatus)Enum.Parse(typeof(ExecutionStatus), strExecutionStatus); // // Check if execution has completed // if (executionStatus != ExecutionStatus.Completed) { // // Not yet, wait a bit and then check again // int secondsToWait = 1; if (executionTimeRemaining > 40) { secondsToWait = 20; } else if (executionTimeRemaining > 5) { secondsToWait = executionTimeRemaining / 2; } else { secondsToWait = 2; } for (int i = 0; i < secondsToWait; i++) { Trace.Write("."); Thread.Sleep(1000); } nextState = States_Execute.sGetExecutionStatus; } break; case States_Execute.sGetExecutionResultStatus: // // Get the execution result status // string strExecutionResultStatus = XmlUtilities.GetXmlValue(xmlResponseNode, Consts.STRXML_RspExecutionResultStatus, false); Trace.WriteLine("ExecutionResultStatus: " + strExecutionResultStatus); // // Convert to an ExecutionStatus enum type // ExecutionStatus executionResultStatus = (ExecutionStatus)Enum.Parse(typeof(ExecutionStatus), strExecutionResultStatus); // // Check if results are available // if (executionResultStatus != ExecutionStatus.Completed) { resultInfo.statusCode = StatusCodes.Failed; //resultInfo.errorMessage = ; } break; case States_Execute.sGetExecutionResults: // // Get the execution results // resultInfo.xmlMeasurements = XmlUtilities.GetXmlValue(xmlResponseNode, Consts.STRXML_RspExecutionResults, false); Trace.WriteLine("ExecutionResults: " + resultInfo.xmlMeasurements); break; default: break; } // // Next state // state = nextState; } // // Update status code // if (resultInfo.statusCode == StatusCodes.Running) { resultInfo.statusCode = StatusCodes.Completed; } } catch (Exception ex) { resultInfo.statusCode = StatusCodes.Failed; resultInfo.errorMessage = ex.Message; Logfile.WriteError(ex.Message); } // // Calculate actual execution time // TimeSpan timeSpan = DateTime.Now - startDateTime; logMessage = STRLOG_StatusCode + resultInfo.statusCode + Logfile.STRLOG_Spacer + STRLOG_ExecutionTime + timeSpan.TotalSeconds.ToString(); Logfile.WriteCompleted(STRLOG_ClassName, STRLOG_MethodName, logMessage); return(resultInfo); }
//-------------------------------------------------------------------------------------------------// /// <summary> /// Parse the XML specification string to check its validity. No exceptions are thrown back to the /// calling method. If an error occurs, 'accepted' is set to false and the error message is placed /// in 'errorMessage' where it can be examined by the calling method. Return 'accepted'. /// </summary> /// <param name="xmlSpecification"></param> public virtual ValidationReport Parse(string xmlSpecification) { const string STRLOG_MethodName = "Parse"; Logfile.WriteCalled(STRLOG_ClassName, STRLOG_MethodName); // // Create a new validation report ready to fill in // ValidationReport validationReport = new ValidationReport(); // // Process the XML specification string // try { // Load XML specification string XmlDocument xmlDocument = XmlUtilities.GetXmlDocument(xmlSpecification); // // Get a copy of the specification XML node // XmlNode xmlNode = XmlUtilities.GetXmlRootNode(xmlDocument, Consts.STRXML_experimentSpecification); this.xmlNodeSpecification = xmlNode.Clone(); // // Get the setup id and check that it exists - search is case-sensitive // this.setupId = XmlUtilities.GetXmlValue(this.xmlNodeSpecification, Consts.STRXML_setupId, false); int setupIndex = Array.IndexOf(this.labConfiguration.SetupIds, this.setupId); if (setupIndex < 0) { throw new ArgumentException(STRERR_SetupIdInvalid, this.setupId); } // // Get the specified setup XML node // XmlNodeList xmlNodeList = XmlUtilities.GetXmlNodeList(this.xmlNodeConfiguration, Consts.STRXML_setup, true); this.xmlNodeSetup = xmlNodeList.Item(setupIndex); // // Create an instance of the driver for the specified setup and then // get the driver's execution time for this specification // int executionTime = -1; if (this.SetupId.Equals(Consts.STRXML_SetupId_EquipmentGeneric)) { if (this.equipmentServiceProxy == null) { throw new ArgumentException(STRERR_EquipmentServiceNotAvailable, this.setupId); } DriverEquipmentGeneric driver = new DriverEquipmentGeneric(this.equipmentServiceProxy, this.labConfiguration); executionTime = driver.GetExecutionTime(this); } else if (this.SetupId.Equals(Consts.STRXML_SetupId_ModuleGeneric)) { DriverModuleGeneric driver = new DriverModuleGeneric(this.labConfiguration); executionTime = driver.GetExecutionTime(this); } // // Specification is valid // validationReport.estRuntime = executionTime; validationReport.accepted = true; } catch (Exception ex) { validationReport.errorMessage = ex.Message; } Logfile.WriteCompleted(STRLOG_ClassName, STRLOG_MethodName); return(validationReport); }
internal override void ReadCurrentElement(XmlReader reader, IWidget parent) { base.ReadCurrentElement(reader, parent); if (reader.GetAttribute("anchorMin") != null || reader.GetAttribute("anchorMax") != null) { Vector2 anchorMin = XmlUtilities.ToVector2(reader.GetAttribute("anchorMin")); Vector2 anchorMax = XmlUtilities.ToVector2(reader.GetAttribute("anchorMax")); SetAnchor(anchorMin, anchorMax); } string layoutstr = reader.GetAttribute("layout"); Direction dir = Direction.Horizontal; SetLayout(layoutstr); switch (layoutstr) { case "grid": if (reader.GetAttribute("gridX") != null) { (layout as GridLayoutGroup).constraint = GridLayoutGroup.Constraint.FixedRowCount; (layout as GridLayoutGroup).constraintCount = Convert.ToInt32(reader.GetAttribute("gridX")); } else if (reader.GetAttribute("gridY") != null) { (layout as GridLayoutGroup).constraint = GridLayoutGroup.Constraint.FixedColumnCount; (layout as GridLayoutGroup).constraintCount = Convert.ToInt32(reader.GetAttribute("gridY")); } if (reader.GetAttribute("cellSize") != null) { Vector2 cellSize = XmlUtilities.ToVector2(reader.GetAttribute("cellSize")); (layout as GridLayoutGroup).cellSize = cellSize; } break; case "horizontal": dir = Direction.Horizontal; break; case "vertical": dir = Direction.Vertical; break; } string childBehaviour = reader.GetAttribute("child"); if (childBehaviour != null) { string[] s = childBehaviour.Split(','); SetChildExpand(s[0], Direction.Horizontal); SetChildExpand(s[1], Direction.Vertical); } string contentPolicy = reader.GetAttribute("content"); if (contentPolicy == null) { } else if (contentPolicy.Split(',').Length == 2) { AddContentSizeFitter(ToFitMode(contentPolicy.Split(',')[0]), Direction.Horizontal); AddContentSizeFitter(ToFitMode(contentPolicy.Split(',')[1]), Direction.Vertical); } else { switch (contentPolicy) { case "minFit": AddContentSizeFitter(ContentSizeFitter.FitMode.MinSize); break; case "preferredFit": AddContentSizeFitter(ContentSizeFitter.FitMode.PreferredSize, dir); break; case "expand": SetChildExpand(true); break; default: break; } } if (reader.GetAttribute("margin") != null) { SetMargin(Convert.ToInt32(reader.GetAttribute("margin"))); } if (reader.GetAttribute("padding") != null) { int[] padding = XmlUtilities.ToIntArray(reader.GetAttribute("padding")); SetPadding(padding); } if (reader.GetAttribute("offset") != null) { float[] padding = XmlUtilities.ToFloatArray(reader.GetAttribute("offset")); SetSize(padding); } }
//---------------------------------------------------------------------------------------// public override ExperimentResultInfo Execute(ExperimentSpecification experimentSpecification) { const string STRLOG_MethodName = "Execute"; Logfile.WriteCalled(STRLOG_ClassName, STRLOG_MethodName); // // Determine how long it actually take to execute // DateTime startDateTime = DateTime.Now; // Typecast the specification so that it can be used here Specification specification = (Specification)experimentSpecification; // // Log the specification // string logMessage = string.Empty; //Logfile.Write(logMessage); // // Create an instance of the result info ready to fill in // ResultInfo resultInfo = new ResultInfo(); resultInfo.statusCode = StatusCodes.Running; // // Initialise variables used in the state machine // int repeatCount = 0; try { // // First, check to see if the LabEquipment is online // LabEquipmentStatus labEquipmentStatus = this.equipmentServiceProxy.GetLabEquipmentStatus(); if (labEquipmentStatus.online == false) { throw new Exception(labEquipmentStatus.statusMessage); } // // Run the state machine to execute the experiment specification // States_Execute state = States_Execute.sCompleted; if (smTable_Execute.Length > 0) { state = smTable_Execute[0].currentState; } while (state != States_Execute.sCompleted) { // // Find table entry // int index = -1; for (int i = 0; i < smTable_Execute.Length; i++) { if (smTable_Execute[i].currentState == state) { // Entry found index = i; break; } } if (index == -1) { throw new ArgumentOutOfRangeException(state.ToString(), STRERR_StateNotFound); } // // Get table entry and save next state // SMTableEntry_Execute entry = smTable_Execute[index]; States_Execute nextState = entry.nextState; logMessage = " [ " + STRLOG_MethodName + ": " + entry.currentState.ToString() + " ]"; Logfile.Write(logMessage); Trace.WriteLine(logMessage); // // Check if experiment was cancelled // if (this.cancelExperiment != null && this.cancelExperiment.IsCancelled == true && resultInfo.statusCode == StatusCodes.Running) { // // Experiment was cancelled // resultInfo.statusCode = StatusCodes.Cancelled; state = entry.exitState; continue; } // // Process non-XML commands // switch (entry.currentState) { case States_Execute.sSuspendPowerdown: if (this.equipmentServiceProxy.SuspendPowerdown() == false) { // // Command execution failed // resultInfo.statusCode = StatusCodes.Failed; resultInfo.errorMessage = STRERR_SuspendPowerdown; state = entry.exitState; } else { state = nextState; } continue; case States_Execute.sResumePowerdown: if (this.equipmentServiceProxy.ResumePowerdown() == false) { // // Command execution failed // resultInfo.statusCode = StatusCodes.Failed; resultInfo.errorMessage = STRERR_ResumePowerdown; state = entry.exitState; } else { state = nextState; } continue; default: break; } // // Add command arguments where required // switch (entry.currentState) { // // Nothing to do here // default: break; } // // Execute command and check response success // XmlDocument xmlRequestDocument = CreateXmlRequestDocument(entry.equipmentCommand, entry.commandArguments); string xmlResponse = this.equipmentServiceProxy.ExecuteRequest(xmlRequestDocument.InnerXml); XmlNode xmlResponseNode = CreateXmlResponseNode(xmlResponse); if (XmlUtilities.GetBoolValue(xmlResponseNode, LabServerEngine.Consts.STRXML_RspSuccess, false) == false) { // // Command execution failed // resultInfo.statusCode = StatusCodes.Failed; resultInfo.errorMessage = XmlUtilities.GetXmlValue(xmlResponseNode, LabServerEngine.Consts.STRXML_RspErrorMessage, true); state = entry.exitState; continue; } // // Extract response values where required // switch (entry.currentState) { case States_Execute.sTakeMeasurement: // // Add in the values // resultInfo.voltage += (float)XmlUtilities.GetRealValue(xmlResponseNode, Consts.STRXML_RspVoltageMut, 0.0); resultInfo.current += (float)XmlUtilities.GetRealValue(xmlResponseNode, Consts.STRXML_RspCurrentMut, 0.0); resultInfo.powerFactor += (float)XmlUtilities.GetRealValue(xmlResponseNode, Consts.STRXML_RspPowerFactorMut, 0.0); resultInfo.speed += XmlUtilities.GetIntValue(xmlResponseNode, Consts.STRXML_RspSpeed, 0); resultInfo.torque += XmlUtilities.GetIntValue(xmlResponseNode, Consts.STRXML_RspTorque, 0); // // Check if all measurements have been taken // if (++repeatCount == this.measurementCount) { // // All measurements taken, average the values // resultInfo.voltage /= this.measurementCount; resultInfo.current /= this.measurementCount; resultInfo.powerFactor /= this.measurementCount; resultInfo.speed /= this.measurementCount; resultInfo.torque /= this.measurementCount; break; } // Next measurement nextState = States_Execute.sTakeMeasurement; break; default: break; } // // Next state // state = nextState; } // // Update status code // if (resultInfo.statusCode == StatusCodes.Running) { resultInfo.statusCode = StatusCodes.Completed; } } catch (Exception ex) { resultInfo.statusCode = StatusCodes.Failed; resultInfo.errorMessage = ex.Message; Logfile.WriteError(ex.Message); } // // Calculate actual execution time // TimeSpan timeSpan = DateTime.Now - startDateTime; logMessage = STRLOG_StatusCode + resultInfo.statusCode + Logfile.STRLOG_Spacer + STRLOG_ExecutionTime + timeSpan.TotalSeconds.ToString(); Logfile.WriteCompleted(STRLOG_ClassName, STRLOG_MethodName, logMessage); return(resultInfo); }
/// <summary>Load script</summary> /// <param name="node">The manager node to read from</param> public void Read(XmlNode node) { XmlCDataSection codeNode = XmlUtilities.Find(node, "Code").ChildNodes[0] as XmlCDataSection; Read(codeNode.InnerText); }
public static List <EndpointInfo> GetEndPoints() { return(XmlUtilities.Serilize <List <EndpointInfo> >(r_FilePath)); }
public PlayerParserException(Exception inner, XmlNode playerNode) : base($"Player XML:\n\n{XmlUtilities.BeautifyXml(playerNode)}\n\n", inner) { }
/// <summary> /// Convert an XML parameter array into a series of commands. /// </summary> /// <param name="parentNode">The XML parameter node.</param> /// <param name="parameterName">The name of the XML child parameter.</param> /// <param name="animalParamName">The name of a GrazPlan parameter.</param> /// <param name="commands">The list of comamnds to add to.</param> /// <param name="numValuesInArray">The number of values that should be in the array.</param> private static void ConvertArrayToCommands(XmlNode parentNode, string parameterName, string animalParamName, List <PropertyReplacement> commands, int numValuesInArray) { var parameterNode = FindChildWithPrefix(parentNode, parameterName); if (parameterNode != null) { var stringValue = parameterNode.InnerText; bool hasMissingValues = stringValue.StartsWith(",") || stringValue.EndsWith(",") || stringValue.Contains(",,"); if (hasMissingValues) { var values = stringValue.Split(','); for (int i = 0; i != values.Length; i++) { if (values[i] != string.Empty) { if (animalParamName == "IntakeLactC") { if (i == 0) { commands.Add(new PropertyReplacement($"FDairyIntakePeak", values[i])); } else { commands.Add(new PropertyReplacement($"{animalParamName}[{i + 1}]", values[i])); } } else { commands.Add(new PropertyReplacement($"{animalParamName}[{i + 2}]", values[i])); // 1 based array indexing before equals sign. } } } } else { // See if an index was specified as part of the parameter name. var nodeName = XmlUtilities.Attribute(parameterNode, "name"); if (nodeName != parameterName) { // There must be an index specified e.g. c-w-0 var index = Convert.ToInt32(nodeName.Replace(parameterName, "")); commands.Add(new PropertyReplacement($"{animalParamName}[{index + 1}]", stringValue)); // 1 based array indexing before equals sign. } else { // Determine if we need to add another value to the top of the values list // so that the number of values matches the array length definition in the animprm.cs code. var values = stringValue.Split(','); if (values.Length != numValuesInArray) { // Add a zero to the top of the list of values. var valuesList = new List <string>(values); valuesList.Insert(0, "0"); values = valuesList.ToArray(); } // We build the string value. stringValue = StringUtilities.BuildString(values, ","); // Create the command. commands.Add(new PropertyReplacement(animalParamName, stringValue)); } } } }
public ServiceComponents(string cloudConfiguration) { Validate.ValidateFileFull(cloudConfiguration, Resources.ServiceConfiguration); CloudConfig = XmlUtilities.DeserializeXmlFile <ServiceConfiguration>(cloudConfiguration); }
/// <summary> /// Shows completion information for a method call. /// </summary> /// <param name="relativeTo">Model to be used as a reference when searching for completion data.</param> /// <param name="code">Code for which we want to generate completion data.</param> /// <param name="offset">Offset of the cursor/caret in the code.</param> public void ShowScriptMethodCompletion(IModel relativeTo, string code, int offset, Point location) { CSharpParser parser = new CSharpParser(); SyntaxTree syntaxTree = parser.Parse(code); string fileName = Path.GetTempFileName(); File.WriteAllText(fileName, code); syntaxTree.FileName = fileName; syntaxTree.Freeze(); IDocument document = new ReadOnlyDocument(new StringTextSource(code), syntaxTree.FileName); CodeCompletionResult result = completion.GetMethodCompletion(document, offset, false); File.Delete(fileName); if (result.OverloadProvider != null) { if (result.OverloadProvider.Count < 1) { return; } List <MethodCompletion> completions = new List <MethodCompletion>(); foreach (IParameterizedMember method in result.OverloadProvider.Items.Select(x => x.Method)) { // Generate argument signatures - e.g. string foo, int bar List <string> arguments = new List <string>(); foreach (var parameter in method.Parameters) { string parameterString = string.Format("{0} {1}", parameter.Type.Name, parameter.Name); if (parameter.ConstantValue != null) { parameterString += string.Format(" = {0}", parameter.ConstantValue.ToString()); } arguments.Add(parameterString); } MethodCompletion completion = new MethodCompletion() { Signature = string.Format("{0} {1}({2})", method.ReturnType.Name, method.Name, arguments.Any() ? arguments.Aggregate((x, y) => string.Format("{0}, {1}", x, y)) : string.Empty) }; if (method.Documentation == null) { completion.Summary = string.Empty; completion.ParameterDocumentation = string.Empty; } else { if (method.Documentation.Xml.Text.Contains("<summary>") && method.Documentation.Xml.Text.Contains("</summary>")) { completion.Summary = method.Documentation.Xml.Text.Substring(0, method.Documentation.Xml.Text.IndexOf("</summary")).Replace("<summary>", string.Empty).Trim(Environment.NewLine.ToCharArray()).Trim(); } else { completion.Summary = string.Empty; } // NRefactory doesn't do anything more than read the xml documentation file. // Therefore, we need to parse this XML to get the parameter summaries. XmlDocument doc = new XmlDocument(); doc.LoadXml(string.Format("<documentation>{0}</documentation>", method.Documentation.Xml.Text)); List <string> argumentSummariesList = new List <string>(); foreach (XmlElement parameter in XmlUtilities.ChildNodesRecursively(doc.FirstChild, "param")) { argumentSummariesList.Add(string.Format("{0}: {1}", parameter.GetAttribute("name"), parameter.InnerText)); } if (argumentSummariesList.Any()) { completion.ParameterDocumentation = argumentSummariesList.Aggregate((x, y) => x + Environment.NewLine + y); } else { completion.ParameterDocumentation = string.Empty; } } completions.Add(completion); } methodCompletionView.Completions = completions; methodCompletionView.Location = location; methodCompletionView.Visible = true; } }
//-------------------------------------------------------------------------------------------------// public override int GetExecutionTime(ExperimentSpecification experimentSpecification) { const string STRLOG_MethodName = "GetExecutionTime"; Logfile.WriteCalled(STRLOG_ClassName, STRLOG_MethodName); // Typecast the specification so that it can be used here Specification specification = (Specification)experimentSpecification; // // Log the specification // string strDistanceList = null; for (int i = 0; i < specification.DistanceList.Length; i++) { if (i > 0) { strDistanceList += Consts.CHR_CsvSplitter.ToString(); } strDistanceList += specification.DistanceList[i].ToString(); } string logMessage = STRLOG_Distance + strDistanceList; logMessage += Logfile.STRLOG_Spacer + STRLOG_Duration + specification.Duration.ToString(); logMessage += Logfile.STRLOG_Spacer + STRLOG_Repeat + specification.Repeat.ToString(); Logfile.Write(logMessage); // // Initialise variables used in the state machine // double executionTime = 0.0; double lcdWriteLineTime = 0.0; int tubeHomeDistance = 0; int distanceIndex = 0; try { // // First, check to see if the LabEquipment is online // LabEquipmentStatus labEquipmentStatus = this.equipmentServiceProxy.GetLabEquipmentStatus(); if (labEquipmentStatus.online == false) { throw new Exception(labEquipmentStatus.statusMessage); } // // Get the time until the LabEquipment is ready to use // executionTime = this.equipmentServiceProxy.GetTimeUntilReady(); // // Run the state machine to determine the execution time for the experiment specification // States_GetExecutionTime state = States_GetExecutionTime.sCompleted; if (smTable_GetExecutionTime.Length > 0) { state = smTable_GetExecutionTime[0].currentState; } while (state != States_GetExecutionTime.sCompleted) { // // Find table entry // int index = -1; for (int i = 0; i < smTable_GetExecutionTime.Length; i++) { if (smTable_GetExecutionTime[i].currentState == state) { // Entry found index = i; break; } } if (index == -1) { throw new ArgumentOutOfRangeException(state.ToString(), "State not found!"); } // // Get table entry and save next state // SMTableEntry_GetExecutionTime entry = smTable_GetExecutionTime[index]; States_GetExecutionTime nextState = entry.nextState; Trace.Write(" [ " + entry.currentState.ToString() + ": " + entry.currentState.ToString()); // // Add command arguments where required // switch (entry.currentState) { case States_GetExecutionTime.sGetAbsorberSelectTime: entry.commandArguments[0, 1] = specification.AbsorberList[0].location.ToString(); break; case States_GetExecutionTime.sGetSourceSelectTime: entry.commandArguments[0, 1] = specification.SourceLocation.ToString(); break; case States_GetExecutionTime.sGetTubeMoveTime: if (distanceIndex == 0) { // From home to first distance entry.commandArguments[0, 1] = tubeHomeDistance.ToString(); entry.commandArguments[1, 1] = specification.DistanceList[distanceIndex].ToString(); } else if (distanceIndex < specification.DistanceList.Length) { // Everything in between entry.commandArguments[0, 1] = specification.DistanceList[distanceIndex - 1].ToString(); entry.commandArguments[1, 1] = specification.DistanceList[distanceIndex].ToString(); } break; case States_GetExecutionTime.sGetCaptureDataTime: entry.commandArguments[0, 1] = specification.Duration.ToString(); break; case States_GetExecutionTime.sGetSourceReturnTime: entry.commandArguments[0, 1] = specification.SourceLocation.ToString(); break; case States_GetExecutionTime.sGetAbsorberReturnTime: entry.commandArguments[0, 1] = specification.AbsorberList[0].location.ToString(); break; case States_GetExecutionTime.sGetTubeReturnTime: entry.commandArguments[0, 1] = specification.DistanceList[specification.DistanceList.Length - 1].ToString(); entry.commandArguments[1, 1] = tubeHomeDistance.ToString(); break; default: break; } // // Execute command and check response success // XmlDocument xmlRequestDocument = CreateXmlRequestDocument(entry.equipmentCommand, entry.commandArguments); string xmlResponse = this.equipmentServiceProxy.ExecuteRequest(xmlRequestDocument.InnerXml); XmlNode xmlResponseNode = CreateXmlResponseNode(xmlResponse); if (XmlUtilities.GetBoolValue(xmlResponseNode, LabServerEngine.Consts.STRXML_RspSuccess, false) == false) { // // Command execution failed // string errorMessage = XmlUtilities.GetXmlValue(xmlResponseNode, LabServerEngine.Consts.STRXML_RspErrorMessage, true); throw new ArgumentException(errorMessage); } // // Extract response values where required // double stateExecutionTime = 0.0; switch (entry.currentState) { case States_GetExecutionTime.sGetLcdWriteLineTime: lcdWriteLineTime = XmlUtilities.GetRealValue(xmlResponseNode, Consts.STRXML_RspLcdWriteLineTime, 0); // Time to ready LCD when completed stateExecutionTime = lcdWriteLineTime * 2; break; case States_GetExecutionTime.sGetAbsorberSelectTime: stateExecutionTime = XmlUtilities.GetRealValue(xmlResponseNode, Consts.STRXML_RspAbsorberSelectTime, 0.0); stateExecutionTime += lcdWriteLineTime * 2; break; case States_GetExecutionTime.sGetSourceSelectTime: stateExecutionTime = XmlUtilities.GetRealValue(xmlResponseNode, Consts.STRXML_RspSourceSelectTime, 0.0); stateExecutionTime += lcdWriteLineTime * 2; break; case States_GetExecutionTime.sGetTubeHomeDistance: tubeHomeDistance = XmlUtilities.GetIntValue(xmlResponseNode, Consts.STRXML_RspTubeHomeDistance, 0); break; case States_GetExecutionTime.sGetTubeMoveTime: stateExecutionTime = XmlUtilities.GetRealValue(xmlResponseNode, Consts.STRXML_RspTubeMoveTime, 0.0); stateExecutionTime += lcdWriteLineTime * 2; break; case States_GetExecutionTime.sGetCaptureDataTime: stateExecutionTime = XmlUtilities.GetRealValue(xmlResponseNode, Consts.STRXML_RspCaptureDataTime, 0.0); stateExecutionTime += lcdWriteLineTime * 2; stateExecutionTime *= specification.Repeat; if (++distanceIndex < specification.DistanceList.Length) { // Next distance nextState = States_GetExecutionTime.sGetTubeMoveTime; } break; case States_GetExecutionTime.sGetSourceReturnTime: stateExecutionTime = XmlUtilities.GetRealValue(xmlResponseNode, Consts.STRXML_RspSourceReturnTime, 0.0); stateExecutionTime += lcdWriteLineTime * 2; break; case States_GetExecutionTime.sGetAbsorberReturnTime: stateExecutionTime = XmlUtilities.GetRealValue(xmlResponseNode, Consts.STRXML_RspAbsorberReturnTime, 0.0); stateExecutionTime += lcdWriteLineTime * 2; break; case States_GetExecutionTime.sGetTubeReturnTime: stateExecutionTime = XmlUtilities.GetRealValue(xmlResponseNode, Consts.STRXML_RspTubeMoveTime, 0.0); stateExecutionTime += lcdWriteLineTime * 2; break; default: break; } Trace.WriteLine(" nextState: " + entry.nextState.ToString() + " ]"); Trace.WriteLine(" stateExecutionTime: " + stateExecutionTime.ToString()); // // Update the execution time so far // executionTime += stateExecutionTime; // // Next state // state = nextState; } } catch (Exception ex) { Logfile.WriteError(ex.Message); throw; } // // Round execution time to the nearest integer // int execTime = (int)(executionTime + 0.5); logMessage = STRLOG_ExecutionTime + execTime.ToString(); Logfile.WriteCompleted(STRLOG_ClassName, STRLOG_MethodName, logMessage); return(execTime); }
private static void MonitorHttp() { HttpSocketClient HttpClient = null; HttpResponse Response; XmlDocument Xml; Thread ControlThread; string Resource; ControlThread = new Thread(ControlHttp); ControlThread.Name = "Control HTTP"; ControlThread.Priority = ThreadPriority.Normal; ControlThread.Start(); try { while (executing) { try { if (HttpClient == null) { HttpClient = new HttpSocketClient("192.168.0.29", 80, new DigestAuthentication("Peter", "Waher")); HttpClient.ReceiveTimeout = 30000; HttpClient.Open(); } if (hasValues) { int NrLeds = (int)System.Math.Round((8 * lightPercent) / 100); double LightNextStepDown = 100 * (NrLeds - 0.1) / 8; double LightNextStepUp = 100 * (NrLeds + 1) / 8; double DistDown = System.Math.Abs(lightPercent - LightNextStepDown); double DistUp = System.Math.Abs(LightNextStepUp - lightPercent); double Dist20 = System.Math.Abs(20 - lightPercent); double MinDist = System.Math.Min(System.Math.Min(DistDown, DistUp), Dist20); if (MinDist < 1) { MinDist = 1; } StringBuilder sb = new StringBuilder(); sb.Append("/event/xml?Light="); sb.Append(XmlUtilities.DoubleToString(lightPercent, 1)); sb.Append("&LightDiff="); sb.Append(XmlUtilities.DoubleToString(MinDist, 1)); sb.Append("&Motion="); sb.Append(motion ? "1" : "0"); sb.Append("&Timeout=25"); Resource = sb.ToString(); } else { Resource = "/xml?Momentary=1&Light=1&Motion=1"; } Response = HttpClient.GET(Resource); Xml = Response.Xml; if (UpdateFields(Xml)) { hasValues = true; CheckControlRules(); } } catch (Exception ex) { Log.Exception(ex.Message); HttpClient.Dispose(); HttpClient = null; } } } finally { ControlThread.Abort(); ControlThread = null; } if (HttpClient != null) { HttpClient.Dispose(); } }
public void NullNodeIsAnAmbiguousTextNode() { Assert.AreEqual(TextNodeStatus.IsAmbiguous, XmlUtilities.IsTextNodeContainer(null)); }
/// <remarks> /// This method boils down to Rewrite(XDocument.Load(fileAttrValue).XPathSelectElements(pathAttrValue)). /// Everything else is error handling. /// </remarks> private XNode[] RewriteIncludeElement(XElement includeElement, string currentXmlFilePath, CSharpSyntaxNode originatingSyntax, out string commentMessage) { Location location = GetIncludeElementLocation(includeElement, ref currentXmlFilePath, ref originatingSyntax); Debug.Assert(originatingSyntax != null); bool diagnose = originatingSyntax.SyntaxTree.ReportDocumentationCommentDiagnostics(); if (!EnterIncludeElement(location)) { // NOTE: these must exist since we're already processed this node elsewhere in the call stack. XAttribute fileAttr = includeElement.Attribute(XName.Get(DocumentationCommentXmlNames.FileAttributeName)); XAttribute pathAttr = includeElement.Attribute(XName.Get(DocumentationCommentXmlNames.PathAttributeName)); string filePathValue = fileAttr.Value; string xpathValue = pathAttr.Value; if (diagnose) { diagnostics.Add(ErrorCode.WRN_FailedInclude, location, filePathValue, xpathValue, new LocalizableErrorArgument(MessageID.IDS_OperationCausedStackOverflow)); } // TODO: use culture from compilation instead of invariant culture? commentMessage = ErrorFacts.GetMessage(MessageID.IDS_XMLNOINCLUDE, CultureInfo.InvariantCulture); // Don't inspect the children - we're already in a cycle. return(new XNode[] { new XComment(commentMessage), includeElement.Copy(copyAttributeAnnotations: false) }); } DiagnosticBag includeDiagnostics = DiagnosticBag.GetInstance(); try { XAttribute fileAttr = includeElement.Attribute(XName.Get(DocumentationCommentXmlNames.FileAttributeName)); XAttribute pathAttr = includeElement.Attribute(XName.Get(DocumentationCommentXmlNames.PathAttributeName)); bool hasFileAttribute = fileAttr != null; bool hasPathAttribute = pathAttr != null; if (!hasFileAttribute || !hasPathAttribute) { var subMessage = hasFileAttribute ? MessageID.IDS_XMLMISSINGINCLUDEPATH.Localize() : MessageID.IDS_XMLMISSINGINCLUDEFILE.Localize(); includeDiagnostics.Add(ErrorCode.WRN_InvalidInclude, location, subMessage); commentMessage = MakeCommentMessage(location, MessageID.IDS_XMLBADINCLUDE); return(null); } string xpathValue = pathAttr.Value; string filePathValue = fileAttr.Value; var resolver = compilation.Options.XmlReferenceResolver; if (resolver == null) { includeDiagnostics.Add(ErrorCode.WRN_FailedInclude, location, filePathValue, xpathValue, new CodeAnalysisResourcesLocalizableErrorArgument(nameof(CodeAnalysisResources.XmlReferencesNotSupported))); commentMessage = MakeCommentMessage(location, MessageID.IDS_XMLFAILEDINCLUDE); return(null); } string resolvedFilePath = resolver.ResolveReference(filePathValue, currentXmlFilePath); if (resolvedFilePath == null) { // NOTE: same behavior as IOException. includeDiagnostics.Add(ErrorCode.WRN_FailedInclude, location, filePathValue, xpathValue, new CodeAnalysisResourcesLocalizableErrorArgument(nameof(CodeAnalysisResources.FileNotFound))); commentMessage = MakeCommentMessage(location, MessageID.IDS_XMLFAILEDINCLUDE); return(null); } if (includedFileCache == null) { includedFileCache = new DocumentationCommentIncludeCache(resolver); } try { XDocument doc; try { doc = includedFileCache.GetOrMakeDocument(resolvedFilePath); } catch (IOException e) { // NOTE: same behavior as resolvedFilePath == null. includeDiagnostics.Add(ErrorCode.WRN_FailedInclude, location, filePathValue, xpathValue, e.Message); commentMessage = MakeCommentMessage(location, MessageID.IDS_XMLFAILEDINCLUDE); return(null); } Debug.Assert(doc != null); string errorMessage; bool invalidXPath; XElement[] loadedElements = XmlUtilities.TrySelectElements(doc, xpathValue, out errorMessage, out invalidXPath); if (loadedElements == null) { includeDiagnostics.Add(ErrorCode.WRN_FailedInclude, location, filePathValue, xpathValue, errorMessage); commentMessage = MakeCommentMessage(location, MessageID.IDS_XMLFAILEDINCLUDE); if (invalidXPath) { // leave the include node as is return(null); } if (location.IsInSource) { // As in Dev11, return only the comment - drop the include element. return(new XNode[] { new XComment(commentMessage) }); } else { commentMessage = null; return(SpecializedCollections.EmptyArray <XNode>()); } } if (loadedElements != null && loadedElements.Length > 0) { // change the current XML file path for nodes contained in the document: XNode[] result = RewriteMany(loadedElements, resolvedFilePath, originatingSyntax); // The elements could be rewritten away if they are includes that refer to invalid // (but existing and accessible) XML files. If this occurs, behave as if we // had failed to find any XPath results (as in Dev11). if (result.Length > 0) { // NOTE: in this case, we do NOT visit the children of the include element - // they are dropped. commentMessage = null; return(result); } } commentMessage = MakeCommentMessage(location, MessageID.IDS_XMLNOINCLUDE); return(null); } catch (XmlException e) { // NOTE: invalid XML is handled differently from other errors - we don't include the include element // in the results and the location is in the included (vs includING) file. Location errorLocation = XmlLocation.Create(e, resolvedFilePath); includeDiagnostics.Add(ErrorCode.WRN_XMLParseIncludeError, errorLocation, GetDescription(e)); //NOTE: location is in included file. if (location.IsInSource) { commentMessage = string.Format(ErrorFacts.GetMessage(MessageID.IDS_XMLIGNORED2, CultureInfo.InvariantCulture), resolvedFilePath); // As in Dev11, return only the comment - drop the include element. return(new XNode[] { new XComment(commentMessage) }); } else { commentMessage = null; return(SpecializedCollections.EmptyArray <XNode>()); } } } finally { if (diagnose) { diagnostics.AddRange(includeDiagnostics); } includeDiagnostics.Free(); LeaveIncludeElement(location); } }
public void AllNullsIsNotTextlevel() { Assert.IsFalse(XmlUtilities.IsTextLevel(null, null, null)); }
public PersonList ProfileSearch(Connects.Profiles.Service.DataContracts.Profiles qd, bool isSecure) { PersonList pl = null; try { ProfileSearchBL ps = new ProfileSearchBL(); Connects.Profiles.Service.DataContracts.Profiles p = new Connects.Profiles.Service.DataContracts.Profiles(); //qd.OutputOptions.StartRecord = (Convert.ToInt32(qd.OutputOptions.StartRecord) + 1).ToString(); string req = XmlUtilities.SerializeToString(qd); req = req.Replace("Version=\"0\"", "Version=\"1\""); XmlUtilities.logit("Line 1: ProfileServiceAdapter.ProfileSearch(" + req + "," + isSecure.ToString() + ")"); // If we are enforcing XSD if (Convert.ToBoolean(ConfigUtil.GetConfigItem("EnforceQuerySchema")) == true) { XmlUtilities.logit("Line 2: Enforcing XSD"); if (ValidateSearchRequest(req) == false) { XmlUtilities.logit("Line 3: Failed XSD"); throw new Exception("Search request failed XML schema validation"); } XmlUtilities.logit("Line 3: Passed XSD"); } else { XmlUtilities.logit("Line 2 and 3: No XSD Required"); } using (XmlReaderScope scope = ps.ProfileSearch(req, isSecure)) { Type type = typeof(PersonList); string responseXML; scope.Reader.Read(); responseXML = scope.Reader.ReadOuterXml(); XmlUtilities.logit("Line 4: Response data " + responseXML); // If we are enforcing XSD if (Convert.ToBoolean(ConfigUtil.GetConfigItem("EnforceResponseSchema")) == true) { XmlUtilities.logit("Line 5: Enforcing response XSD"); if (ValidateSearchResponse(responseXML) == false) { XmlUtilities.logit("Line 6: Failed response xsd"); throw new Exception("Search response failed XML schema validation"); } XmlUtilities.logit("Line 6: Passed response xsd"); } else { XmlUtilities.logit("Line 5 and 6: No XSD Required"); } pl = XmlUtilities.DeserializeObject(responseXML, type) as PersonList; XmlUtilities.logit("Line 7: Returned to requestor"); } } catch (Exception ex) { XmlUtilities.logit("ERROR==> " + ex.Message + " STACK:" + ex.StackTrace + " SOURCE:" + ex.Source); } return(pl); }
/// <summary>Pastes the contents of the clipboard.</summary> public void Add(string xml, string parentPath) { try { XmlDocument document = new XmlDocument(); try { document.LoadXml(xml); } catch (XmlException) { MainPresenter.ShowMessage("Invalid XML. Are you sure you're trying to paste an APSIM model?", DataStore.ErrorLevel.Error); } object newModel = XmlUtilities.Deserialise(document.DocumentElement, ApsimXFile.GetType().Assembly); // See if the presenter is happy with this model being added. Model parentModel = Apsim.Get(this.ApsimXFile, parentPath) as Model; AllowDropArgs allowDropArgs = new AllowDropArgs(); allowDropArgs.NodePath = parentPath; allowDropArgs.DragObject = new DragObject() { NodePath = null, ModelType = newModel.GetType(), Xml = GetClipboardText() }; this.OnAllowDrop(null, allowDropArgs); // If it is happy then issue an AddModelCommand. if (allowDropArgs.Allow) { // If the model xml is a soil object then try and convert from old // APSIM format to new. if (document.DocumentElement.Name == "Soil" && XmlUtilities.Attribute(document.DocumentElement, "Name") != "") { XmlDocument newDoc = new XmlDocument(); newDoc.AppendChild(newDoc.CreateElement("D")); APSIMImporter importer = new APSIMImporter(); importer.ImportSoil(document.DocumentElement, newDoc.DocumentElement, newDoc.DocumentElement); XmlNode soilNode = XmlUtilities.FindByType(newDoc.DocumentElement, "Soil"); if (soilNode != null && XmlUtilities.FindByType(soilNode, "Sample") == null && XmlUtilities.FindByType(soilNode, "InitialWater") == null) { // Add in an initial water and initial conditions models. XmlNode initialWater = soilNode.AppendChild(soilNode.OwnerDocument.CreateElement("InitialWater")); XmlUtilities.SetValue(initialWater, "Name", "Initial water"); XmlUtilities.SetValue(initialWater, "PercentMethod", "FilledFromTop"); XmlUtilities.SetValue(initialWater, "FractionFull", "1"); XmlUtilities.SetValue(initialWater, "DepthWetSoil", "NaN"); XmlNode initialConditions = soilNode.AppendChild(soilNode.OwnerDocument.CreateElement("Sample")); XmlUtilities.SetValue(initialConditions, "Name", "Initial conditions"); XmlUtilities.SetValue(initialConditions, "Thickness/double", "1800"); XmlUtilities.SetValue(initialConditions, "NO3/double", "10"); XmlUtilities.SetValue(initialConditions, "NH4/double", "1"); XmlUtilities.SetValue(initialConditions, "NO3Units", "kgha"); XmlUtilities.SetValue(initialConditions, "NH4Units", "kgha"); XmlUtilities.SetValue(initialConditions, "SWUnits", "Volumetric"); } document.LoadXml(newDoc.DocumentElement.InnerXml); } IModel child = XmlUtilities.Deserialise(document.DocumentElement, ApsimXFile.GetType().Assembly) as IModel; AddModelCommand command = new AddModelCommand(parentModel, document.DocumentElement, GetNodeDescription(child), view); this.CommandHistory.Add(command, true); } } catch (Exception exception) { this.MainPresenter.ShowMessage(exception.Message, DataStore.ErrorLevel.Error); } }
public string GetHtml(string style, string styleSheet) { var builder = new StringBuilder(); builder.Append("<html><head>" + styleSheet + "</head>"); if (style == "normal") { if (_conflict is UnreadableConflict) { builder.Append(((UnreadableConflict)_conflict).ConflictNode.OuterXml); } else if (_conflict is UnmergableFileTypeConflict) { builder.Append(((UnmergableFileTypeConflict)_conflict).GetFullHumanReadableDescription()); } else if (_report is XmlAdditionChangeReport) { builder.AppendFormat( "<p>{0} and {1} both edited {2} in the file {3} in a way that could not be automatically merged.</p>", _conflict.Situation.AlphaUserId, _conflict.Situation.BetaUserId, _conflict.Context.DataLabel, _conflict.RelativeFilePath); builder.AppendFormat("<p></p>"); // XmlUtilities.GetXmlForShowingInHtml(_report.ChildNode.OuterXml)); } } else { if (_conflict is UnreadableConflict) { builder.Append(((UnreadableConflict)_conflict).ConflictNode.OuterXml); } else if (_conflict is UnmergableFileTypeConflict) { builder.Append(((UnmergableFileTypeConflict)_conflict).GetFullHumanReadableDescription()); } else { builder.AppendFormat( "{0} and {1} both edited {2} in a way that could not be merged. Where they conflicted, {3}'s version was kept.<br/>", _conflict.Situation.AlphaUserId, _conflict.Situation.BetaUserId, _conflict.Context.DataLabel, _conflict.WinnerId); builder.AppendFormat( "The kind of conflict was: {0}", _conflict.Description); // var m = new Rainbow.HtmlDiffEngine.Merger(original, modified); // builder.Append(m.merge()); builder.AppendFormat("<h3>Original Record</h3>"); var ancestor = _conflict.GetConflictingRecordOutOfSourceControl(_fileRetriever, ThreeWayMergeSources.Source.Ancestor); builder.Append(XmlUtilities.GetXmlForShowingInHtml(ancestor)); builder.AppendFormat("<h3>{0}'s version</h3>", _conflict.Situation.AlphaUserId); var userXVersion = _conflict.GetConflictingRecordOutOfSourceControl(_fileRetriever, ThreeWayMergeSources.Source. UserX); builder.Append(XmlUtilities.GetXmlForShowingInHtml(userXVersion)); builder.AppendFormat("</p><h3>{0}'s version</h3>", _conflict.Situation.BetaUserId); var userYVersion = _conflict.GetConflictingRecordOutOfSourceControl(_fileRetriever, ThreeWayMergeSources.Source. UserY); builder.Append(XmlUtilities.GetXmlForShowingInHtml(userYVersion)); builder.AppendFormat("</p><h3>Resulting version</h3>", _conflict.Situation.BetaUserId); string resulting = ""; try { resulting = _fileRetriever.RetrieveHistoricalVersionOfFile(_conflict.RelativeFilePath, _conflict. RevisionWhereMergeWasCheckedIn); builder.Append(XmlUtilities.GetXmlForShowingInHtml(resulting)); } catch (Exception error) { if (File.Exists(resulting)) { File.Delete(resulting); } builder.Append("Could not retrieve the file. The error was: " + error.Message); } } } builder.Append("</html>"); return(builder.ToString()); }
public TerrainProcessor(string filePath) { filePath = Path.Combine(Application.streamingAssetsPath, filePath); XmlUtilities.Read("TerrainProcessor", "Parameters", filePath, null, LoadProcess); }
private async Task <List <Geometry> > ParseRoute(XElement node, Dictionary <string, ShapeStyle> styles) { var geoms = new List <Geometry>(); var line = new LineString(); var metadata = new ShapeMetadata(); var coords = new CoordinateCollection(); var style = new ShapeStyle(); string nodeName; foreach (var n in node.Elements()) { nodeName = n.Name.LocalName; switch (nodeName) { case "name": metadata.Title = XmlUtilities.GetString(n, stripHtml); break; case "desc": metadata.Description = XmlUtilities.GetString(n, stripHtml); break; case "cmt": case "src": case "type": SetMetadataString(metadata, nodeName, n, stripHtml); break; case "number": //<number> xsd:nonNegativeInteger </number> [0..1] ? var i = XmlUtilities.GetInt32(n, -1); if (i >= 0 && !metadata.Properties.ContainsKey(nodeName)) { metadata.Properties.Add(nodeName, i); } break; case "link": var href = XmlUtilities.GetStringAttribute(n, "href"); if (!string.IsNullOrWhiteSpace(href) && !metadata.Properties.ContainsKey(nodeName)) { metadata.Properties.Add(nodeName, href); } break; case "rtept": if (readRouteWaypoints) { var wpt = ParseWaypoint(n, styles); coords.Add(wpt.Coordinate); geoms.Add(wpt); } else { var c = ParseWaypointAsCoordinate(n); if (c.HasValue) { coords.Add(c.Value); } } break; case "extensions": ParseExtensions(n, metadata, style); break; default: break; } } if (!string.IsNullOrEmpty(metadata.Title) || !string.IsNullOrEmpty(metadata.Description) || metadata.Properties.Count > 0) { line.Metadata = metadata; } if (style.StrokeColor.HasValue) { var styleKey = "embeddedStyle_" + embeddedStyleCnt; embeddedStyleCnt++; styles.Add(styleKey, style); line.StyleKey = styleKey; } if (coords.Count >= 2) { if (optimize) { coords = await SpatialTools.VertexReductionAsync(coords, tolerance); } line.Vertices = coords; geoms.Add(line); } return(geoms); }
//-------------------------------------------------------------------------------------------------// public override string ToString() { return(XmlUtilities.ToXmlString(this.xmlNodeSpecification)); }
private Point ParseWaypoint(XElement node, Dictionary <string, ShapeStyle> styles) { var lat = XmlUtilities.GetDoubleAttribute(node, "lat"); var lon = XmlUtilities.GetDoubleAttribute(node, "lon"); if (!double.IsNaN(lat) && !double.IsNaN(lon)) { var point = new Point(new Coordinate(lat, lon)); var metadata = new ShapeMetadata(); var style = new ShapeStyle(); string nodeName; foreach (var n in node.Elements()) { nodeName = n.Name.LocalName; switch (nodeName) { case "name": metadata.Title = XmlUtilities.GetString(n, stripHtml); break; case "desc": metadata.Description = XmlUtilities.GetString(n, stripHtml); break; case "cmt": case "src": case "sym": case "type": case "fix": SetMetadataString(metadata, nodeName, n, stripHtml); break; case "sat": //xsd:nonNegativeInteger case "dgpsid": var i = XmlUtilities.GetInt32(n, -1); if (i >= 0 && !metadata.Properties.ContainsKey(nodeName)) { metadata.Properties.Add(nodeName, i); } break; case "magvar": case "hdop": case "vdop": case "pdop": case "ageofdgpsdata": case "geoidheight": var d = XmlUtilities.GetDouble(n, double.NaN); if (!double.IsNaN(d) && !metadata.Properties.ContainsKey(nodeName)) { metadata.Properties.Add(nodeName, d); } break; case "link": var href = XmlUtilities.GetStringAttribute(n, "href"); if (!string.IsNullOrWhiteSpace(href) && !metadata.Properties.ContainsKey(nodeName)) { metadata.Properties.Add(nodeName, href); } break; case "ele": var ele = XmlUtilities.GetDouble(n, double.NaN); if (!double.IsNaN(ele)) { point.Coordinate = new Coordinate(point.Coordinate.Latitude, point.Coordinate.Longitude, ele); } break; case "time": var time = XmlUtilities.GetDateTime(n); if (time.HasValue && !metadata.Properties.ContainsKey(nodeName)) { metadata.Properties.Add(nodeName, time); } break; case "extensions": ParseExtensions(n, metadata, style); break; default: break; } } if (!string.IsNullOrEmpty(metadata.Title) || !string.IsNullOrEmpty(metadata.Description) || metadata.Properties.Count > 0) { point.Metadata = metadata; } if (style.StrokeColor.HasValue) { var styleKey = "embeddedStyle_" + embeddedStyleCnt; embeddedStyleCnt++; styles.Add(styleKey, style); point.StyleKey = styleKey; } return(point); } return(null); }
private async Task <MultiLineString> ParseTrack(XElement node, Dictionary <string, ShapeStyle> styles) { var lines = new MultiLineString(); var metadata = new ShapeMetadata(); var style = new ShapeStyle(); string nodeName; foreach (var n in node.Elements()) { nodeName = n.Name.LocalName; switch (nodeName) { case "name": metadata.Title = XmlUtilities.GetString(n, stripHtml); break; case "desc": metadata.Description = XmlUtilities.GetString(n, stripHtml); break; case "cmt": case "src": case "type": SetMetadataString(metadata, nodeName, n, stripHtml); break; case "number": //<number> xsd:nonNegativeInteger </number> [0..1] ? var i = XmlUtilities.GetInt32(n, -1); if (i >= 0 && !metadata.Properties.ContainsKey(nodeName)) { metadata.Properties.Add(nodeName, i); } break; case "trkseg": var seg = await ParseTrackSegment(n); if (seg != null && seg.Vertices != null && seg.Vertices.Count >= 2) { lines.Geometries.Add(seg); } break; case "link": var href = XmlUtilities.GetStringAttribute(n, "href"); if (!string.IsNullOrWhiteSpace(href) && !metadata.Properties.ContainsKey(nodeName)) { metadata.Properties.Add(nodeName, href); } break; case "extensions": ParseExtensions(n, metadata, style); break; default: break; } } if (!string.IsNullOrEmpty(metadata.Title) || !string.IsNullOrEmpty(metadata.Description) || metadata.Properties.Count > 0) { lines.Metadata = metadata; } if (style.StrokeColor.HasValue) { var styleKey = "embeddedStyle_" + embeddedStyleCnt; embeddedStyleCnt++; styles.Add(styleKey, style); lines.StyleKey = styleKey; } if (lines.Geometries.Count > 0) { return(lines); } return(null); }
public static void ToXml(TextWriter writer, TraceProcess stats, TraceLoadedDotNetRuntime runtime, string indent) { JITStatsEx statsEx = JITStatsEx.Create(runtime); // TODO pay attention to indent; writer.Write(" <JitProcess Process=\"{0}\" ProcessID=\"{1}\" JitTimeMSec=\"{2:n3}\" Count=\"{3}\" ILSize=\"{4}\" NativeSize=\"{5}\"", stats.Name, stats.ProcessID, runtime.JIT.Stats().TotalCpuTimeMSec, runtime.JIT.Stats().Count, runtime.JIT.Stats().TotalILSize, runtime.JIT.Stats().TotalNativeSize); if (stats.CPUMSec != 0) { writer.Write(" ProcessCpuTimeMsec=\"{0}\"", stats.CPUMSec); } if (!string.IsNullOrEmpty(stats.CommandLine)) { writer.Write(" CommandLine=\"{0}\"", XmlUtilities.XmlEscape(stats.CommandLine, false)); } writer.WriteLine(">"); writer.WriteLine(" <JitEvents>"); foreach (TraceJittedMethod _event in runtime.JIT.Methods) { ToXml(writer, _event); } writer.WriteLine(" </JitEvents>"); writer.WriteLine(" <ModuleStats Count=\"{0}\" TotalCount=\"{1}\" TotalJitTimeMSec=\"{2:n3}\" TotalILSize=\"{3}\" TotalNativeSize=\"{4}\">", statsEx.TotalModuleStats.Count, runtime.JIT.Stats().Count, runtime.JIT.Stats().TotalCpuTimeMSec, runtime.JIT.Stats().TotalILSize, runtime.JIT.Stats().TotalNativeSize); // Sort the module list by Jit Time; List <string> moduleNames = new List <string>(statsEx.TotalModuleStats.Keys); moduleNames.Sort(delegate(string x, string y) { double diff = statsEx.TotalModuleStats[y].TotalCpuTimeMSec - statsEx.TotalModuleStats[x].TotalCpuTimeMSec; if (diff > 0) { return(1); } else if (diff < 0) { return(-1); } return(0); }); foreach (string moduleName in moduleNames) { JITStats info = statsEx.TotalModuleStats[moduleName]; writer.Write("<Module"); writer.Write(" JitTimeMSec={0}", StringUtilities.QuotePadLeft(info.TotalCpuTimeMSec.ToString("n3"), 11)); writer.Write(" Count={0}", StringUtilities.QuotePadLeft(info.Count.ToString(), 7)); writer.Write(" ILSize={0}", StringUtilities.QuotePadLeft(info.TotalILSize.ToString(), 9)); writer.Write(" NativeSize={0}", StringUtilities.QuotePadLeft(info.TotalNativeSize.ToString(), 9)); writer.Write(" Name=\"{0}\"", moduleName); writer.WriteLine("/>"); } writer.WriteLine(" </ModuleStats>"); writer.WriteLine(" </JitProcess>"); }
/// <summary>Do all soil related settings.</summary> /// <param name="simulation">The specification to use</param> /// <param name="workingFolder">The folder where files shoud be created.</param> private static void DoSoil(APSIMSpecification simulation, string workingFolder) { Soil soil; if (simulation.Soil == null) { if (simulation.SoilPath.StartsWith("http")) { // Soil and Landscape grid string xml; using (var client = new WebClient()) { xml = client.DownloadString(simulation.SoilPath); } XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); List <XmlNode> soils = XmlUtilities.ChildNodes(doc.DocumentElement, "Soil"); if (soils.Count == 0) { throw new Exception("Cannot find soil in Soil and Landscape Grid"); } soil = XmlUtilities.Deserialise(soils[0], typeof(Soil)) as Soil; } else { // Apsoil web service. APSOIL.Service apsoilService = new APSOIL.Service(); string soilXml = apsoilService.SoilXML(simulation.SoilPath); if (soilXml == string.Empty) { throw new Exception("Cannot find soil: " + simulation.SoilPath); } soil = SoilUtilities.FromXML(soilXml); } } else { // Just use the soil we already have soil = simulation.Soil; } // Make sure we have a soil crop parameterisation. If not then try creating one // based on wheat. Sow sowing = YieldProphetUtility.GetCropBeingSown(simulation.Management); string[] cropNames = soil.Water.Crops.Select(c => c.Name).ToArray(); if (cropNames.Length == 0) { throw new Exception("Cannot find any crop parameterisations in soil: " + simulation.SoilPath); } if (sowing != null && !StringUtilities.Contains(cropNames, sowing.Crop)) { SoilCrop wheat = soil.Water.Crops.Find(c => c.Name.Equals("wheat", StringComparison.InvariantCultureIgnoreCase)); if (wheat == null) { // Use the first crop instead. wheat = soil.Water.Crops[0]; } SoilCrop newSoilCrop = new SoilCrop(); newSoilCrop.Name = sowing.Crop; newSoilCrop.Thickness = wheat.Thickness; newSoilCrop.LL = wheat.LL; newSoilCrop.KL = wheat.KL; newSoilCrop.XF = wheat.XF; soil.Water.Crops.Add(newSoilCrop); } // Remove any initwater nodes. soil.InitialWater = null; // Transfer the simulation samples to the soil if (simulation.Samples != null) { soil.Samples = simulation.Samples; } if (simulation.InitTotalWater != 0) { soil.InitialWater = new InitialWater(); soil.InitialWater.PercentMethod = InitialWater.PercentMethodEnum.FilledFromTop; double pawc; if (sowing == null || sowing.Crop == null) { pawc = MathUtilities.Sum(PAWC.OfSoilmm(soil)); soil.InitialWater.RelativeTo = "LL15"; } else { SoilCrop crop = soil.Water.Crops.Find(c => c.Name.Equals(sowing.Crop, StringComparison.InvariantCultureIgnoreCase)); pawc = MathUtilities.Sum(PAWC.OfCropmm(soil, crop)); soil.InitialWater.RelativeTo = crop.Name; } soil.InitialWater.FractionFull = Convert.ToDouble(simulation.InitTotalWater) / pawc; } if (simulation.InitTotalNitrogen != 0) { // Add in a sample. Sample nitrogenSample = new Sample(); nitrogenSample.Name = "NitrogenSample"; soil.Samples.Add(nitrogenSample); nitrogenSample.Thickness = new double[] { 150, 150, 3000 }; nitrogenSample.NO3Units = Nitrogen.NUnitsEnum.kgha; nitrogenSample.NH4Units = Nitrogen.NUnitsEnum.kgha; nitrogenSample.NO3 = new double[] { 6.0, 2.1, 0.1 }; nitrogenSample.NH4 = new double[] { 0.5, 0.1, 0.1 }; nitrogenSample.OC = new double[] { double.NaN, double.NaN, double.NaN }; nitrogenSample.EC = new double[] { double.NaN, double.NaN, double.NaN }; nitrogenSample.PH = new double[] { double.NaN, double.NaN, double.NaN }; double Scale = Convert.ToDouble(simulation.InitTotalNitrogen) / MathUtilities.Sum(nitrogenSample.NO3); nitrogenSample.NO3 = MathUtilities.Multiply_Value(nitrogenSample.NO3, Scale); } // Add in soil temperature. Needed for Aflatoxin risk. soil.SoilTemperature = new SoilTemperature(); soil.SoilTemperature.BoundaryLayerConductance = 15; soil.SoilTemperature.Thickness = new double[] { 2000 }; soil.SoilTemperature.InitialSoilTemperature = new double[] { 22 }; if (soil.Analysis.ParticleSizeClay == null) { soil.Analysis.ParticleSizeClay = MathUtilities.CreateArrayOfValues(60, soil.Analysis.Thickness.Length); } InFillMissingValues(soil.Analysis.ParticleSizeClay); foreach (Sample sample in soil.Samples) { CheckSample(soil, sample, sowing); } Defaults.FillInMissingValues(soil); // Correct the CONA / U parameters depending on LAT/LONG CorrectCONAU(simulation, soil, workingFolder); // get rid of <soiltype> from the soil // this is necessary because NPD uses this field and puts in really long // descriptive classifications. Soiln2 bombs with an FString internal error. soil.SoilType = null; // Set the soil name to 'soil' soil.Name = "Soil"; simulation.Soil = soil; }
//---------------------------------------------------------------------------------------// private void ParseLabConfiguration(LabClientSession labClientSession, string xmlLabConfiguration) { const string STRLOG_MethodName = "ParseLabConfiguration"; Logfile.WriteCalled(STRLOG_ClassName, STRLOG_MethodName); try { Logfile.Write(STRLOG_LoadingLabConfiguration); // // Load the lab configuration from an XML string // XmlDocument xmlDocument = XmlUtilities.GetXmlDocument(xmlLabConfiguration); // // Save a copy of the lab configuration XML node // XmlNode xmlNode = XmlUtilities.GetXmlRootNode(xmlDocument, Consts.STRXML_labConfiguration); XmlNode xmlNodeLabConfiguration = xmlNode.Clone(); labClientSession.xmlNodeLabConfiguration = xmlNodeLabConfiguration; Logfile.Write(STRLOG_ParsingLabConfiguration); // // Get information from the lab configuration node // labClientSession.bannerTitle = XmlUtilities.GetXmlValue(xmlNodeLabConfiguration, Consts.STRXMLPARAM_title, false); labClientSession.statusVersion = XmlUtilities.GetXmlValue(xmlNodeLabConfiguration, Consts.STRXMLPARAM_version, false); labClientSession.navmenuPhotoUrl = XmlUtilities.GetXmlValue(xmlNodeLabConfiguration, Consts.STRXML_navmenuPhoto_image, false); labClientSession.labCameraUrl = XmlUtilities.GetXmlValue(xmlNodeLabConfiguration, Consts.STRXML_labCamera_url, true); labClientSession.labInfoText = XmlUtilities.GetXmlValue(xmlNodeLabConfiguration, Consts.STRXML_labInfo_text, true); labClientSession.labInfoUrl = XmlUtilities.GetXmlValue(xmlNodeLabConfiguration, Consts.STRXML_labInfo_url, true); Logfile.Write(STRLOG_Title + labClientSession.bannerTitle); Logfile.Write(STRLOG_Version + labClientSession.statusVersion); Logfile.Write(STRLOG_PhotoUrl + labClientSession.navmenuPhotoUrl); Logfile.Write(STRLOG_LabCameraUrl + labClientSession.labCameraUrl); Logfile.Write(STRLOG_LabInfoText + labClientSession.labInfoText); Logfile.Write(STRLOG_LabInfoUrl + labClientSession.labInfoUrl); // // These are mandatory // xmlNode = XmlUtilities.GetXmlNode(xmlNodeLabConfiguration, Consts.STRXML_configuration, false); labClientSession.xmlNodeConfiguration = xmlNode.Clone(); xmlNode = XmlUtilities.GetXmlNode(xmlNodeLabConfiguration, Consts.STRXML_experimentSpecification, false); labClientSession.xmlNodeSpecification = xmlNode.Clone(); // // These are optional and depend on the LabServer implementation // xmlNode = XmlUtilities.GetXmlNode(xmlNodeLabConfiguration, Consts.STRXML_validation, true); if (xmlNode != null) { labClientSession.xmlNodeValidation = xmlNode.Clone(); } } catch (Exception ex) { Logfile.WriteError(ex.Message); throw; } Logfile.WriteCompleted(STRLOG_ClassName, STRLOG_MethodName); }
/// <summary>Create all necessary YP files (.apsim and .met) from a YieldProphet spec.</summary> /// <param name="simulations">The simulations to write.</param> /// <param name="workingFolder">The folder where files shoud be created.</param> /// <param name="fileNameToWrite">The name of a file to write.</param> /// <returns>The name of the created .apsim file.</returns> public static string Create(List <APSIMSpecification> simulations, string workingFolder, string fileNameToWrite) { bool usingAPSIMx = Path.GetExtension(fileNameToWrite) == ".apsimx"; // Create the .apsim XML XmlDocument doc = new XmlDocument(); if (usingAPSIMx) { doc.AppendChild(doc.CreateElement("Simulations")); XmlUtilities.SetValue(doc.DocumentElement, "Name", "Simulations"); XmlUtilities.SetValue(doc.DocumentElement, "DataStore/Name", "DataStore"); } else { doc.AppendChild(doc.CreateElement("folder")); XmlUtilities.SetNameAttr(doc.DocumentElement, "Simulations"); XmlUtilities.SetAttribute(doc.DocumentElement, "version", APSIMVerionNumber.ToString()); } // Determine whether all simulations are single season. bool allSimulationsAreSingleSeason = true; foreach (APSIMSpecification simulation in simulations) { if (simulation.RunType != APSIMSpecification.RunTypeEnum.Normal) { allSimulationsAreSingleSeason = false; } } WeatherFileCache weatherCache = new WeatherFileCache(); foreach (APSIMSpecification simulation in simulations) { CreateWeatherFilesForSimulations(simulation, workingFolder, weatherCache, allSimulationsAreSingleSeason); CreateApsimFile(simulation, workingFolder, doc.DocumentElement, usingAPSIMx); } // Apply factors. if (!usingAPSIMx) { foreach (APSIMSpecification simulation in simulations) { if (simulation.ErrorMessage == null && simulation.Factors != null) { foreach (APSIMSpecification.Factor factor in simulation.Factors) { APSIMFileWriter.ApplyFactor(doc.DocumentElement, factor); } } } } // Write the .apsim file. string apsimFileName = Path.Combine(workingFolder, fileNameToWrite); File.WriteAllText(apsimFileName, XmlUtilities.FormattedXML(doc.DocumentElement.OuterXml)); // Write a .apsimrun file. string apsimRunFileName = Path.Combine(workingFolder, Path.ChangeExtension(fileNameToWrite, ".spec")); string xml = XmlUtilities.Serialise(simulations, false); File.WriteAllText(apsimRunFileName, xml); return(apsimFileName); }
/// <summary> /// Parse a ProjectItemElement /// </summary> private ProjectItemElement ParseProjectItemElement(XmlElementWithLocation element, ProjectItemGroupElement parent) { bool belowTarget = parent.Parent is ProjectTargetElement; string itemType = element.Name; string include = element.GetAttribute(XMakeAttributes.include); string exclude = element.GetAttribute(XMakeAttributes.exclude); string remove = element.GetAttribute(XMakeAttributes.remove); string update = element.GetAttribute(XMakeAttributes.update); var exclusiveItemOperation = ""; int exclusiveAttributeCount = 0; if (element.HasAttribute(XMakeAttributes.include)) { exclusiveAttributeCount++; exclusiveItemOperation = XMakeAttributes.include; } if (element.HasAttribute(XMakeAttributes.remove)) { exclusiveAttributeCount++; exclusiveItemOperation = XMakeAttributes.remove; } if (element.HasAttribute(XMakeAttributes.update)) { exclusiveAttributeCount++; exclusiveItemOperation = XMakeAttributes.update; } // At most one of the include, remove, or update attributes may be specified if (exclusiveAttributeCount > 1) { XmlAttributeWithLocation errorAttribute = remove.Length > 0 ? (XmlAttributeWithLocation)element.Attributes[XMakeAttributes.remove] : (XmlAttributeWithLocation)element.Attributes[XMakeAttributes.update]; ProjectErrorUtilities.ThrowInvalidProject(errorAttribute.Location, "InvalidAttributeExclusive"); } // Include, remove, or update must be present unless inside a target ProjectErrorUtilities.VerifyThrowInvalidProject(exclusiveAttributeCount == 1 || belowTarget, element.Location, "IncludeRemoveOrUpdate", exclusiveItemOperation, itemType); // Exclude must be missing, unless Include exists ProjectXmlUtilities.VerifyThrowProjectInvalidAttribute(exclude.Length == 0 || include.Length > 0, (XmlAttributeWithLocation)element.Attributes[XMakeAttributes.exclude]); // If we have an Include attribute at all, it must have non-zero length ProjectErrorUtilities.VerifyThrowInvalidProject(include.Length > 0 || element.Attributes[XMakeAttributes.include] == null, element.Location, "MissingRequiredAttribute", XMakeAttributes.include, itemType); // If we have a Remove attribute at all, it must have non-zero length ProjectErrorUtilities.VerifyThrowInvalidProject(remove.Length > 0 || element.Attributes[XMakeAttributes.remove] == null, element.Location, "MissingRequiredAttribute", XMakeAttributes.remove, itemType); // If we have an Update attribute at all, it must have non-zero length ProjectErrorUtilities.VerifyThrowInvalidProject(update.Length > 0 || element.Attributes[XMakeAttributes.update] == null, element.Location, "MissingRequiredAttribute", XMakeAttributes.update, itemType); XmlUtilities.VerifyThrowProjectValidElementName(element); ProjectErrorUtilities.VerifyThrowInvalidProject(!XMakeElements.ReservedItemNames.Contains(itemType), element.Location, "CannotModifyReservedItem", itemType); ProjectItemElement item = new ProjectItemElement(element, parent, _project); foreach (XmlAttributeWithLocation attribute in element.Attributes) { bool isKnownAttribute; bool isValidMetadataNameInAttribute; CheckMetadataAsAttributeName(attribute.Name, out isKnownAttribute, out isValidMetadataNameInAttribute); if (!isKnownAttribute && !isValidMetadataNameInAttribute) { ProjectXmlUtilities.ThrowProjectInvalidAttribute(attribute); } else if (isValidMetadataNameInAttribute) { ProjectMetadataElement metadatum = _project.CreateMetadataElement(attribute.Name, attribute.Value); metadatum.ExpressedAsAttribute = true; metadatum.Parent = item; item.AppendParentedChildNoChecks(metadatum); } } foreach (XmlElementWithLocation childElement in ProjectXmlUtilities.GetVerifyThrowProjectChildElements(element)) { ProjectMetadataElement metadatum = ParseProjectMetadataElement(childElement, item); item.AppendParentedChildNoChecks(metadatum); } return(item); }
public object Build( XmlUtilities.XmlModule moduleToBuild, out bool success) { var node = moduleToBuild.OwningNode; var targetNode = node.ExternalDependents[0]; var toProject = targetNode.Data as IProject; var configCollection = toProject.Configurations; var configurationName = configCollection.GetConfigurationNameForTarget((Bam.Core.BaseTarget)targetNode.Target); // TODO: not accurate var configuration = configCollection[configurationName]; var toolName = "VCPreBuildEventTool"; var vcPreBuildEventTool = configuration.GetTool(toolName); if (null == vcPreBuildEventTool) { vcPreBuildEventTool = new ProjectTool(toolName); configuration.AddToolIfMissing(vcPreBuildEventTool); } var commandLine = new System.Text.StringBuilder(); var locationMap = moduleToBuild.Locations; var outputDir = locationMap[XmlUtilities.XmlModule.OutputDir]; var outputDirPath = outputDir.GetSingleRawPath(); commandLine.AppendFormat("IF NOT EXIST {0} MKDIR {0}{1}", outputDirPath, System.Environment.NewLine); var outputFileLoc = locationMap[XmlUtilities.XmlModule.OutputFile]; var outputFilePath = outputFileLoc.GetSingleRawPath(); var content = XmlUtilities.XmlDocumentToStringBuilder.Write(moduleToBuild.Document); foreach (var line in content.ToString().Split('\n')) { commandLine.AppendFormat("ECHO {0} >> {1}{2}", line, outputFilePath, System.Environment.NewLine); } { string attributeName = null; if (VisualStudioProcessor.EVisualStudioTarget.VCPROJ == toProject.VSTarget) { attributeName = "CommandLine"; } else if (VisualStudioProcessor.EVisualStudioTarget.MSBUILD == toProject.VSTarget) { attributeName = "Command"; } lock (vcPreBuildEventTool) { if (vcPreBuildEventTool.HasAttribute(attributeName)) { var currentValue = vcPreBuildEventTool[attributeName]; currentValue += commandLine.ToString(); vcPreBuildEventTool[attributeName] = currentValue; } else { vcPreBuildEventTool.AddAttribute(attributeName, commandLine.ToString()); } } } success = true; return null; }
private ShapeMetadata ParseDocMetadata(XElement node, out BoundingBox bounds) { var metadata = new ShapeMetadata(); bounds = null; string nodeName; foreach (var n in node.Elements()) { nodeName = n.Name.LocalName; switch (nodeName) { case "name": metadata.Title = XmlUtilities.GetString(n, stripHtml); break; case "desc": metadata.Description = XmlUtilities.GetString(n, stripHtml); break; case "keywords": SetMetadataString(metadata, nodeName, n, stripHtml); break; case "bounds": var minLat = XmlUtilities.GetDoubleAttribute(n, "minlat"); var minLon = XmlUtilities.GetDoubleAttribute(n, "minlon"); var maxLat = XmlUtilities.GetDoubleAttribute(n, "maxlat"); var maxLon = XmlUtilities.GetDoubleAttribute(n, "maxlon"); if (!double.IsNaN(minLat) && !double.IsNaN(minLon) && !double.IsNaN(maxLat) && !double.IsNaN(maxLon)) { //Not all documents properly order the latitude coordinates. //Assume that the longitude coordinates are correct var maxY = Math.Max(minLat, maxLat); var minY = Math.Min(minLat, maxLat); var minX = minLon; var maxX = maxLon; bounds = new BoundingBox(minX, maxY, maxX, minY); } break; case "link": var href = XmlUtilities.GetStringAttribute(n, "href"); if (!string.IsNullOrWhiteSpace(href) && !metadata.Properties.ContainsKey(nodeName)) { metadata.Properties.Add(nodeName, href); } break; case "time": var time = XmlUtilities.GetDateTime(n); if (time.HasValue && !metadata.Properties.ContainsKey(nodeName)) { metadata.Properties.Add(nodeName, time); } break; default: break; } } return(metadata); }