コード例 #1
0
        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));
        }
コード例 #2
0
        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);
        }
コード例 #3
0
        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);
        }
コード例 #4
0
        /// <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);
        }
コード例 #5
0
        /// <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);
        }
コード例 #6
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);
        }
コード例 #7
0
        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;
        }
コード例 #8
0
        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);
        }
コード例 #9
0
ファイル: ImageTools.cs プロジェクト: arruor/coverity-sample
        ///////////////////////////////////////////////////////////////////////////////////////////
        /// <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();
        }
コード例 #10
0
        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
            }
        }
コード例 #11
0
        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);
        }
コード例 #12
0
        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));
        }
コード例 #13
0
        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);
        }
コード例 #14
0
        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);
        }
コード例 #15
0
ファイル: EntityData.cs プロジェクト: yongweisun/paradox
 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));
            }
コード例 #17
0
        public object FromDB(ConverterContext context)
        {
            if (context.DbValue is string version)
            {
                return(Version.Parse(version));
            }

            return(null);
        }
コード例 #18
0
ファイル: EntityData.cs プロジェクト: yongweisun/paradox
 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);
     }
 }
コード例 #19
0
        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));
        }
コード例 #20
0
        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);
        }
コード例 #21
0
        public object FromDB(ConverterContext context)
        {
            if (context.DbValue == DBNull.Value)
            {
                return(TimeSpan.Zero);
            }

            return(TimeSpan.Parse(context.DbValue.ToString()));
        }
コード例 #22
0
        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);
        }
コード例 #23
0
ファイル: EnumIntConverter.cs プロジェクト: novarr/Comarr
        public object FromDB(ConverterContext context)
        {
            if (context.DbValue != null && context.DbValue != DBNull.Value)
            {
                return(Enum.ToObject(context.ColumnMap.FieldType, (long)context.DbValue));
            }

            return(null);
        }
コード例 #24
0
        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);
        }
コード例 #25
0
 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);
         }
     }
 }
コード例 #26
0
        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);
        }
コード例 #27
0
        static ConverterContext GetConverterContext()
        {
            var c = s_converter_context;

            if (c == null)
            {
                c = s_converter_context = new ConverterContext();
            }
            return(c);
        }
コード例 #28
0
        public object FromDB(ConverterContext context)
        {
            if (context.DbValue == DBNull.Value)
            {
                return(DBNull.Value);
            }

            var value = (string)context.DbValue;

            return(new OsPath(value));
        }
コード例 #29
0
        public object FromDB(ConverterContext context)
        {
            if (context.DbValue == DBNull.Value)
            {
                return(Quality.Unknown);
            }

            var val = Convert.ToInt32(context.DbValue);

            return((Quality)val);
        }
コード例 #30
0
        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);
        }
コード例 #31
0
        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);
        }
コード例 #32
0
        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);
        }
コード例 #33
0
        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));
        }
コード例 #34
0
        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;
        }