public LiteCrawlerStorage(string fileName) { BsonDocument BsonFromImage(ICrawlerImage image) { return(new BsonDocument { ["_id"] = image.ImageId, ["url"] = image.ImageUrl, ["tags"] = new BsonArray(image.HumanoidTags.Select(t => new BsonValue(t))) }); } ICrawlerImage ImageFromBson(BsonValue value) { var doc = value.AsDocument; return(new AutoTaggerImage { ImageId = doc["_id"], ImageUrl = doc["url"], HumanoidTags = doc["tags"].AsArray.Select(t => t.AsString) }); } var mapper = new BsonMapper(); mapper.RegisterType(BsonFromImage, ImageFromBson); var database = new LiteDatabase(fileName, mapper); this.images = database.GetCollection <ICrawlerImage>("images"); }
/// <summary> /// Registers mappings for a specific ExtendableEnum type with a Value property type of string. /// </summary> /// <param name="mapper">The <see cref="BsonMapper"/> for which the mapping will be registered.</param> /// <param name="type">An ExtendableEnum <see cref="Type"/> which is to be registered.</param> public static void RegisterExtendableEnumAsString(this BsonMapper mapper, Type type) { if (mapper == null) { throw new ArgumentNullException(nameof(mapper)); } if (type == null) { throw new ArgumentNullException(nameof(type)); } if (!type.IsExtendableEnum()) { throw new ArgumentException("The type must be an ExtendableEnum.", nameof(type)); } var valueProperty = type.GetProperty("Value"); if (valueProperty.PropertyType != typeof(string)) { throw new ArgumentException("The ExtendableEnum type must have a value type of string.", nameof(type)); } var parseMethod = type.GetMethod("ParseValue", BindingFlags.Static | BindingFlags.FlattenHierarchy | BindingFlags.Public); mapper.RegisterType(type, s => ((IExtendableEnum <string>)s).Value, b => parseMethod.Invoke(null, new object[] { b.AsString })); }
public virtual void Register(BsonMapper bsonMapper) { BsonMapper = bsonMapper ?? throw new ArgumentNullException(nameof(bsonMapper)); BsonMapper.RegisterType( serialize: Serialize, deserialize: Deserialize); }
protected void RegisterType <TIdentity>() where TIdentity : Identity <TIdentity> { _mapper.RegisterType <TIdentity>( (id) => id.Value, (bson) => (TIdentity)Activator.CreateInstance(typeof(TIdentity), (object)bson.AsGuid) ); }
public static void RegisterIdBsonMappers(this BsonMapper mapper, Assembly assemblyToScanForTypes = null) { var types = GetIHasIdTypes(assemblyToScanForTypes); foreach (var type in types) { mapper.RegisterType(type, obj => ((IGuidValue)obj).Value.ToString("N"), value => Activator.CreateInstance(type, new Guid(value.AsString))); } }
public void RegisterCustomSerializers(BsonMapper mapper) { //this implementation is only for testing as the simulator doesn't save it's state BsonMapper defaultMapper = new BsonMapper(); BsonValue OrderToBson(Order order) { return(defaultMapper.Serialize(typeof(IOrder), order)); } Order BsonToOrder(BsonValue value) { var order = DeserializedOrders.FirstOrDefault(o => o.Id == value["_id"].AsString); if (order == null) { DeserializedOrders.Add(order = defaultMapper.Deserialize <Order>(value)); } return(order); } BsonValue SerializeTrade(Trade trade) { return(defaultMapper.Serialize(typeof(ITrade), trade)); } Trade DeserializeTrade(BsonValue value) { var trade = DeserializedTrades.FirstOrDefault(o => o.Id == value["_id"].AsString); if (trade == null) { DeserializedTrades.Add(trade = defaultMapper.Deserialize <Trade>(value)); } return(trade); } mapper.RegisterType <Order>(OrderToBson, BsonToOrder); mapper.RegisterType <Trade>(SerializeTrade, DeserializeTrade); }
public static void MapSimpleValueObjects(this BsonMapper mapper) { var simpleValueObjectTypes = from type in PizzaMaster.PizzaMasterAssembly.ExportedTypes where type.IsClass && !type.IsAbstract where type.IsAssignableTo <ISingleValueObject>() select type; foreach (var type in simpleValueObjectTypes) { mapper.RegisterType(type, o => new BsonValue(((ISingleValueObject)o).GetValue()), v => Activator.CreateInstance(type, v.RawValue)); } }
/// <summary> /// Create a new instance of the BmpCoffer manager based on the given LiteDB database. /// </summary> /// <param name="dbPath"></param> /// <returns></returns> internal static BmpCoffer CreateInstance(string dbPath) { var mapper = new BsonMapper(); mapper.RegisterType ( group => group.Index, bson => Instrument.Parse(bson.AsInt32) ); mapper.RegisterType ( group => group.Index, bson => InstrumentTone.Parse(bson.AsInt32) ); mapper.RegisterType ( group => group.Index, bson => OctaveRange.Parse(bson.AsInt32) ); mapper.RegisterType ( tempoMap => SerializeTempoMap(tempoMap), bson => DeserializeTempoMap(bson.AsBinary) ); mapper.RegisterType ( trackChunk => SerializeTrackChunk(trackChunk), bson => DeserializeTrackChunk(bson.AsBinary) ); var dbi = new LiteDatabase(dbPath, mapper); MigrateDatabase(dbi); return(new BmpCoffer(dbi)); }
public LiteConfigStore( ConnectionString connectionString, CommandService commands, BsonMapper mapper = null, Func <LogMessage, Task> logger = null) { _connectionString = connectionString ?? throw new ArgumentNullException(nameof(connectionString)); _commands = commands ?? throw new ArgumentNullException(nameof(commands)); _mapper = mapper ?? BsonMapper.Global; _logger = logger ?? Extensions.NoOpLogger; _mapper.RegisterType <ulong>( serialize: (ul => new BsonValue((long)ul)), deserialize: (val => (ulong)val.AsInt64)); }
public static void RegisterIdBsonMappers(this BsonMapper mapper, Assembly assemblyToScanForTypes = null) { if (assemblyToScanForTypes == null) { assemblyToScanForTypes = Assembly.GetExecutingAssembly(); } var iHasTraits = typeof(IHasTraits); var types = assemblyToScanForTypes.GetTypes() .Select(x => (type: x, interfaces: x.GetInterfaces())) .Where(x => x.interfaces.Contains(iHasTraits)) .Where(HasId); var idType = typeof(Id <>); foreach (var type in types) { var idClosed = idType.MakeGenericType(type.type); mapper.RegisterType(idClosed, obj => ((IGuidValue)obj).Value.ToString("N"), value => Activator.CreateInstance(idClosed, new Guid(value.AsString))); } }
private BsonMapper Create() { var mapper = new BsonMapper(); mapper.RegisterType <HashHeightPair> ( serialize: (hash) => hash.ToString(), deserialize: (bson) => HashHeightPair.Parse(bson.AsString) ); mapper.RegisterType <OutPoint> ( serialize: (outPoint) => outPoint.ToString(), deserialize: (bson) => OutPoint.Parse(bson.AsString) ); mapper.RegisterType <uint256> ( serialize: (hash) => hash.ToString(), deserialize: (bson) => uint256.Parse(bson.AsString) ); mapper.RegisterType <Money> ( serialize: (money) => money.Satoshi, deserialize: (bson) => Money.Satoshis(bson.AsInt64) ); mapper.RegisterType <Script> ( serialize: (script) => Encoders.Hex.EncodeData(script.ToBytes(false)), deserialize: (bson) => Script.FromBytesUnsafe(Encoders.Hex.DecodeData(bson.AsString)) ); mapper.RegisterType <PartialMerkleTree> ( serialize: (pmt) => Encoders.Hex.EncodeData(pmt.ToBytes()), deserialize: (bson) => { var ret = new PartialMerkleTree(); var bytes = Encoders.Hex.DecodeData(bson.AsString); ret.ReadWrite(bytes); return(ret); } ); return(mapper); }
public BsonMapper CreateMapper() { var mapper = new BsonMapper(); mapper.UseLowerCaseDelimiter('_'); #if NAMEVALUECOLLECTION mapper.RegisterType( nv => { var doc = new BsonDocument(); foreach (var key in nv.AllKeys) { doc[key] = nv[key]; } return(doc); }, bson => { var nv = new NameValueCollection(); var doc = bson.AsDocument; foreach (var key in doc.Keys) { nv[key] = doc[key].AsString; } return(nv); } ); #endif return(mapper); }
public static void Register(BsonMapper mapper) { IEntity GetValue(Type type, int id) { if (type == typeof(Exercise)) { return(new Exercise { Id = id }); } if (type == typeof(Muscle)) { return(new Muscle { Id = id }); } if (type == typeof(Category)) { return(new Category { Id = id }); } throw new ArgumentException("Invalid value type"); } Type GetType(string typeName) => Type.GetType(typeName); mapper.RegisterType( filter => { var doc = new Dictionary <string, BsonValue> { { "_id", filter.Id }, { "name", filter.Name }, }; if (filter.Metric.HasValue) { doc.Add("metric", (int)filter.Metric.Value); } if (filter.GroupBy.HasValue) { doc.Add("groupBy", (int)filter.GroupBy.Value); } if (filter.FilterBy.HasValue) { doc.Add("filterBy", (int)filter.FilterBy.Value); doc.Add("valueType", filter.FilteringValue.GetType().AssemblyQualifiedName); doc.Add("valueId", filter.FilteringValue.Id); } return(doc); }, bsonValue => { var doc = bsonValue.AsDocument; var filterBy = doc["filterBy"].RawValue; var groupBy = doc["groupBy"].RawValue; var metric = doc["metric"].RawValue; var filter = new ProgressFilter { Id = doc["_id"], Name = doc["name"], }; if (filterBy != null) { filter.FilterBy = (FilterBy)filterBy; filter.FilteringValue = GetValue(GetType(doc["valueType"].AsString), doc["valueId"].AsInt32); } if (groupBy != null) { filter.GroupBy = (GroupBy)groupBy; } if (metric != null) { filter.Metric = (FilterMetric)metric; } return(filter); } ); }