/// <summary> /// Creates a telemetry entry for a given log event /// </summary> /// <param name="logEvent">Event that was logged and written to this sink</param> /// <param name="formatProvider">Provider to format event</param> /// <returns>Telemetry entry to emit to Azure Application Insights</returns> protected override RequestTelemetry CreateTelemetryEntry(LogEvent logEvent, IFormatProvider formatProvider) { Guard.NotNull(logEvent, nameof(logEvent), "Requires a Serilog log event to create an Azure Application Insights Request telemetry instance"); Guard.NotNull(logEvent.Properties, nameof(logEvent), "Requires a Serilog event with a set of properties to create an Azure Application Insights Request telemetry instance"); StructureValue logEntry = logEvent.Properties.GetAsStructureValue(ContextProperties.RequestTracking.RequestLogEntry); string requestMethod = logEntry.Properties.GetAsRawString(nameof(RequestLogEntry.RequestMethod)); string requestHost = logEntry.Properties.GetAsRawString(nameof(RequestLogEntry.RequestHost)); string requestUri = logEntry.Properties.GetAsRawString(nameof(RequestLogEntry.RequestUri)); string responseStatusCode = logEntry.Properties.GetAsRawString(nameof(RequestLogEntry.ResponseStatusCode)); TimeSpan requestDuration = logEntry.Properties.GetAsTimeSpan(nameof(RequestLogEntry.RequestDuration)); DateTimeOffset requestTime = logEntry.Properties.GetAsDateTimeOffset(nameof(RequestLogEntry.RequestTime)); IDictionary <string, string> context = logEntry.Properties.GetAsDictionary(nameof(RequestLogEntry.Context)); string operationId = logEvent.Properties.GetAsRawString(ContextProperties.Correlation.OperationId); var requestName = $"{requestMethod} {requestUri}"; bool isSuccessfulRequest = DetermineRequestOutcome(responseStatusCode); var url = new Uri($"{requestHost}{requestUri}"); var requestTelemetry = new RequestTelemetry(requestName, requestTime, requestDuration, responseStatusCode, isSuccessfulRequest) { Id = operationId, Url = url, }; requestTelemetry.Properties.AddRange(context); return(requestTelemetry); }
public bool TryDestructure(object value, ILogEventPropertyValueFactory propertyValueFactory, out LogEventPropertyValue result) { if (value is T) { var properties = value.GetType().GetAllProperties(); var logEventProperties = new List <LogEventProperty>(); foreach (var propertyInfo in properties) { var propValue = propertyValueFactory.CreatePropertyValue(propertyInfo.GetValue(value), destructureObjects: true); if (_propertyNames.Contains(propertyInfo.Name) == _shouldContain) { propValue = propValue.AsSensitive(); } logEventProperties.Add(new LogEventProperty(propertyInfo.Name, propValue)); } result = new StructureValue(logEventProperties); return(true); } result = null; return(false); }
/// <summary> /// Visit a <see cref="StructureValue"/> value. /// </summary> /// <param name="state">Operation state.</param> /// <param name="structure">The value to visit.</param> /// <returns>The result of visiting <paramref name="structure"/>.</returns> protected override bool VisitStructureValue(TextWriter state, StructureValue structure) { state.Write('{'); var delim = ""; for (var i = 0; i < structure.Properties.Count; i++) { state.Write(delim); delim = ","; var prop = structure.Properties[i]; WriteQuotedJsonString(prop.Name, state); state.Write(':'); Visit(state, prop.Value); } if (_typeTagName != null && structure.TypeTag != null) { state.Write(delim); WriteQuotedJsonString(_typeTagName, state); state.Write(':'); WriteQuotedJsonString(structure.TypeTag, state); } state.Write('}'); return(false); }
/// <summary> /// Appends the INamable which match the name provided in retVal /// </summary> /// <param name="name"></param> /// <param name="retVal"></param> public void Find(string name, List <INamable> retVal) { if (!_buildingDeclaredElements) { try { _buildingDeclaredElements = true; StructureValue structureValue = Value as StructureValue; if (structureValue != null) { structureValue.Find(name, retVal); } // Dereference of an empty value holds the empty value EmptyValue emptyValue = Value as EmptyValue; if (emptyValue != null) { retVal.Add(emptyValue); } } finally { _buildingDeclaredElements = false; } } }
/// <summary> /// Visit a <see cref="StructureValue"/> value. /// </summary> /// <param name="state">Operation state.</param> /// <param name="structure">The value to visit.</param> /// <returns>The result of visiting <paramref name="structure"/>.</returns> protected override LogEventPropertyValue VisitStructureValue(TState state, StructureValue structure) { if (structure == null) { throw new ArgumentNullException(nameof(structure)); } for (var i = 0; i < structure.Properties.Count; ++i) { var original = structure.Properties[i]; if (!ReferenceEquals(original.Value, Visit(state, original.Value))) { var properties = new LogEventProperty[structure.Properties.Count]; // There's no need to visit any earlier elements: they all evaluated to // a reference equal with the original so just fill in the array up until `i`. for (var j = 0; j < i; ++j) { properties[j] = structure.Properties[j]; } for (var k = i; k < properties.Length; ++k) { var property = structure.Properties[k]; properties[k] = new LogEventProperty(property.Name, Visit(state, property.Value)); } return(new StructureValue(properties, structure.TypeTag)); } } return(structure); }
/// <summary> /// Creates a telemetry entry for a given log event /// </summary> /// <param name="logEvent">Event that was logged and written to this sink</param> /// <param name="formatProvider">Provider to format event</param> /// <returns>Telemetry entry to emit to Azure Application Insights</returns> protected override DependencyTelemetry CreateTelemetryEntry(LogEvent logEvent, IFormatProvider formatProvider) { Guard.NotNull(logEvent, nameof(logEvent), "Requires a Serilog log event to create an Azure Application Insights Dependency telemetry instance"); Guard.NotNull(logEvent.Properties, nameof(logEvent), "Requires a Serilog event with a set of properties to create an Azure Application Insights Dependency telemetry instance"); StructureValue logEntry = logEvent.Properties.GetAsStructureValue(ContextProperties.DependencyTracking.DependencyLogEntry); string dependencyType = logEntry.Properties.GetAsRawString(nameof(DependencyLogEntry.DependencyType)); string dependencyName = logEntry.Properties.GetAsRawString(nameof(DependencyLogEntry.DependencyName)); string target = logEntry.Properties.GetAsRawString(nameof(DependencyLogEntry.TargetName)); string data = logEntry.Properties.GetAsRawString(nameof(DependencyLogEntry.DependencyData)); DateTimeOffset startTime = logEntry.Properties.GetAsDateTimeOffset(nameof(DependencyLogEntry.StartTime)); TimeSpan duration = logEntry.Properties.GetAsTimeSpan(nameof(DependencyLogEntry.Duration)); string resultCode = logEntry.Properties.GetAsRawString(nameof(DependencyLogEntry.ResultCode)); bool outcome = logEntry.Properties.GetAsBool(nameof(DependencyLogEntry.IsSuccessful)); IDictionary <string, string> context = logEntry.Properties.GetAsDictionary(nameof(DependencyLogEntry.Context)); string operationId = logEvent.Properties.GetAsRawString(ContextProperties.Correlation.OperationId); var dependencyTelemetry = new DependencyTelemetry(dependencyType, target, dependencyName, data, startTime, duration, resultCode, success: outcome) { Id = operationId }; dependencyTelemetry.Properties.AddRange(context); return(dependencyTelemetry); }
public bool TryDestructure(object value, ILogEventPropertyValueFactory propertyValueFactory, out LogEventPropertyValue result) { if (value is Interval interval) { if (interval.HasStart) { // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression if (interval.HasEnd) // start and end { result = propertyValueFactory.CreatePropertyValue(new { interval.Start, interval.End }, destructureObjects: true); } else // start only { result = propertyValueFactory.CreatePropertyValue(new { interval.Start }, destructureObjects: true); } } else if (interval.HasEnd) // end only { result = propertyValueFactory.CreatePropertyValue(new { interval.End }, destructureObjects: true); } else // neither { result = new StructureValue(new LogEventProperty[0]); } return(true); } else { result = null; return(false); } }
static void WriteProperties( IEnumerable <KeyValuePair <string, LogEventPropertyValue> > properties, TextWriter output ) { output.Write(",\"Data\":{"); var precedingDelimiter = ""; foreach (var property in properties.Where(IsRenderedProperty)) { StructureValue structure = property.Value as StructureValue; if (structure != null) { FlattenAndWriteStructure(structure, output, ref precedingDelimiter); } else { output.Write(precedingDelimiter); precedingDelimiter = ","; JsonValueFormatter.WriteQuotedJsonString(property.Key, output); output.Write(':'); ValueFormatter.Format(property.Value, output); } } output.Write('}'); }
public void Can_Generate_Api_Xml() { //Arrange var expected = new XElement("StructureAttribute", new XAttribute("id", "46"), new XAttribute("name", "bar"), new XElement("StructureValue", new XAttribute("langId", "10"), new XAttribute("scope", "global"), new XCData("foo"))); var value = new StructureValue { LanguageId = 10, Value = "foo" }; var attr = new StructureAttribute { DefinitionId = 46, Name = "bar", Values = new List <StructureValue> { value } }; //Act var actual = attr.ToAdsml(); //Assert Assert.That(actual, Is.Not.Null); Assert.That(actual.ToString(), Is.EqualTo(expected.ToString())); }
/// <summary> /// Executes the action requested by this tool strip button /// </summary> protected override void OnClick(EventArgs e) { Collection collectionType = (Collection)Variable.Type; Structure structureType = (Structure)collectionType.Type; StructureValue element = new StructureValue(structureType, false); if (structureType.Elements.Count == 1) { StructureElement subElement = (StructureElement)structureType.Elements[0]; Structure subElementStructureType = subElement.Type as Structure; if (subElementStructureType != null) { element.CreateField(subElement, structureType); } } ListValue value = Variable.Value.RightSide(Variable, false, true) as ListValue; Variable.Value = value; if (value != null) { value.Val.Add(element); element.Enclosing = value; } base.OnClick(e); }
public ActionResult <StructureValue> PostStructureValue(StructureValue structureValue) { _context.StructureValue.Add(structureValue); _context.SaveChanges(); return(CreatedAtAction("GetStructureValue", new { id = structureValue.Id }, structureValue)); }
public bool TryResolve(object value, IMessagePropertyValueFactory nest, out MessagePropertyValue result) { if (value is Interval interval) { if (interval.HasStart) { // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression if (interval.HasEnd) { // start and end result = nest.CreatePropertyValue(new { interval.Start, interval.End }, PropertyResolvingMode.Destructure); } else { // start only result = nest.CreatePropertyValue(new { interval.Start }, PropertyResolvingMode.Destructure); } } else if (interval.HasEnd) { // end only result = nest.CreatePropertyValue(new { interval.End }, PropertyResolvingMode.Destructure); } else { // neither result = new StructureValue(new MessageProperty[0]); } return(true); } result = null; return(false); }
private static object ToRawValue(LogEventPropertyValue logEventValue) { // Special-case a few types of LogEventPropertyValue that allow us to maintain better type fidelity. // For everything else take the default string rendering as the data. ScalarValue scalarValue = logEventValue as ScalarValue; if (scalarValue != null) { return(scalarValue.Value); } SequenceValue sequenceValue = logEventValue as SequenceValue; if (sequenceValue != null) { object[] arrayResult = sequenceValue.Elements.Select(e => ToRawScalar(e)).ToArray(); if (arrayResult.Length == sequenceValue.Elements.Count) { // All values extracted successfully, it is a flat array of scalars return(arrayResult); } } StructureValue structureValue = logEventValue as StructureValue; if (structureValue != null) { IDictionary <string, object> structureResult = new Dictionary <string, object>(structureValue.Properties.Count); foreach (var property in structureValue.Properties) { structureResult[property.Name] = ToRawScalar(property.Value); } if (structureResult.Count == structureValue.Properties.Count) { if (structureValue.TypeTag != null) { structureResult["$type"] = structureValue.TypeTag; } return(structureResult); } } DictionaryValue dictionaryValue = logEventValue as DictionaryValue; if (dictionaryValue != null) { IDictionary <string, object> dictionaryResult = dictionaryValue.Elements .Where(kvPair => kvPair.Key.Value is string) .ToDictionary(kvPair => (string)kvPair.Key.Value, kvPair => ToRawScalar(kvPair.Value)); if (dictionaryResult.Count == dictionaryValue.Elements.Count) { return(dictionaryResult); } } // Fall back to string rendering of the value return(logEventValue.ToString()); }
public IActionResult PutStructureValue(long id, StructureValue structureValue) { if (id != structureValue.Id) { return(BadRequest()); } _context.Entry(structureValue).State = EntityState.Modified; try { _context.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!StructureValueExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public void Test_Format_Sequence() { // arrange var name = "Scope"; var sequenceValue = "HTTP POST https://apigateway.mhdev.se/member-service/int/v2.0/members"; var scalar = new SequenceValue(new List <LogEventPropertyValue> { new ScalarValue(sequenceValue) }); var logEventProperty = new LogEventProperty(name, scalar); var structureValue = new StructureValue(new List <LogEventProperty> { logEventProperty }); var _formatter = new MhSensitivePropertyValueFormatter(); var logEvent = new LogEvent( new System.DateTimeOffset(), LogEventLevel.Information, null, new MessageTemplate("", new List <MessageTemplateToken>()), new List <LogEventProperty> { new LogEventProperty("BaseModel", structureValue) }); // act _formatter.Format(logEvent); var baseModel = logEvent.Properties["BaseModel"] as StructureValue; var result = baseModel.Properties[0]; // assert Assert.Equal(name, result.Name); Assert.NotNull(result.Value); }
public void Test_AdditionalKeywords(string name, string value, string keyWordToAdd, string expected) { // arrange var scalar = new ScalarValue(value); var logEventProperty = new LogEventProperty(name, scalar); var structureValue = new StructureValue(new List <LogEventProperty> { logEventProperty }); var _formatter = new MhSensitivePropertyValueFormatter(new List <string> { keyWordToAdd }); var logEvent = new LogEvent( new System.DateTimeOffset(), LogEventLevel.Information, null, new MessageTemplate("", new List <MessageTemplateToken>()), new List <LogEventProperty> { new LogEventProperty("BaseModel", structureValue) }); // act _formatter.Format(logEvent); var baseModel = logEvent.Properties["BaseModel"] as StructureValue; var result = baseModel.Properties[0]; // assert Assert.Equal(name, result.Name); Assert.Equal(new ScalarValue(expected), result.Value); }
private void WriteStructureValue(Utf8JsonWriter writer, string key, StructureValue val, bool array) { if (key != null) { writer.WritePropertyName(HandleKeyPrefix(this.Options.ObjectKeyPrefix, key, array)); if (array) { writer.WriteStartArray(); } } writer.WriteStartObject(); if (this.Options.WriteObjectTypeTag && val.TypeTag != null) { writer.WriteString(this.Options.ObjectTypeTagPropertyName, val.TypeTag); } foreach (LogEventProperty property in val.Properties) { WriteProperty(writer, property.Name, property.Value, false); } writer.WriteEndObject(); }
/// <summary> /// Constructor /// </summary> /// <param name="args"></param> /// <param name="value"></param> /// <param name="element"></param> public ToolStripAddStructureMember(CellRightClickEventArgs args, StructureValue value, StructureElement element) : base(args, "Add " + element.Name) { Value = value; Element = element; }
/// <summary> /// Creates a single target /// </summary> /// <param name="start"></param> /// <param name="length"></param> /// <param name="speed"></param> /// <returns></returns> private StructureValue CreateTarget(double start, double length, double speed) { NameSpace defaultNameSpace = OverallNameSpaceFinder.INSTANCE.findByName(EFSSystem.Dictionaries[0], "Default"); Structure structureType = (Structure) EFSSystem.FindType( defaultNameSpace, "TargetStruct"); StructureValue value = new StructureValue(structureType); Field speedV = value.CreateField(value, "Speed", structureType); speedV.Value = new DoubleValue(EFSSystem.DoubleType, speed); Field location = value.CreateField(value, "Location", structureType); location.Value = new DoubleValue(EFSSystem.DoubleType, start); Field lengthV = value.CreateField(value, "Length", structureType); lengthV.Value = new DoubleValue(EFSSystem.DoubleType, length); Enum targetType = (Enum)EFSSystem.FindType(defaultNameSpace, "TargetTypeEnum"); Field type = value.CreateField(value, "Type", structureType); type.Value = targetType.DefaultValue; return(value); }
public override void CopyFrom(IPropertyModel property) { if (property is StructProperty structProperty) { StructureValue.CopyFrom(structProperty.StructureValue); } }
public bool TryDestructure(object value, ILogEventPropertyValueFactory propertyValueFactory, out LogEventPropertyValue result) { if (value is TodoItemQuery todoItemQuery) { result = new StructureValue(new List <LogEventProperty> { new LogEventProperty(nameof(todoItemQuery.Id), new ScalarValue(todoItemQuery.Id)), new LogEventProperty(nameof(todoItemQuery.NamePattern), new ScalarValue(todoItemQuery.NamePattern)), new LogEventProperty(nameof(todoItemQuery.IsComplete), new ScalarValue(todoItemQuery.IsComplete)), new LogEventProperty(nameof(todoItemQuery.Owner), new ScalarValue(todoItemQuery.Owner.GetNameOrDefault())), new LogEventProperty(nameof(todoItemQuery.PageIndex), new ScalarValue(todoItemQuery.PageIndex)), new LogEventProperty(nameof(todoItemQuery.PageSize), new ScalarValue(todoItemQuery.PageSize)), new LogEventProperty(nameof(todoItemQuery.SortBy), new ScalarValue(todoItemQuery.SortBy)), new LogEventProperty(nameof(todoItemQuery.IsSortAscending), new ScalarValue(todoItemQuery.IsSortAscending)) }); return(true); } result = null; return(false); }
public static void FormatStructureValue(LogEvent logEvent, TextWriter builder, StructureValue value) { if (value.TypeTag != null) { ColorCodeContext.WriteOverridden(builder, logEvent, ColorCode.StructureName, value.TypeTag + " "); } ColorCodeContext.WriteOverridden(builder, logEvent, ColorCode.Value, "{"); var isFirst = true; foreach (var property in value.Properties) { if (!isFirst) { ColorCodeContext.WriteOverridden(builder, logEvent, ColorCode.Value, ", "); } isFirst = false; ColorCodeContext.WriteOverridden(builder, logEvent, ColorCode.StructureName, property.Name); ColorCodeContext.WriteOverridden(builder, logEvent, ColorCode.Value, "="); Format(logEvent, property.Value, builder, null, property.Name); } ColorCodeContext.WriteOverridden(builder, logEvent, ColorCode.Value, "}"); }
public void StructuresFormatAsAnObject() { var structure = new StructureValue(new[] { new LogEventProperty("A", new ScalarValue(123)) }, "T"); var f = Format(structure); Assert.Equal("{\"A\": 123, \"$type\": \"T\"}", f); }
private static string format_euroloop_message(DBMessage message) { EfsSystem system = EfsSystem.Instance; NameSpace nameSpace = findNameSpace("Messages.EUROLOOP"); Structure structureType = (Structure)system.FindType(nameSpace, "Message"); StructureValue structure = new StructureValue(structureType); int currentIndex = 0; FillStructure(nameSpace, message.Fields, ref currentIndex, structure); // then we fill the packets IVariable subSequenceVariable; if (structure.SubVariables.TryGetValue("Sequence1", out subSequenceVariable)) { subSequenceVariable.Value = get_message_packets(message, nameSpace, system); } else { throw new Exception("Cannot find SubSequence in variable"); } return(structure.Name); }
/// <summary> /// Provides the value of the function /// </summary> /// <param name="context"></param> /// <param name="actuals">the actual parameters values</param> /// <param name="explain"></param> /// <returns>The value for the function application</returns> public override IValue Evaluate(InterpretationContext context, Dictionary <Actual, IValue> actuals, ExplanationPart explain) { IValue retVal = null; int token = context.LocalScope.PushContext(); AssignParameters(context, actuals); StructureValue startDate = context.FindOnStack(StartDate).Value as StructureValue; if (startDate != null) { int year = GetIntValue(startDate, "Year"); int month = GetIntValue(startDate, "Month"); int day = GetIntValue(startDate, "Day"); int hour = GetIntValue(startDate, "Hour"); int minute = GetIntValue(startDate, "Minute"); int second = GetIntValue(startDate, "Second"); int tts = GetIntValue(startDate, "TTS"); DoubleValue addedTime = context.FindOnStack(Increment).Value as DoubleValue; if (addedTime != null) { DateTime start = new DateTime(year, month, day, hour, minute, second, tts); DateTime currentTime = start.AddSeconds(addedTime.Val); retVal = GetEfsDate(currentTime, startDate.Type as Structure); } } context.LocalScope.PopContext(token); return(retVal); }
private static void WriteStructureValue(string key, StructureValue structureValue, IDictionary <string, string> properties) { foreach (var eventProperty in structureValue.Properties) { WriteValue(key + "." + eventProperty.Name, eventProperty.Value, properties); } }
public static void Render(MessageTemplate template, IReadOnlyDictionary <string, LogEventPropertyValue> properties, MessageTemplate outputTemplate, TextWriter output, string format, IFormatProvider formatProvider = null) { if (format?.Contains("j") == true) { var sv = new StructureValue(properties .Where(kvp => !(TemplateContainsPropertyName(template, kvp.Key) || TemplateContainsPropertyName(outputTemplate, kvp.Key))) .Select(kvp => new LogEventProperty(kvp.Key, kvp.Value))); JsonValueFormatter.Format(sv, output); return; } output.Write("{ "); var delim = ""; foreach (var kvp in properties) { if (TemplateContainsPropertyName(template, kvp.Key) || TemplateContainsPropertyName(outputTemplate, kvp.Key)) { continue; } output.Write(delim); delim = ", "; output.Write(kvp.Key); output.Write(": "); kvp.Value.Render(output, null, formatProvider); } output.Write(" }"); }
public override bool CompareForEquality(IValue left, IValue right) // left == right { bool retVal = base.CompareForEquality(left, right); if (!retVal) { if (left != null && right != null && left.Type == right.Type) { StructureValue leftValue = left as StructureValue; StructureValue rightValue = right as StructureValue; if (leftValue != null && rightValue != null) { retVal = true; foreach (KeyValuePair <string, IVariable> pair in leftValue.SubVariables) { IVariable leftVar = pair.Value; IVariable rightVar = rightValue.GetVariable(pair.Key); if (leftVar.Type != null) { retVal = leftVar.Type.CompareForEquality(leftVar.Value, rightVar.Value); if (!retVal) { break; } } } } } } return(retVal); }
/// <summary> /// Provides the int value which corresponds to a specific field of the structure provided /// </summary> /// <param name="structure"></param> /// <param name="name"></param> /// <returns></returns> private int GetIntValue(StructureValue structure, string name) { IVariable variable = structure.Val[name] as IVariable; IntValue intValue = variable.Value as IntValue; int retVal = (int)intValue.Val; return(retVal); }
public void Should_Be_Able_To_Instantiate_New_StructureValue() { //Act var value = new StructureValue(); //Assert Assert.That(value, Is.Not.Null); }
/// <summary> /// Creates a variable according to the structure element provided /// </summary> /// <param name="element"></param> /// <returns></returns> private static Field CreateField(StructureElement element) { Structure elementStructureType = (Structure) element.Type; StructureValue subValue = new StructureValue(elementStructureType, false); Field retVal = new Field(elementStructureType, element); retVal.Value = subValue; return retVal; }
/// <summary> /// Constructor /// </summary> /// <param name="args"></param> /// <param name="value"></param> /// <param name="element"></param> public ToolStripAddStructureMember(CellRightClickEventArgs args, StructureValue value, StructureElement element) : base(args, "Add " + element.Name) { Value = value; Element = element; }
/// <summary> /// Creates a single target /// </summary> /// <param name="start"></param> /// <param name="length"></param> /// <param name="speed"></param> /// <returns></returns> private StructureValue CreateTarget(double start, double length, double speed) { Structure structureType = (Structure) EFSSystem.FindType( OverallNameSpaceFinder.INSTANCE.findByName(EFSSystem.Dictionaries[0], "Kernel.SpeedAndDistanceMonitoring.TargetSpeedMonitoring"), "Kernel.SpeedAndDistanceMonitoring.TargetSpeedMonitoring.Target"); StructureValue value = new StructureValue(structureType); Field speedV = value.CreateField(value, "Speed", structureType); speedV.Value = new DoubleValue(EFSSystem.DoubleType, speed); Field location = value.CreateField(value, "Location", structureType); location.Value = new DoubleValue(EFSSystem.DoubleType, start); Field lengthV = value.CreateField(value, "Length", structureType); lengthV.Value = new DoubleValue(EFSSystem.DoubleType, length); return value; }
/// <summary> /// Provides the value associated to this Expression /// </summary> /// <param name="context">The context on which the value must be found</param> /// <param name="explain">The explanation to fill, if any</param> /// <returns></returns> protected internal override IValue GetValue(InterpretationContext context, ExplanationPart explain) { StructureValue retVal = null; Structure structureType = Structure.GetExpressionType() as Structure; if (structureType != null) { retVal = new StructureValue(this, context, explain); } else { AddError("Cannot determine structure type for " + ToString()); } return retVal; }
private static string format_euroradio_message(DBMessage message) { EfsSystem system = EfsSystem.Instance; NameSpace rbcRoot = findNameSpace("Messages.MESSAGE"); // Get the EFS namespace corresponding to the message // Select the appropriate message type, tracktotrain or traintotrack DBField nidMessage = message.Fields[0] as DBField; string msg_id = get_namespace_from_ID(nidMessage.Value); NameSpace nameSpace = OverallNameSpaceFinder.INSTANCE.findByName(rbcRoot, msg_id); if (nameSpace == null) { throw new Exception("Message type not found in EFS"); } // The EURORADIO messages are defined in the namespaces TRACK_TO_TRAIN and TRAIN_TO_TRACK, which enclose the specific message namespaces // So we get the message type from nameSpace.EnclosingNameSpace and the actual structure corresponding to the message in nameSpace Structure enclosingStructureType = (Structure) system.FindType(nameSpace.EnclosingNameSpace, "Message"); StructureValue Message = new StructureValue(enclosingStructureType); // Within the message, get the appropriate field and get that structure Structure structureType = (Structure) system.FindType(nameSpace, "Message"); StructureValue structure = new StructureValue(structureType); // Fill the structure int currentIndex = 0; FillStructure(nameSpace, message.Fields, ref currentIndex, structure); // Fill the default packets int translatedPackets = 0; foreach (KeyValuePair<string, IVariable> subVariable in structure.SubVariables) { if (subVariable.Value.TypeName.EndsWith("Message")) { // The structure of packets will always be a Message, but in some cases, it is a message that contains // the different options for a single field in the message structure.GetVariable(subVariable.Value.Name).Value = FillDefaultPacket(message, subVariable.Value); translatedPackets++; } } // and fill the packets IVariable subSequenceVariable; if (structure.SubVariables.TryGetValue("Sequence1", out subSequenceVariable) && message.Packets.Count > translatedPackets) { subSequenceVariable.Value = get_message_packets(message, nameSpace, system); } // Fill the correct field in Message with the structure. foreach (KeyValuePair<string, IVariable> pair in Message.SubVariables) { string[] ids = msg_id.Split('.'); if (ids[ids.Length-1].Equals(pair.Key)) { pair.Value.Type = structureType; pair.Value.Value = structure; } } return Message.Name; }
/// <summary> /// Handles a drop event /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void TimeLineControl_DragDrop(object sender, DragEventArgs e) { if (e.Data.GetDataPresent("WindowsForms10PersistentObject", false)) { BaseTreeNode sourceNode = e.Data.GetData("WindowsForms10PersistentObject") as BaseTreeNode; if (sourceNode != null) { VariableTreeNode variableNode = sourceNode as VariableTreeNode; if (variableNode != null) { SubStep subStep = SubStepRelatedToMousePosition(); if (subStep != null) { // Create the default value IValue value = null; Expression expression = null; string defaultValue = variableNode.Item.Default; if (defaultValue != null) { const bool doSemanticalAnalysis = true; const bool silent = true; expression = new Parser().Expression(variableNode.Item, defaultValue, AllMatches.INSTANCE, doSemanticalAnalysis, null, silent); } if (expression != null) { InterpretationContext context = new InterpretationContext {UseDefaultValue = false}; value = expression.GetExpressionValue(context, null); } if (value == null || value is EmptyValue) { Structure structureType = variableNode.Item.Type as Structure; if (structureType != null) { const bool setDefaultValue = false; value = new StructureValue(structureType, setDefaultValue); } } // Create the action or the expectation according to the keyboard modifier keys if (value != null) { if ((e.KeyState & Ctrl) != 0) { Expectation expectation = (Expectation) acceptor.getFactory().createExpectation(); expectation.ExpressionText = variableNode.Item.FullName + " == " + value.FullName; subStep.appendExpectations(expectation); } else { Action action = (Action) acceptor.getFactory().createAction(); action.ExpressionText = variableNode.Item.FullName + " <- " + value.FullName; subStep.appendActions(action); } } else { MessageBox.Show( Resources .StaticTimeLineControl_TimeLineControl_DragDrop_Cannot_evaluate_variable_default_value, Resources.StaticTimeLineControl_TimeLineControl_DragDrop_Cannot_create_event, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } } } }
/// <summary> /// Provides the int value which corresponds to a specific field of the structure provided /// </summary> /// <param name="structure"></param> /// <param name="name"></param> /// <returns></returns> private int GetIntValue(StructureValue structure, string name) { int retVal = 0; Variable variable = structure.Val[name] as Variable; IntValue intValue = variable.Value as IntValue; retVal = (int) intValue.Val; return retVal; }
/// <summary> /// Coputes targets from the function and adds them to the collection /// </summary> /// <param name="function">Function containing targets</param> /// <param name="collection">Collection to be filled with targets</param> private void ComputeTargets(Function function, ListValue collection) { if (function != null) { Graph graph = function.Graph; if (graph != null && graph.Segments.Count > 1) { double prevSpeed = graph.Segments[0].Evaluate(graph.Segments[0].Start); for (int i = 1; i < graph.Segments.Count; i++) { Graph.Segment s = graph.Segments[i]; Structure structureType = (Structure) EFSSystem.FindType( OverallNameSpaceFinder.INSTANCE.findByName(EFSSystem.Dictionaries[0], "Kernel.SpeedAndDistanceMonitoring.TargetSpeedMonitoring"), "Kernel.SpeedAndDistanceMonitoring.TargetSpeedMonitoring.Target"); StructureValue value = new StructureValue(structureType); Variable speed = (Variable) acceptor.getFactory().createVariable(); speed.Type = EFSSystem.FindType( OverallNameSpaceFinder.INSTANCE.findByName(EFSSystem.Dictionaries[0], "Default.BaseTypes"), "Default.BaseTypes.Speed"); speed.Name = "Speed"; speed.Mode = acceptor.VariableModeEnumType.aInternal; speed.Default = "0.0"; speed.Enclosing = value; speed.Value = new DoubleValue(EFSSystem.DoubleType, s.Evaluate(s.Start)); value.set(speed); Variable location = (Variable) acceptor.getFactory().createVariable(); location.Type = EFSSystem.FindType( OverallNameSpaceFinder.INSTANCE.findByName(EFSSystem.Dictionaries[0], "Default.BaseTypes"), "Default.BaseTypes.Distance"); location.Name = "Location"; location.Mode = acceptor.VariableModeEnumType.aInternal; location.Default = "0.0"; location.Enclosing = value; location.Value = new DoubleValue(EFSSystem.DoubleType, s.Start); value.set(location); Variable length = (Variable) acceptor.getFactory().createVariable(); length.Type = EFSSystem.FindType( OverallNameSpaceFinder.INSTANCE.findByName(EFSSystem.Dictionaries[0], "Default.BaseTypes"), "Default.BaseTypes.Length"); length.Name = "Length"; length.Mode = acceptor.VariableModeEnumType.aInternal; length.Default = "0.0"; length.Enclosing = value; length.Value = SegmentLength(s.End); value.set(length); // Only add the target for the current segment to the collection if it brings a reduction in permitted speed if (s.Evaluate(s.Start) < prevSpeed) { collection.Val.Add(value); } // But even if it is not added to the collection of targets, this segment is now the reference speed prevSpeed = s.Evaluate(s.Start); } } } }
/// <summary> /// Executes the action requested by this tool strip button /// </summary> protected override void OnClick(EventArgs e) { Structure elementStructureType = (Structure) Element.Type; StructureValue subValue = new StructureValue(elementStructureType, false); Variable subVariable = (Variable) acceptor.getFactory().createVariable(); subVariable.Name = Element.Name; subVariable.Type = Element.Type; subVariable.Value = subValue; Value.set(subVariable); base.OnClick(e); }
/// <summary> /// Coputes targets from the function and adds them to the collection /// </summary> /// <param name="function">Function containing targets</param> /// <param name="collection">Collection to be filled with targets</param> private void ComputeTargets(Function function, ListValue collection) { if (function != null) { Graph graph = function.Graph; if (graph != null && graph.Segments.Count > 1) { NameSpace defaultNameSpace = OverallNameSpaceFinder.INSTANCE.findByName(EFSSystem.Dictionaries[0], "Default"); Structure structureType = (Structure) EFSSystem.FindType( defaultNameSpace, "TargetStruct" ); double prevSpeed = graph.Segments[0].Evaluate(graph.Segments[0].Start); for (int i = 1; i < graph.Segments.Count; i++) { Graph.Segment s = graph.Segments[i]; StructureValue value = new StructureValue(structureType); Field speed = value.CreateField(value, "Speed", structureType); speed.Value = new DoubleValue(EFSSystem.DoubleType, s.Evaluate(s.Start)); Field location = value.CreateField(value, "Location", structureType); location.Value = new DoubleValue(EFSSystem.DoubleType, s.Start); Field length = value.CreateField(value, "Length", structureType); length.Value = SegmentLength(s.End); Enum targetType = (Enum) EFSSystem.FindType(defaultNameSpace, "TargetTypeEnum"); Field type = value.CreateField(value, "Type", structureType); type.Value = targetType.DefaultValue; // Only add the target for the current segment to the collection if it brings a reduction in permitted speed if (s.Evaluate(s.Start) < prevSpeed) { collection.Val.Add(value); } // But even if it is not added to the collection of targets, this segment is now the reference speed prevSpeed = s.Evaluate(s.Start); } } } }
/// <summary> /// Creates a single target /// </summary> /// <param name="start"></param> /// <param name="length"></param> /// <param name="speed"></param> /// <returns></returns> private StructureValue CreateSegment(double start, double length, double speed) { NameSpace defaultNameSpace = OverallNameSpaceFinder.INSTANCE.findByName(EFSSystem.Dictionaries[0], "Default"); Structure structureType = (Structure) EFSSystem.FindType( defaultNameSpace, "SegmentStruct"); StructureValue value = new StructureValue(structureType); Field speedV = value.CreateField(value, "Speed", structureType); speedV.Value = new DoubleValue(EFSSystem.DoubleType, speed); Field location = value.CreateField(value, "Location", structureType); location.Value = new DoubleValue(EFSSystem.DoubleType, start); Field lengthV = value.CreateField(value, "Length", structureType); lengthV.Value = new DoubleValue(EFSSystem.DoubleType, length); return value; }
/// <summary> /// Finds the type of the structure corresponding to the provided NID_PACKET /// </summary> /// <param name="nameSpace">The namespace where the type has to be found</param> /// <param name="nidPacket">The id of the packet</param> /// <returns></returns> private static StructureValue FindStructure(int nidPacket) { EfsSystem system = EfsSystem.Instance; Structure structure = null; NameSpace nameSpace = findNameSpace("Messages.PACKET.TRACK_TO_TRAIN"); foreach (NameSpace packetNameSpace in nameSpace.NameSpaces) { Structure structureType = (Structure) system.FindType(packetNameSpace, packetNameSpace.FullName + ".Message"); StructureValue structureValue = new StructureValue(structureType); foreach (KeyValuePair<string, IVariable> pair in structureValue.SubVariables) { string variableName = pair.Key; if (variableName.Equals("NID_PACKET")) { IntValue value = pair.Value.Value as IntValue; if (value.Val == nidPacket) { structure = structureType; } } if (structure != null) { break; } } if (structure != null) { break; } } StructureValue retVal = null; if (structure != null) { retVal = new StructureValue(structure); } return retVal; }
private static ListValue get_message_packets(DBMessage message, NameSpace nameSpace, EfsSystem system) { ListValue retVal; Collection collectionType = (Collection) system.FindType(nameSpace, "Collection1"); Structure subStructure1Type = (Structure) system.FindType(nameSpace, "SubStructure1"); string packetLocation = "Messages.PACKET."; if (nameSpace.FullName.Contains("TRAIN_TO_TRACK")) { packetLocation += "TRAIN_TO_TRACK.Message"; } else { packetLocation += "TRACK_TO_TRAIN.Message"; } Structure packetStructureType = (Structure) system.FindType(nameSpace, packetLocation); retVal = new ListValue(collectionType, new List<IValue>()); foreach (DBPacket packet in message.Packets) { DBField nidPacketField = packet.Fields[0] as DBField; if (nidPacketField.Value != "255") // 255 means "end of information" { int packetId = int.Parse(nidPacketField.Value); StructureValue subStructure = FindStructure(packetId); int currentIndex = 0; FillStructure(nameSpace, packet.Fields, ref currentIndex, subStructure); StructureValue subStructure1 = new StructureValue(subStructure1Type); // For Balise messages, we have an extra level of information to fill, so here we define StructureVal in one of two ways StructureValue structureVal; if (subStructure1.SubVariables.Count == 1 && subStructure1.SubVariables.ContainsKey("TRACK_TO_TRAIN")) { // For a Balise message, we have an extra level of structures for TRACK_TO_TRAIN structureVal = new StructureValue(packetStructureType); subStructure1.SubVariables["TRACK_TO_TRAIN"].Value = structureVal; } else { // For RBC, the collection directly holds the different packet types structureVal = subStructure1; } // Find the right variable in the packet to add the structure we just created foreach (KeyValuePair<string, IVariable> pair in structureVal.SubVariables) { string variableName = pair.Key; string[] ids = subStructure.Structure.FullName.Split('.'); if (ids[ids.Length-2].Equals(variableName)) { pair.Value.Value = subStructure; retVal.Val.Add(subStructure1); break; } } } } return retVal; }
/// <summary> /// Executes the action requested by this tool strip button /// </summary> protected override void OnClick(EventArgs e) { Structure elementStructureType = (Structure) Element.Type; StructureValue subValue = new StructureValue(elementStructureType, false); Field field = Value.CreateField(Element, elementStructureType); field.Value = subValue; base.OnClick(e); }
/// <summary> /// Executes the action requested by this tool strip button /// </summary> protected override void OnClick(EventArgs e) { Collection collectionType = (Collection) Variable.Type; Structure structureType = (Structure) collectionType.Type; StructureValue element = new StructureValue(structureType, false); if (structureType.Elements.Count == 1) { StructureElement subElement = (StructureElement) structureType.Elements[0]; Structure subElementStructureType = subElement.Type as Structure; if (subElementStructureType != null) { element.CreateField(subElement, structureType); } } Variable.Value = Variable.Value.RightSide(Variable, false, true) as ListValue; ListValue value = Variable.Value as ListValue; if (value != null) { value.Val.Add (element); element.Enclosing = value; } base.OnClick(e); }
/// <summary> /// Executes the action requested by this tool strip button /// </summary> protected override void OnClick(EventArgs e) { Collection collectionType = (Collection) Variable.Type; Structure structureType = (Structure) collectionType.Type; StructureValue element = new StructureValue(structureType, false); if (structureType.Elements.Count == 1) { StructureElement subElement = (StructureElement) structureType.Elements[0]; Structure subElementStructureType = subElement.Type as Structure; if (subElementStructureType != null) { element.CreateField(subElement, structureType); } } Variable.Value = Variable.Value.RightSide(Variable, false, true) as ListValue; ListValue value = Variable.Value as ListValue; if (value != null) { for (int i = 0; i < value.Val.Count; i++) { if (value.Val[i] == EfsSystem.Instance.EmptyValue) { value.Val[i] = element; element.Enclosing = Variable.Value; break; } } } base.OnClick(e); }
/// <summary> /// Fills the given structure with the values provided from the database /// </summary> /// <param name="aNameSpace">Namespace of the structure</param> /// <param name="fields">Fields to be copied into the structure</param> /// <param name="index">Index (of fields list) from which we have to start copying</param> /// <param name="aStructure">The structure to be filled</param> private static void FillStructure(NameSpace aNameSpace, ArrayList fields, ref int currentIndex, StructureValue aStructure) { EFSSystem system = EFSSystem.INSTANCE; int j = 0; while (currentIndex < fields.Count) { DBField field = fields[currentIndex] as DBField; KeyValuePair<string, IVariable> pair = aStructure.SubVariables.ElementAt(j); IVariable variable = pair.Value; // conditional variables can be missing in the database fields, but present in our structure => skip them while (!variable.Name.StartsWith(field.Variable) && j < aStructure.SubVariables.Count - 1) { j++; pair = aStructure.SubVariables.ElementAt(j); variable = pair.Value; } if (variable.Name.StartsWith(field.Variable)) // we use StartsWith and not Equals because we can have N_ITER_1 and N_ITER { if (variable.Type is Enum) { Enum type = variable.Type as Enum; foreach (EnumValue enumValue in type.Values) { int value = int.Parse(enumValue.getValue()); int other = int.Parse(field.Value); if (value == other) { variable.Value = enumValue; j++; break; } } } else if (variable.Type is Range) { Range type = variable.Type as Range; object v = VariableConverter.INSTANCE.Convert(variable.Name, field.Value); variable.Value = new IntValue(type, (int) v); j++; } else if (variable.Type is StringType) { StringType type = variable.Type as StringType; variable.Value = new StringValue(type, field.Value); j++; } else { throw new Exception("Unhandled variable type"); } if (variable.Name.StartsWith("N_ITER")) // we have to create a sequence { KeyValuePair<string, IVariable> sequencePair = aStructure.SubVariables.ElementAt(j); IVariable sequenceVariable = sequencePair.Value; Collection collectionType = (Collection) system.FindType(aNameSpace, sequenceVariable.TypeName); ListValue sequence = new ListValue(collectionType, new List<IValue>()); int value = int.Parse(field.Value); for (int k = 0; k < value; k++) { currentIndex++; Structure structureType = (Structure) system.FindType(aNameSpace, sequence.CollectionType.Type.FullName); StructureValue structureValue = new StructureValue(structureType); FillStructure(aNameSpace, fields, ref currentIndex, structureValue); sequence.Val.Add(structureValue); } sequenceVariable.Value = sequence; j++; } } // if all the fields of the structue are filled, we terminated if (j == aStructure.SubVariables.Count) { break; } else { currentIndex += 1; } } }
/// <summary> /// Creates a EFS DateAndTime structure from a System.DateTime /// </summary> /// <param name="value">The values that will go into the structure</param> /// <param name="structureType">The structure type</param> /// <returns></returns> private IValue GetEFSDate(DateTime value, Structure structureType) { IValue retVal = null; StructureValue structure = new StructureValue(structureType); structure.SubVariables["Year"].Value = ToEFSInt(value.Year); structure.SubVariables["Month"].Value = ToEFSInt(value.Month); structure.SubVariables["Day"].Value = ToEFSInt(value.Day); structure.SubVariables["Hour"].Value = ToEFSInt(value.Hour); structure.SubVariables["Minute"].Value = ToEFSInt(value.Minute); structure.SubVariables["Second"].Value = ToEFSInt(value.Second); structure.SubVariables["TTS"].Value = ToEFSInt(value.Millisecond); retVal = structure; return retVal; }
private static string format_euroloop_message(DBMessage message) { EfsSystem system = EfsSystem.Instance; NameSpace nameSpace = findNameSpace("Messages.EUROLOOP"); Structure structureType = (Structure) system.FindType(nameSpace, "Message"); StructureValue structure = new StructureValue(structureType); int currentIndex = 0; FillStructure(nameSpace, message.Fields, ref currentIndex, structure); // then we fill the packets IVariable subSequenceVariable; if (structure.SubVariables.TryGetValue("Sequence1", out subSequenceVariable)) { subSequenceVariable.Value = get_message_packets(message, nameSpace, system); } else { throw new Exception("Cannot find SubSequence in variable"); } return structure.Name; }
/// <summary> /// Creates a single target /// </summary> /// <param name="start"></param> /// <param name="length"></param> /// <param name="speed"></param> /// <returns></returns> private StructureValue CreateTarget(double start, double length, double speed) { Structure structureType = (Structure) EFSSystem.FindType( OverallNameSpaceFinder.INSTANCE.findByName(EFSSystem.Dictionaries[0], "Kernel.SpeedAndDistanceMonitoring.TargetSpeedMonitoring"), "Kernel.SpeedAndDistanceMonitoring.TargetSpeedMonitoring.Target"); StructureValue value = new StructureValue(structureType); Variable speedV = (Variable) acceptor.getFactory().createVariable(); speedV.Type = EFSSystem.FindType( OverallNameSpaceFinder.INSTANCE.findByName(EFSSystem.Dictionaries[0], "Default.BaseTypes"), "Default.BaseTypes.Speed"); speedV.Name = "Speed"; speedV.Mode = acceptor.VariableModeEnumType.aInternal; speedV.Default = "0.0"; speedV.Enclosing = value; speedV.Value = new DoubleValue(EFSSystem.DoubleType, speed); value.set(speedV); Variable location = (Variable) acceptor.getFactory().createVariable(); location.Type = EFSSystem.FindType( OverallNameSpaceFinder.INSTANCE.findByName(EFSSystem.Dictionaries[0], "Default.BaseTypes"), "Default.BaseTypes.Distance"); location.Name = "Location"; location.Mode = acceptor.VariableModeEnumType.aInternal; location.Default = "0.0"; location.Enclosing = value; location.Value = new DoubleValue(EFSSystem.DoubleType, start); value.set(location); Variable lengthV = (Variable) acceptor.getFactory().createVariable(); lengthV.Type = EFSSystem.FindType( OverallNameSpaceFinder.INSTANCE.findByName(EFSSystem.Dictionaries[0], "Default.BaseTypes"), "Default.BaseTypes.Length"); lengthV.Name = "Length"; lengthV.Mode = acceptor.VariableModeEnumType.aInternal; lengthV.Default = "0.0"; lengthV.Enclosing = value; lengthV.Value = new DoubleValue(EFSSystem.DoubleType, length); value.set(lengthV); return value; }
private static IValue FillDefaultPacket(DBMessage message, IVariable structure) { IValue retVal = structure.Value; if (isPacket(structure)) { Structure defaultPacketType = (Structure) structure.Type; StructureValue defaultPacket = new StructureValue(defaultPacketType); NameSpace packetNameSpace = structure.NameSpace; foreach (DBPacket packet in message.Packets) { DBField nidPacketField = packet.Fields[0] as DBField; int packetID = int.Parse(nidPacketField.Value); Structure packetType = (Structure) FindStructure(packetID).Type; if (packetType == defaultPacketType) { int defaultPacketIndex = 0; FillStructure(packetNameSpace, packet.Fields, ref defaultPacketIndex, defaultPacket); retVal = defaultPacket; } } } else { Structure structureType = structure.Type as Structure; StructureValue Structure = new StructureValue(structureType); if (Structure != null) { foreach (KeyValuePair<string, IVariable> subVariable in Structure.SubVariables) { if (isPacket(subVariable.Value)) { Structure defaultPacketType = (Structure) subVariable.Value.Type; StructureValue defaultPacket = new StructureValue(defaultPacketType); NameSpace packetNameSpace = subVariable.Value.NameSpace; foreach (DBPacket packet in message.Packets) { DBField nidPacketField = packet.Fields[0] as DBField; int packetID = int.Parse(nidPacketField.Value); Structure packetType = (Structure) FindStructure(packetID).Type; if (packetType == defaultPacketType) { int defaultPacketIndex = 0; FillStructure(packetNameSpace, packet.Fields, ref defaultPacketIndex, defaultPacket); Structure.GetVariable(subVariable.Value.Name).Value = defaultPacket; } } } } retVal = Structure; } } return retVal; }
/// <summary> /// Fills the given structure with the values provided from the database /// </summary> /// <param name="aNameSpace">Namespace of the structure</param> /// <param name="fields">Fields to be copied into the structure</param> /// <param name="index">Index (of fields list) from which we have to start copying</param> /// <param name="aStructure">The structure to be filled</param> private static void FillStructure(NameSpace aNameSpace, ArrayList fields, ref int currentIndex, StructureValue aStructure) { EfsSystem system = EfsSystem.Instance; int j = 0; while (currentIndex < fields.Count) { bool foundMatch = false; DBField field = fields[currentIndex] as DBField; KeyValuePair<string, IVariable> pair = aStructure.SubVariables.ElementAt(j); IVariable variable = pair.Value; // Conditioned variables can be missing in the database fields, but present in our structure => skip them while (!variable.Name.StartsWith(field.Variable) && j < aStructure.SubVariables.Count - 1) { j++; pair = aStructure.SubVariables.ElementAt(j); variable = pair.Value; } // We use StartsWith and not Equals because we can have N_ITER_1 and N_ITER if (variable.Name.StartsWith(field.Variable)) { foundMatch = true; if (variable.Type is Enum) { Enum type = variable.Type as Enum; foreach (EnumValue enumValue in type.Values) { int value = int.Parse(enumValue.getValue()); int other = int.Parse(field.Value); if (value == other) { variable.Value = enumValue; j++; break; } } } else if (variable.Type is Range) { Range type = variable.Type as Range; object v = VariableConverter.INSTANCE.Convert(variable.Name, field.Value); string stringValue = v as string; if (stringValue != null) { int intValue; if (int.TryParse(stringValue, out intValue)) { v = intValue; } else if (stringValue.EndsWith(" b")) { stringValue = stringValue.Substring(0, stringValue.Length - 2); v = Convert.ToInt32(stringValue, 2); } } variable.Value = new IntValue(type, (int) v); j++; } else if (variable.Type is StringType) { StringType type = variable.Type as StringType; variable.Value = new StringValue(type, field.Value); j++; } else { throw new Exception("Unhandled variable type"); } if (variable.Name.StartsWith("N_ITER")) // we have to create a sequence { KeyValuePair<string, IVariable> sequencePair = aStructure.SubVariables.ElementAt(j); IVariable sequenceVariable = sequencePair.Value; Collection collectionType = (Collection) system.FindType(aNameSpace, sequenceVariable.TypeName); ListValue sequence = new ListValue(collectionType, new List<IValue>()); int value = int.Parse(field.Value); for (int k = 0; k < value; k++) { currentIndex++; Structure structureType = (Structure) system.FindType(aNameSpace, sequence.CollectionType.Type.FullName); StructureValue structureValue = new StructureValue(structureType); FillStructure(aNameSpace, fields, ref currentIndex, structureValue); sequence.Val.Add(structureValue); } sequenceVariable.Value = sequence; j++; } } // Special case for X_TEXT if ("Sequence1".Equals(variable.Name) && "X_TEXT".Equals(field.Variable)) { foundMatch = true; KeyValuePair<string, IVariable> sequencePair = aStructure.SubVariables.ElementAt(j); IVariable sequenceVariable = sequencePair.Value; Collection collectionType = (Collection)system.FindType(aNameSpace, sequenceVariable.TypeName); ListValue sequence = new ListValue(collectionType, new List<IValue>()); while (field != null && "X_TEXT".Equals(field.Variable)) { if (string.IsNullOrEmpty(field.Value)) { field.Value = " "; } Structure structureType = (Structure)system.FindType(aNameSpace, sequence.CollectionType.Type.FullName); StructureValue structureValue = new StructureValue(structureType); FillStructure(aNameSpace, fields, ref currentIndex, structureValue); sequence.Val.Add(structureValue); currentIndex += 1; if ( currentIndex < fields.Count) { field = fields[currentIndex] as DBField; } else { field = null; } } sequenceVariable.Value = sequence; j++; } // if all the fields of the structue are filled, we terminated if (j == aStructure.SubVariables.Count ) { break; } else if (!foundMatch) { // We used a lookahead to determine if we needed to fill the structure // But the encountered field is not the right one // (for instance, because of a conditional field determiner by a Q_XXX value) // => Rollback currentIndex -= 1; break; } else { currentIndex += 1; } } }
/// <summary> /// Creates a variable according to the structure element provided /// </summary> /// <param name="element"></param> /// <returns></returns> private static Variable CreateVariable(StructureElement element) { Structure elementStructureType = (Structure) element.Type; StructureValue subValue = new StructureValue(elementStructureType, false); Variable retVal = (Variable) acceptor.getFactory().createVariable(); retVal.Name = element.Name; retVal.Type = element.Type; retVal.Value = subValue; return retVal; }