public override object FromDB(ConverterContext context) { if (context.DbValue == DBNull.Value) { return(null); } var stringValue = (string)context.DbValue; if (stringValue.IsNullOrWhiteSpace()) { return(null); } var ordinal = context.DataRecord.GetOrdinal("Name"); var contract = context.DataRecord.GetString(ordinal); var impType = typeof(Command).Assembly.FindTypeByName(contract + "Command"); if (impType == null) { var result = Json.Deserialize <UnknownCommand>(stringValue); result.ContractName = contract; return(result); } return(Json.Deserialize(stringValue, impType)); }
static bool TryConvert(Context ctx, Arg arg, PropertyInfo prop, Type targetType, out object?result) { var value = arg.Value; var converterContext = new ConverterContext { ParseOptions = ctx.Options, Arg = arg, TargetProperty = prop, TargetType = targetType }; // User provided converters foreach (var t in ctx.Options._customConverters) { if (t.converter.TryConvert(converterContext, arg, out result)) { return(true); } } // Built in converters foreach (var c in BuiltInConverters) { if (c.TryConvert(converterContext, arg, out result)) { return(true); } } // Array if (targetType.IsArray) { var elementType = targetType.GetElementType(); // todo: get seperator from attribute or options // todo: maybe add support for quotes (so seperator can be used inside) var strValues = value.Split(','); var ar = Array.CreateInstance(elementType, strValues.Length); for (int i = 0; i < strValues.Length; i++) { var elementArg = Arg.CreateForArrayElement(arg, strValues[i]); if (TryConvert(ctx, elementArg, prop, elementType, out object?element)) { ar.SetValue(element, i); } else { throw new InvalidCastException($"Error while converting array element to type \"{elementType.FullName}\". Index: [{i}]. SourceValue: \"{strValues[i]}\""); } } result = ar; return(true); } result = null; return(false); }
public override void ConvertFromData(ConverterContext converterContext, VertexBufferBindingData data, ref VertexBufferBinding source) { Buffer buffer = null; converterContext.ConvertFromData(data.Buffer, ref buffer); source = new VertexBufferBinding(buffer, data.Declaration, data.Count, data.Stride, data.Offset); }
/// <summary> /// Creates convert context. /// </summary> /// <param name="project">The project.</param> /// <param name="config">The convert config.</param> /// <returns>Convert context.</returns> private ConverterContext CreateConverterContext(Project project, Config config) { ConverterConfig converterConfig = new ConverterConfig { OmittedQualifiedNames = config.OmittedQualifiedNames, NamespaceMappings = new Dictionary <string, string>() }; foreach (string item in config.NamespaceMappings) { string[] ms = item.Split(':'); converterConfig.NamespaceMappings[ms[0]] = ms[1]; } if (config.Samples.Count > 0) { //always convert samples foreach (var sample in config.Samples) { Document doc = project.GetDocumentByType(sample); if (doc != null) { project.AddIncludeDocument(doc); } } List <string> avaiableTypes = project.GetReferences(config.Samples.ToArray()); List <string> allTypes = project.TypeNames; converterConfig.ExcludeTypes = allTypes.FindAll(t => !avaiableTypes.Contains(t)); } ConverterContext convertContext = new ConverterContext(project, converterConfig); ConverterContext.Current = convertContext; return(convertContext); }
/// <summary> /// Command execute handler. /// </summary> /// <returns>0 success, otherwise failure.</returns> private int OnCommandExecute() { ExecuteArgument arg = ExecuteArgument.Create(this._appCmd.Options); if (arg == null) { return(1); } if (arg.Files.Count == 0 && arg.Config.Samples.Count == 0) { this.Log("No files to convert."); return(0); } List <Document> documents = this.BuildAst(arg.AllFiles); List <Document> includedDocuments = (arg.Files == arg.AllFiles ? documents : documents.FindAll(doc => arg.Files.Contains(doc.Path))); if (this.ConfirmConvert(includedDocuments)) { Project project = new Project(arg.BasePath, documents, includedDocuments); ConverterContext context = this.CreateConverterContext(project, arg.Config); this.ClearOutput(arg); this.Convert(context, arg); } return(0); }
public override void ConvertToData(ConverterContext converterContext, ref EntityComponentReference <TSource> componentReference, TSource component) { ContentReference <EntityData> entityReference = null; converterContext.ConvertToData(ref entityReference, component.Entity); // Find key of this component PropertyKey <TSource> componentKey = null; if (component.Entity == null) { throw new InvalidOperationException("Entity of a referenced component can't be null"); } foreach (var entityComponent in component.Entity.Tags) { if (entityComponent.Value is EntityComponent && entityComponent.Value == component) { componentKey = (PropertyKey <TSource>)entityComponent.Key; } } if (componentKey == null) { throw new InvalidOperationException("Could not find the component in its entity"); } componentReference = new EntityComponentReference <TSource>(entityReference, componentKey); }
public ConverterResult Convert(ConverterContext context) { ConverterResult result = null; if (!supportedDestinationTypes.Contains(context.DestinationType) || typeof(IConvertible).IsAssignableFrom(context.SourceType)) { result = new ConverterResult(success: false); } else { try { result = new ConverterResult( result: ((IConvertible)context.Source).ToType(context.DestinationType, context.FormatProvider), success: true ); } catch (Exception ex) { result = new ConverterResult( exception: ex, success: false ); } } return result; }
public override void ConvertFromData(ConverterContext converterContext, DynamicSpriteFontData data, ref SpriteFont obj) { var services = converterContext.Tags.Get(ServiceRegistry.ServiceRegistryKey); var fontSystem = services.GetSafeServiceAs <GameFontSystem>().FontSystem; obj = new DynamicSpriteFont(fontSystem, data); }
/////////////////////////////////////////////////////////////////////////////////////////// /// <summary> Converts images. </summary> /// /// <exception cref="ImageFormatException"> Thrown when an Image Format error condition occurs. </exception> /// /// <param name="sourceFile"> Source file. </param> /// <param name="destinationFile"> Destination file. </param> /// <param name="Type"> The type. </param> /////////////////////////////////////////////////////////////////////////////////////////// public void Convert(String sourceFile, String destinationFile, String Type) { switch (Type.ToLower()) { case "jpg": case "jpeg": converter = new ConverterContext(new Jpeg()); break; case "gif": converter = new ConverterContext(new Gif()); break; case "png": converter = new ConverterContext(new Png()); break; default: throw new ImageFormatException(); } // Check source file for read access CheckSourceFile(sourceFile); // Check destination file for write access CheckDestinationFile(destinationFile); Image sourceImage = Image.FromFile(sourceFile); converter.ConvertImage(sourceImage, destinationFile); sourceImage.Dispose(); }
static void Initialize() { using (ConverterContext context = new ConverterContext()) { //drop create database always try { context.Database.EnsureDeleted(); } catch (Exception) { context.Database.EnsureCreated(); } #region Converters var converters = new List <Converter>() { new Converter { TypeOfConvert = "kilometer to miles", NumbertoConvert = 0, NumberConverted = 5.00, }, }; context.Converters.AddRange(converters); context.SaveChanges(); #endregion } }
public override void ConvertFromData(ConverterContext converterContext, EffectBytecode data, ref Effect obj) { var services = converterContext.Tags.Get(ServiceRegistry.ServiceRegistryKey); var graphicsDeviceService = services.GetSafeServiceAs <IGraphicsDeviceService>(); obj = new Effect(graphicsDeviceService.GraphicsDevice, data); }
public override object FromDB(ConverterContext context) { if (context.DbValue == DBNull.Value) { return(NullConfig.Instance); } var stringValue = (string)context.DbValue; if (string.IsNullOrWhiteSpace(stringValue)) { return(NullConfig.Instance); } var ordinal = context.DataRecord.GetOrdinal("ConfigContract"); var contract = context.DataRecord.GetString(ordinal); var impType = typeof(IProviderConfig).Assembly.FindTypeByName(contract); if (impType == null) { throw new ConfigContractNotFoundException(contract); } return(Json.Deserialize(stringValue, impType)); }
public override void ConvertFromData(ConverterContext converterContext, IndexBufferBindingData data, ref IndexBufferBinding source) { Buffer buffer = null; converterContext.ConvertFromData(data.Buffer, ref buffer); source = new IndexBufferBinding(buffer, data.Is32Bit, data.Count, data.Offset); }
public override void ConvertFromData(ConverterContext converterContext, EntityComponentReference <TSource> componentReference, ref TSource component) { // Load entity var entity = converterContext.ConvertFromData <Entity>(componentReference.Entity); // Get its component component = entity.Get(componentReference.Component); }
public override void ConstructFromData(ConverterContext converterContext, EntityData entityData, ref Entity entity) { entity = new Entity(entityData.Name); foreach (var component in entityData.Components) { entity.Tags.SetObject(component.Key, converterContext.ConvertFromData <EntityComponent>(component.Value, ConvertFromDataFlags.Construct)); } }
public async ValueTask <ConversionResult> ConvertAsync(ConverterContext context) { await Task.Delay(1); // simulate an async operation. var customer = new Customer(context.Source.ToString(), context.Source + "-converted customer"); return(ConversionResult.Success(value: customer)); }
public object FromDB(ConverterContext context) { if (context.DbValue is string version) { return(Version.Parse(version)); } return(null); }
public override void ConvertFromData(ConverterContext converterContext, EntityData entityData, ref Entity entity) { foreach (var component in entityData.Components) { var entityComponent = (EntityComponent)entity.Tags.Get(component.Key); converterContext.ConvertFromData(component.Value, ref entityComponent, ConvertFromDataFlags.Convert); entity.Tags.SetObject(component.Key, entityComponent); } }
public void should_throw_for_non_boolean_equivalent_number_value_when_getting_from_db() { var context = new ConverterContext { DbValue = (long)2 }; Assert.Throws <ConversionException>(() => Subject.FromDB(context)); }
public void should_return_time_span_zero_for_db_null_value_when_getting_from_db() { var context = new ConverterContext { DbValue = DBNull.Value }; Subject.FromDB(context).Should().Be(TimeSpan.Zero); }
public object FromDB(ConverterContext context) { if (context.DbValue == DBNull.Value) { return(TimeSpan.Zero); } return(TimeSpan.Parse(context.DbValue.ToString())); }
public void should_return_bool_when_getting_int_from_db(int input, bool expected) { var context = new ConverterContext { DbValue = (long)input }; Subject.FromDB(context).Should().Be(expected); }
public object FromDB(ConverterContext context) { if (context.DbValue != null && context.DbValue != DBNull.Value) { return(Enum.ToObject(context.ColumnMap.FieldType, (long)context.DbValue)); } return(null); }
public void should_return_db_null_for_db_null_value_when_getting_from_db() { var context = new ConverterContext { DbValue = DBNull.Value }; Subject.FromDB(context).Should().Be(DBNull.Value); }
public static void SaveIndicesToBinaryFile(ConverterContext context, string fileName) { using (var writer = new BinaryWriter(File.Create(fileName))) { foreach (var index in context.Indices) { writer.Write(index); } } }
public void NullStringToNullableGuid() { var converter = new TypeConverterConverter(); var context = new ConverterContext(typeof(string), typeof(Guid?), null, CultureInfo.CurrentCulture); var result = converter.Convert(context); Assert.IsNotNull(result); Assert.IsTrue(result.Success); }
static ConverterContext GetConverterContext() { var c = s_converter_context; if (c == null) { c = s_converter_context = new ConverterContext(); } return(c); }
public object FromDB(ConverterContext context) { if (context.DbValue == DBNull.Value) { return(DBNull.Value); } var value = (string)context.DbValue; return(new OsPath(value)); }
public object FromDB(ConverterContext context) { if (context.DbValue == DBNull.Value) { return(Quality.Unknown); } var val = Convert.ToInt32(context.DbValue); return((Quality)val); }
public void should_return_time_span_when_getting_time_span_from_db() { var dateTime = DateTime.Now.ToUniversalTime(); var context = new ConverterContext { DbValue = dateTime }; Subject.FromDB(context).Should().Be(dateTime); }
public void should_return_int_when_getting_string_from_db() { var i = 5; var context = new ConverterContext { DbValue = i.ToString() }; Subject.FromDB(context).Should().Be(i); }
public void should_return_double_when_getting_string_from_db() { var expected = 10.5D; var context = new ConverterContext { DbValue = $"{expected}" }; Subject.FromDB(context).Should().Be(expected); }
public void StringToGuid() { var converter = new TypeConverterConverter(); Guid e = Guid.NewGuid(); string s = e.ToString(); var context = new ConverterContext(typeof(string), typeof(Guid), s, CultureInfo.CurrentCulture); var result = converter.Convert(context); Assert.IsNotNull(result); Assert.IsNotNull(result.Result); Assert.IsInstanceOfType(result.Result, typeof(Guid)); Assert.AreEqual(e, result.Result); Assert.IsFalse(ReferenceEquals(e, result.Result)); }
public ConverterResult Convert(ConverterContext context) { ConverterResult result = null; var converter = GetConverter(context.DestinationType); try { result = new ConverterResult( result: converter.ConvertFrom(context.Source), success: true); } catch (Exception ex) { result = new ConverterResult( exception: ex, success: false); } return result; }