/// <summary> /// Converts a <see cref="object"/> to <see cref="System.Protobuf.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="obj"></param> /// <returns></returns> public static System.Protobuf.Value ToProtobuf(this object obj) { var value = new System.Protobuf.Value(); var objType = obj.GetType(); if (objType.IsEnumerable() && !objType.IsDictionary()) { value.ListValue = ((System.Collections.IEnumerable)obj).ToProtobuf(); } else if (objType == typeof(Dolittle.PropertyBags.PropertyBag)) { value.DictionaryValue = ((Dolittle.PropertyBags.PropertyBag)obj).ToProtobuf().AsDictionaryValue(); } else { var protobufObj = new System.Protobuf.Object(); var protobufType = obj.GetProtobufType(); protobufObj.Type = (int)protobufType; var stream = new MemoryStream(); using (var outputStream = new CodedOutputStream(stream)) { obj.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="System.Protobuf.Value"/> /// </summary> /// <param name="value"><see cref="System.Protobuf.Value"/> to read from</param> /// <returns>Value in the correct type - null if not capable of converting</returns> public static object ToCLR(this System.Protobuf.Value value) { object returnValue = null; switch (value.KindCase) { case System.Protobuf.Value.KindOneofCase.ObjectValue: returnValue = value.ObjectValue.ToCLR(); break; case System.Protobuf.Value.KindOneofCase.ListValue: returnValue = value.ListValue.ToCLR(); break; case System.Protobuf.Value.KindOneofCase.DictionaryValue: returnValue = value.DictionaryValue.ToCLR(); break; } return(returnValue); }