protected override string FormatNonNullValue(FormatContext context, PostalAddress postalAddress, int indentLevel) { IDictionary <string, string> attributeMap = new Dictionary <string, string>(); string useAttribute = GetUseAttribute(context.Type, postalAddress, context.GetVersion().GetBaseVersion()); if (StringUtils.IsNotBlank(useAttribute)) { attributeMap["use"] = useAttribute; } Boolean?isNotOrdered = postalAddress.IsNotOrdered; if (isNotOrdered != null) { attributeMap["isNotOrdered"] = isNotOrdered.ToString().ToLower(); } //lowercase for .NET StringBuilder buffer = new StringBuilder(); buffer.Append(CreateElement(context, attributeMap, indentLevel, false, true)); foreach (PostalAddressPart postalAddressPart in postalAddress.Parts) { AppendPostalAddressPart(buffer, postalAddressPart, indentLevel + 1); } IDictionary <PlatformDate, SetOperator> useablePeriods = postalAddress.UseablePeriods; foreach (PlatformDate date in useablePeriods.Keys) { SetOperator @operator = useablePeriods.SafeGet(date); AppendUseablePeriod(buffer, date, @operator, indentLevel + 1, context); } buffer.Append(CreateElementClosure(context, indentLevel, true)); return(buffer.ToString()); }
private void ValidateDatePattern(string datePattern, FormatContext context) { StandardDataType standardDataType = StandardDataType.GetByTypeName(context); VersionNumber version = (context == null ? null : context.GetVersion()); string[] allowedDateFormats = TsDateFormats.GetAllDateFormats(standardDataType, version); if (ArrayContains(allowedDateFormats, datePattern)) { // check if this pattern is missing a timezone if (!IsCerx(standardDataType, version) && TsDateFormats.datetimeFormatsRequiringWarning.Contains(datePattern)) { context.GetModelToXmlResult().AddHl7Error(new Hl7Error(Hl7ErrorCode.DATA_TYPE_ERROR, System.String.Format("Date format {0} supplied for value of type {1} should also have a timezone (ZZZZZ)" , datePattern, context == null ? "TS" : context.Type), context.GetPropertyPath())); } } else { // MBR-368: a temporary work-around for producing AB PIN compliant date time renderings // with out error messages -- required until the runtime's knowledge of datatypes has been // corrected to distinguish between CeRx v3 (ie., V01R03) and CeRx v4 (ie., V01R04) if (!SpecificationVersion.IsExactVersion(SpecificationVersion.V01R04_1_AB, version)) { context.GetModelToXmlResult().AddHl7Error(new Hl7Error(Hl7ErrorCode.DATA_TYPE_ERROR, System.String.Format("Invalid date format {0} supplied for value of type {1}" , datePattern, context == null ? "TS" : context.Type), context.GetPropertyPath())); } } }
private void HandleConstraints(Identifier identifier, FormatContext context) { ErrorLogger logger = new _ErrorLogger_164(context); this.constraintsHandler.HandleConstraints(context.GetConstraints(), identifier, logger, IsSingleCardinality(context.GetCardinality ())); }
private static bool FormatCurrentVariables( KernelValues instance, FormatContext context) { PocketView output = null; if (instance.Detailed) { output = table( thead( tr( th("Variable"), th("Type"), th("Value"))), tbody( instance.Select(v => tr( td(v.Name), td(v.Type), td(div[@class: "dni-plaintext"](v.Value.ToDisplayString())) )))); } else { output = div(instance.Select(v => v.Name + "\t ")); } output.WriteTo(context); return(true); }
public override string Format(FormatContext context, BareANY hl7Value, int indentLevel) { string result = base.Format(context, hl7Value, indentLevel); if (hl7Value != null) { string originalText = ((ANYMetaData)hl7Value).OriginalText; bool hasNullFlavor = hl7Value.HasNullFlavor(); bool hasAnyValues = HasAnyValues(hl7Value); this.pqValidationUtils.ValidateOriginalText(context.Type, originalText, hasAnyValues, hasNullFlavor, context.GetVersion() , null, context.GetPropertyPath(), context.GetModelToXmlResult()); // complete hack for BC if (SpecificationVersion.IsExactVersion(context.GetVersion(), SpecificationVersion.V02R04_BC)) { if (hasNullFlavor && HasAnyValues(hl7Value)) { // dump the result and rebuild, adding in NF IDictionary <string, string> attributeNameValuePairs = GetAttributeNameValuePairs(context, (PhysicalQuantity)hl7Value.BareValue , hl7Value); attributeNameValuePairs.PutAll(CreateNullFlavorAttributes(hl7Value.NullFlavor)); result = CreateElement(context, attributeNameValuePairs, indentLevel, true, true); } } if (StringUtils.IsNotBlank(originalText)) { string otElement = CreateElement("originalText", null, indentLevel + 1, false, false); otElement += XmlStringEscape.Escape(originalText); otElement += CreateElementClosure("originalText", 0, true); // pulling off the end "/>" is not the most elegant solution, but superclass would need significant refactoring otherwise result = Ca.Infoway.Messagebuilder.StringUtils.Substring(result, 0, result.IndexOf("/>")) + ">" + SystemUtils.LINE_SEPARATOR + otElement + CreateElementClosure(context.GetElementName(), indentLevel, true); } } return(result); }
private static void WriteImageTo(Frame frame, FormatContext fc) { Codec codec = Codec.FindEncoder(fc.OutputFormat.VideoCodec); var mediaStream = new MediaStream(fc); using CodecContext codecContext = new CodecContext(codec) { PixelFormat = codec.PixelFormats.First(), Width = frame.Width, Height = frame.Height, TimeBase = new MediaRational(1, 25), Flags = fc.OutputFormat.Flags.HasFlag(FormatOutputFlag.Globalheader) ? CodecFlag.GlobalHeader : CodecFlag.None, }; codecContext.Open(codec); mediaStream.Codecpar.CopyFrom(codecContext); if ((PixelFormat)frame.Format == codecContext.PixelFormat) { WriteAction(frame, fc, codecContext); } else { using var tempFrame = Frame.CreateWritableVideo(frame.Width, frame.Height, codecContext.PixelFormat); using var frameConverter = new FrameConverter(); frameConverter.ConvertFrame(frame, tempFrame); WriteAction(tempFrame, fc, codecContext); } }
protected override string FormatNonNullDataType(FormatContext context, BareANY dataType, int indentLevel) { EncapsulatedData encapsulatedData = ExtractBareValue(dataType); HandleConstraints(encapsulatedData, context.GetConstraints(), context.GetPropertyPath(), context.GetModelToXmlResult()); IDictionary <string, string> attributes = CreateAttributes(encapsulatedData, context); bool hasContent = HasContent(encapsulatedData); bool hasReferenceOrThumbnailOrDocument = HasReferenceOrThumbnailOrDocument(encapsulatedData); if (!this.isR2) { AddSpecializationType(encapsulatedData, attributes, context.Type, dataType.DataType, context.GetVersion()); Validate(context, dataType, encapsulatedData); } StringBuilder buffer = new StringBuilder(); buffer.Append(CreateElement(context, attributes, indentLevel, !hasContent, hasReferenceOrThumbnailOrDocument)); if (hasContent) { WriteReference(encapsulatedData, buffer, indentLevel + 1, context); WriteThumbnail(encapsulatedData, buffer, indentLevel + 1, context); this.edContentRenderer.RenderContent(encapsulatedData, buffer, indentLevel + 1, context, hasReferenceOrThumbnailOrDocument ); buffer.Append(CreateElementClosure(context, hasReferenceOrThumbnailOrDocument ? indentLevel : 0, true)); } return(buffer.ToString()); }
private void CheckNameForTn(EntityName entityName, FormatContext context) { int numParts = entityName.Parts.Count; if (numParts > 1) { // only 1 allowed RecordError(context, "TN values can only have one name part. Parts found: " + numParts); } if (numParts >= 1) { EntityNamePart tnPart = entityName.Parts[0]; if (tnPart.Type != null) { // no part types allowed RecordError(context, "TN values can not have a name part type. Part type found: " + tnPart.Type.Value); } if (tnPart.Qualifier != null) { // no qualifier allowed RecordError(context, "TN values can not have any qualifiers. Qualifier found: " + tnPart.Qualifier.CodeValue); } } if (!entityName.Uses.IsEmpty()) { // uses not allowed RecordError(context, "TN values can not have any uses specified. Uses found: " + entityName.Uses.ToString()); } }
private void LogValueNotAllowed(string propertyName, FormatContext context) { string message = System.String.Format("Relationships of type \"{0}\" are not allowed to have the \"{1}\" property.", context .Type, propertyName); RecordError(message, context); }
public bool Format(FormatContext context, CurrentVariables instance, TextWriter writer) { PocketView output = null; /// <summary> /// Renders the tag to the specified <see cref = "TextWriter" />. /// </summary> /// <param name = "writer">The writer.</param> if (instance.Detailed) { var innerContext = context.ReduceContent(FormatContext.NestedInTable); output = table( thead( tr( th("Variable"), th("Type"), th("Value"))), tbody( instance.Select(v => tr( // Note, embeds these as objects into the HTML content, ultimately rendered by PocketView td(v.Name), td(embed(v.Type, innerContext)), td(embed(v.Value, innerContext)) )))); } else { output = div(instance.Select(v => v.Name + "\t ")); } output.WriteTo(writer, HtmlEncoder.Default); return(true); }
private void Validate(Int32?integer, FormatContext context, BareANY bareAny) { if (integer.Value < 0) { RecordNotNegativeError(integer, context.GetPropertyPath(), context.GetModelToXmlResult()); } }
public override void Evaluate(FormatContext context, char character) { if (character == '_') { if (TryConsumeMoniker(context, context.Buffer.ToString())) { context.Buffer.Append(' '); context.Flush(); } else { Next?.Evaluate(context, character); } return; } if (context.HasMoreText) { Next?.Evaluate(context, character); } else if (TryConsumeMoniker(context, context.Buffer.ToString() + character)) { context.Flush(); } else { Next?.Evaluate(context, character); } }
// only checking II constraints for now protected virtual FormatContext CreateSubContext(FormatContext context) { return(new Ca.Infoway.Messagebuilder.Marshalling.HL7.Formatter.FormatContextImpl(context.GetModelToXmlResult(), context.GetPropertyPath (), context.GetElementName(), GetSubType(context), context.GetDomainType(), context.GetConformanceLevel(), context.GetCardinality (), context.IsSpecializationType(), context.GetVersion(), context.GetDateTimeZone(), context.GetDateTimeTimeZone(), null , null, context.IsCda())); }
protected virtual string CreatePivlTsElement(FormatContext context, PeriodicIntervalTime value, int indentLevel) { PivlTsPropertyFormatter formatter = new GtsBoundedPivlFormatter.CustomPivlTsPropertyFormatter(!RequiresOperatorOnFirstRepetition (context), RequiresSpecializationType(context)); return(formatter.Format(context, new PIVLImpl(value), indentLevel)); }
public void Format(FormatContext context, TSegment entity) { var length = 0; var entityContext = context.CreateEntityContext(entity); var segmentContext = entityContext.SetLevel(FormatLevel.Segment); var elementSeparator = segmentContext.Settings.ElementSeparator; for (var i = 0; i < _formatters.Length; i++) { if (i > 0) { context.Append(elementSeparator); } var position = context.Position; _formatters[i].Format(entityContext.CreateEntityContext(entity)); if (position < context.Position) { length = context.Position; } } if (length == 0) { context.Clear(); } else { context.Trim(length); } }
public void Format(FormatContext context, TEntity entity) { for (int i = 0; i < _formatters.Length; i++) { _formatters[i].Format(context.CreateEntityContext(entity)); } }
private void Validate(StringBuilder buffer, int indentLevel, FormatContext context, bool isStLang, BareANY dataType) { // ST.LANG not allowed for CeRx; not checking as this should be controlled by the message set // is ST allowed to be 0 length or only whitespace??? ModelToXmlResult result = context.GetModelToXmlResult(); string language = GetLanguage(dataType); if (isStLang) { if (!STImpl.ALLOWED_LANGUAGES.Contains(language)) { Hl7Error hl7Error = new Hl7Error(Hl7ErrorCode.DATA_TYPE_ERROR, System.String.Format("The language attribute content ({0}) is not an allowed value. Using en-CA instead." , language), context.GetPropertyPath()); result.AddHl7Error(hl7Error); } } else { if (language != null) { Hl7Error hl7Error = new Hl7Error(Hl7ErrorCode.DATA_TYPE_ERROR, System.String.Format("The language attribute ({0}) is not allowed for ST element types" , language), context.GetPropertyPath()); result.AddHl7Error(hl7Error); } } }
private void RecordAnyErrors(IList <string> errors, FormatContext context) { foreach (string error in errors) { RecordError(error, context); } }
private void Validate(StringBuilder buffer, int indentLevel, FormatContext context, bool hasLang, BareANY dataType) { // ST has min length of 1 according to schema, and cannot have both a NF and text // no details on what language strings are allowed ModelToXmlResult result = context.GetModelToXmlResult(); if (dataType.HasNullFlavor()) { if (dataType.BareValue != null) { Hl7Error hl7Error = new Hl7Error(Hl7ErrorCode.DATA_TYPE_ERROR, "ST cannot have both a nullFlavour and a text value.", context .GetPropertyPath()); result.AddHl7Error(hl7Error); } } else { if (StringUtils.IsBlank(GetStringValue(dataType))) { Hl7Error hl7Error = new Hl7Error(Hl7ErrorCode.DATA_TYPE_ERROR, "ST text value must be provided.", context.GetPropertyPath ()); result.AddHl7Error(hl7Error); } } if (hasLang && StringUtils.IsBlank(GetLanguage(dataType))) { Hl7Error hl7Error = new Hl7Error(Hl7ErrorCode.DATA_TYPE_ERROR, "ST language attribute, if provided, can not be blank.", context .GetPropertyPath()); result.AddHl7Error(hl7Error); } }
public Expression Deserialize(FormatContext context) { var genericArgs = context.Type.GetGenericArguments(); //new KeyValuePair<TKey, TValue>(Read(TKey), Read(TValue)) return(New(context.Type.GetConstructor(genericArgs), context.Read(genericArgs[0]), context.Read(genericArgs[1]))); }
private void Validate(Int32?integer, FormatContext context, BareANY bareAny) { if (integer.Value <= 0) { RecordMustBeGreaterThanZeroError(integer, context.GetPropertyPath(), context.GetModelToXmlResult()); } }
protected virtual string CreateElement(FormatContext context, string name, QTY <T> value, Boolean?inclusive, bool isSxcm, int indentLevel) { string type = Hl7DataTypeName.GetParameterizedType(context.Type); if (isSxcm) { type = "SXCM<" + type + ">"; } PropertyFormatter formatter = FormatterR2Registry.GetInstance().Get(type); if (formatter != null) { bool isSpecializationType = false; FormatContext newContext = new Ca.Infoway.Messagebuilder.Marshalling.HL7.Formatter.FormatContextImpl(type, isSpecializationType , Ca.Infoway.Messagebuilder.Xml.ConformanceLevel.POPULATED, Cardinality.Create("1"), name, context); string result = formatter.Format(newContext, value, indentLevel); if (inclusive != null) { // TM - small hack to add in the inclusive attribute (low/high) (operator, simple only, is already formatted by using the SXCM type) result = result.ReplaceFirst(" value=", " inclusive=\"" + inclusive.ToString().ToLower() + "\" value="); } return(result); } else { throw new ModelToXmlTransformationException("No formatter found for " + type); } }
protected virtual string FormatAllElements(FormatContext originalContext, FormatContext subContext, ICollection <BareANY> collection, int indentLevel) { StringBuilder builder = new StringBuilder(); ValidateCardinality(originalContext, collection); PropertyFormatter formatter = this.formatterRegistry.Get(subContext.Type); if (collection.IsEmpty()) { builder.Append(formatter.Format(subContext, null, indentLevel)); } else { foreach (BareANY hl7Value in EmptyIterable <object> .NullSafeIterable <BareANY>(collection)) { string type = DetermineActualType(subContext.Type, hl7Value, originalContext.GetModelToXmlResult(), originalContext.GetPropertyPath (), originalContext.IsCda()); if (!StringUtils.Equals(type, subContext.Type)) { subContext = new Ca.Infoway.Messagebuilder.Marshalling.HL7.Formatter.FormatContextImpl(type, true, subContext); formatter = this.formatterRegistry.Get(type); } builder.Append(formatter.Format(subContext, hl7Value, indentLevel)); } } return(builder.ToString()); }
public async Task <bool> Render( ThumbnailsRenderContext ctx, ThumbnailsRenderFileInfo fileInfo, ThumbnailsRenderOption option) { await _fileService.ReadFileStream(fileInfo.FileHandle, videoStream => { using var formatContext = new FormatContext(videoStream); var attachedPicStream = formatContext.FindAttachedPicStream(); if (attachedPicStream != null) { DrawAttachedPicture(ctx, attachedPicStream); } else { var audioStream = formatContext.FindBestAudioStream(); if (audioStream == null) { throw new InvalidDataException("No audio stream found"); } DrawWaves(ctx, audioStream); } return(ValueTask.FromResult(true)); }); return(true); }
protected override void AddOtherAttributesIfNecessary(TelecommunicationAddress phonemail, IDictionary <string, string> attributes , FormatContext context, BareANY bareAny) { VersionNumber version = context.GetVersion(); string type = (bareAny == null || bareAny.DataType == null) ? null : bareAny.DataType.Type; string actualType = TEL_VALIDATION_UTILS.DetermineActualType(phonemail, context.Type, type, version, null, context.GetPropertyPath (), context.GetModelToXmlResult(), false); if (!context.Type.Equals(actualType)) { // excluding our test NFLD version to allow legacy tests to pass if (!"NEWFOUNDLAND".Equals(version == null ? null : version.VersionLiteral)) { AddSpecializationType(attributes, actualType); } } if (!phonemail.AddressUses.IsEmpty()) { StringBuilder useValue = new StringBuilder(); bool isFirst = true; foreach (Ca.Infoway.Messagebuilder.Domainvalue.TelecommunicationAddressUse addressUse in phonemail.AddressUses) { if (TEL_VALIDATION_UTILS.IsAllowableUse(actualType, addressUse, version)) { if (!isFirst) { useValue.Append(XmlRenderingUtils.SPACE); } useValue.Append(addressUse.CodeValue); isFirst = false; } } attributes["use"] = useValue.ToString(); } }
private FormatContext ValidateInterval(Interval <T> value, BareANY bareAny, FormatContext context) { string type = context.Type; IList <string> errors = new List <string>(); string specializationType = bareAny.DataType == null ? null : bareAny.DataType.Type; string newType = this.ivlValidationUtils.ValidateSpecializationType(type, specializationType, errors); RecordAnyErrors(errors, context); if (!StringUtils.Equals(type, newType)) { // replace the context with one using the specialization type context = new Ca.Infoway.Messagebuilder.Marshalling.HL7.Formatter.FormatContextImpl(newType, true, context); } bool lowProvided = RepresentationUtil.HasLow(value.Representation) && (value.Low != null || value.LowNullFlavor != null); bool highProvided = RepresentationUtil.HasHigh(value.Representation) && (value.High != null || value.HighNullFlavor != null ); bool centerProvided = RepresentationUtil.HasCentre(value.Representation) && (value.Centre != null || value.CentreNullFlavor != null); bool widthProvided = RepresentationUtil.HasWidth(value.Representation) && (value.Width != null && (value.Width.Value != null || value.Width.NullFlavor != null)); errors = this.ivlValidationUtils.ValidateCorrectElementsProvided(type, context.GetVersion(), lowProvided, highProvided, centerProvided , widthProvided); RecordAnyErrors(errors, context); errors = this.ivlValidationUtils.DoOtherValidations(type, lowProvided ? value.LowNullFlavor : null, centerProvided ? value .CentreNullFlavor : null, highProvided ? value.HighNullFlavor : null, widthProvided ? value.Width.NullFlavor : null, (widthProvided && value.Width is DateDiff) ? (DateDiff.ConvertDiff(value.Width)).Unit : null); RecordAnyErrors(errors, context); return(context); }
private void ValidateExtensionLength(string extension, FormatContext context) { if (iiValidationUtils.IsExtensionLengthInvalid(extension)) { RecordError(iiValidationUtils.GetInvalidExtensionLengthErrorMessage(extension), context); } }
private void RenderRealmCodes(PartBridge tealBean) { if (tealBean.GetRealmCode() != null) { string type = "CS"; PropertyFormatter formatter = this.formatterRegistry.Get(type); Relationship placeholderRelationship = new Relationship("realmCode", type, Cardinality.Create("0-*")); placeholderRelationship.DomainType = "Realm"; FormatContext context = Ca.Infoway.Messagebuilder.Marshalling.FormatContextImpl.Create(this.result, null, placeholderRelationship , version, null, null, null, this.isCda); foreach (Realm realm in tealBean.GetRealmCode()) { BareANY any = (BareANY)DataTypeFactory.CreateDataType(type, this.isCda && this.isR2); if (this.isR2) { ((BareANYImpl)any).BareValue = new CodedTypeR2 <Realm>(realm); } else { ((BareANYImpl)any).BareValue = realm; } string xmlFragment = formatter.Format(context, any, GetIndent()); CurrentBuffer().GetChildBuilder().Append(xmlFragment); } } }
protected override string FormatNumerator(FormatContext context, Money numerator, int indentLevel) { FormatContext newContext = new Ca.Infoway.Messagebuilder.Marshalling.HL7.Formatter.FormatContextImpl("MO", Ca.Infoway.Messagebuilder.Xml.ConformanceLevel .OPTIONAL, Cardinality.Create("0-1"), "numerator", context); return(this.moFormatter.Format(newContext, new MOImpl(numerator), indentLevel)); }
private void LogMandatoryError(FormatContext context) { string errorMessage = context.GetElementName() + " is a mandatory field, but no value is specified"; context.GetModelToXmlResult().AddHl7Error(new Hl7Error(Hl7ErrorCode.DATA_TYPE_ERROR, errorMessage, context.GetPropertyPath ())); }
/// <summary> /// Formats the specified display name. /// </summary> /// <param name="displayName">The display name to format.</param> /// <returns>The formatted display name.</returns> public string Format(string displayName) { var context = new FormatContext(displayName); while (context.HasMoreText) { rule.Evaluate(context, context.ReadNext()); } context.Flush(); return context.FormattedDisplayName.ToString(); }
public override void Evaluate(FormatContext context, char character) { switch (character) { case 'U': // same as \uHHHH without the leading '\u' TryConsumeEscapeSequence(context, character, 4); break; case 'X': // same as \xHH without the leading '\x' TryConsumeEscapeSequence(context, character, 2); break; default: Next?.Evaluate(context, character); break; } }
public override void Evaluate(FormatContext context, char character) { if (character == '.') { context.Buffer.Append(character); context.Flush(); } else { Next?.Evaluate(context, character); } }
public override void Evaluate(FormatContext context, char character) { if (character == '_') { if (TryConsumeMoniker(context, context.Buffer.ToString())) { context.Buffer.Append(' '); context.Flush(); } else { Next?.Evaluate(context, character); } return; } if (context.HasMoreText) { Next?.Evaluate(context, character); } else if (TryConsumeMoniker(context, context.Buffer.ToString() + character)) { context.Flush(); } else { Next?.Evaluate(context, character); } }
private static void TryConsumeEscapeSequence(FormatContext context, char @char, int allowedLength) { var escapeSequence = new char[allowedLength]; var consumed = 0; while (consumed < allowedLength && context.HasMoreText) { var nextChar = context.ReadNext(); escapeSequence[consumed++] = nextChar; if (IsHex(nextChar)) { continue; } context.Buffer.Append(@char); context.Buffer.Append(escapeSequence, 0, consumed); return; } context.Buffer.Append(char.ConvertFromUtf32(HexToInt32(escapeSequence))); }
public virtual void Evaluate(FormatContext context, char character) => context.Buffer.Append(character);
private bool TryConsumeMoniker(FormatContext context, string token) { var @operator = default(string); if (!tokenMonikers.TryGetValue(token, out @operator)) { return false; } context.Buffer.Clear(); context.Buffer.Append(@operator); return true; }