protected override async Task <IVh <StreamInfo> > GetSourceStreamAsync(ISubjectLoadContext ctx) { ctx.EnsureNotNull(nameof(ctx)); // await Task.CompletedTask; // Stream sourceStream = default; try { sourceStream = ResourceUtilities.RequireManifestResourceStream(uri: ctx.BaseUri.ArgProp($"{nameof(ctx)}.{nameof(ctx.BaseUri)}"), resourceName: out var resourceName); string mediaType; if (resourceName.EndsWith(value: DescriptionPackageConstants.PackageXmlFormatFileExtension, comparisonType: StringComparison.OrdinalIgnoreCase)) { mediaType = MediaTypeNameUtilities.AppXml; } else if (resourceName.EndsWith(value: DescriptionPackageConstants.PackageJsonFormatFileExtension, comparisonType: StringComparison.OrdinalIgnoreCase)) { mediaType = MediaTypeNameUtilities.AppJson; } else { mediaType = default; } return(new StreamInfo(stream: sourceStream, ownsStream: true, contentMediaType: mediaType).ToValueHolder(ownsValue: true)); } catch { sourceStream?.Dispose(); throw; } }
// TODO: Put strings into the resources. // protected virtual async Task <TSubject> DoMaterializeAsync(ISubjectLoadContext ctx, StreamInfo stream) { ctx.EnsureNotNull(nameof(ctx)); stream.EnsureNotNull(nameof(stream)); // await Task.CompletedTask; TSubject subject; var deserializedObjectAsIDisposable = default(IDisposable); try { object deserializedObject; if (IsJsonMediaType(mediaTypeName: stream.ContentMediaType)) { // JSON. // var jsonSerializer = ctx.CreateJsonSerializer(); using (var textReader = new StreamReader(stream.Stream, Encoding.UTF8, true, TextReaderWriterUtilities.DefaultBufferSize, true)) using (var jsonReader = new JsonTextReader(textReader)) deserializedObjectAsIDisposable = (deserializedObject = jsonSerializer.Deserialize(jsonReader)) as IDisposable; } else if (IsXmlMediaType(mediaTypeName: stream.ContentMediaType)) { // XML. // var xmlObjectSerializer = ctx.CreateXmlObjectSerializer(type: typeof(object)); using (var xmlReader = XmlReader.Create(input: stream.Stream, settings: ctx.CreateXmlReaderSettings().CopyWith(closeInput: false))) deserializedObjectAsIDisposable = (deserializedObject = xmlObjectSerializer.ReadObject(xmlReader, false)) as IDisposable; } else { throw new NotSupportedException($"Медиа-тип содержимого потока не поддерживается.{Environment.NewLine}\tМедиа-тип:{stream.ContentMediaType.FmtStr().GNLI2()}"); } // subject = deserializedObject as TSubject; if (subject is null && !(deserializedObject is null)) { throw new EonException(message: $"Десериализованный объект имеет тип, не совместимый с требуемым.{Environment.NewLine}\tТип десериализованного объекта:{deserializedObject.GetType().FmtStr().GNLI2()}{Environment.NewLine}\tТребуемый тип:{typeof(TSubject).FmtStr().GI2()}."); } // return(subject); } catch (Exception exception) { DisposeMany(exception: exception, disposables: deserializedObjectAsIDisposable); throw; } }