/// <summary> /// Converts a <see cref="object"/> to <see cref="grpc.Value"/>. /// </summary> /// <remarks> /// This is primarily used when converting propertybags to protobuf messages and scenarios when we don't /// know the actual type of obj. /// </remarks> /// <param name="source"><see cref="object"/> to convert.</param> /// <returns>Converted value.</returns> public static grpc.Value ToProtobuf(this object source) { var value = new grpc.Value(); var objType = source.GetType(); if (objType.IsEnumerable() && !objType.IsDictionary()) { value.ListValue = ((IEnumerable)source).ToProtobuf(); } else if (objType == typeof(PropertyBag)) { value.DictionaryValue = ((PropertyBag)source).ToProtobuf().AsDictionaryValue(); } else { var protobufObj = new grpc.Object(); var protobufType = source.GetProtobufType(); protobufObj.Type = (int)protobufType; var stream = new MemoryStream(); using (var outputStream = new CodedOutputStream(stream)) { source.WriteWithTypeTo(protobufType, outputStream); outputStream.Flush(); stream.Flush(); stream.Seek(0, SeekOrigin.Begin); protobufObj.Content = ByteString.CopyFrom(stream.ToArray()); } value.ObjectValue = protobufObj; } return(value); }
/// <summary> /// Read value from <see cref="grpc.Value"/>. /// </summary> /// <param name="value"><see cref="grpc.Value"/> to read from.</param> /// <returns>Value in the correct type - null if not capable of converting.</returns> public static object ToCLR(this grpc.Value value) { switch (value.KindCase) { case grpc.Value.KindOneofCase.ObjectValue: return(value.ObjectValue.ToCLR()); case grpc.Value.KindOneofCase.ListValue: return(value.ListValue.ToCLR()); case grpc.Value.KindOneofCase.DictionaryValue: return(value.DictionaryValue.ToCLR()); } return(null); }