コード例 #1
0
        /// <summary>
        /// Creates a new instance of LightningEnvironment.
        /// </summary>
        /// <param name="directory">Directory for storing database files.</param>
        /// <param name="openFlags">Database open options.</param>
        /// <param name="accessMode">Unix file access privelegies (optional). Only makes sense on unix operationg systems.</param>
        public LightningEnvironment(string directory, EnvironmentOpenFlags openFlags = EnvironmentOpenFlags.None, UnixAccessMode accessMode = UnixAccessMode.Default)
        {
            if (String.IsNullOrWhiteSpace(directory))
                throw new ArgumentException("Invalid directory name");

            IntPtr handle = default(IntPtr);
            NativeMethods.Execute(lib => lib.mdb_env_create(out handle));

            _shouldDispose = true;
            
            _handle = handle;
            _accessMode = accessMode;

            this.Directory = directory;
            _openFlags = openFlags;

            if (LightningConfig.Environment.DefaultMapSize != LightningConfig.Environment.LibDefaultMapSize)
                this.MapSize = LightningConfig.Environment.DefaultMapSize;
            else
                _mapSize = LightningConfig.Environment.LibDefaultMapSize;

            if (LightningConfig.Environment.DefaultMaxDatabases != LightningConfig.Environment.LibDefaultMaxDatabases)
                this.MaxDatabases = LightningConfig.Environment.DefaultMaxDatabases;
            else
                _maxDbs = LightningConfig.Environment.LibDefaultMaxDatabases;

            _openedDatabases = new ConcurrentDictionary<string, LightningDatabase>();
            _databasesForReuse = new HashSet<uint>();

            ConverterStore = new ConverterStore();
            var defaultConverters = new DefaultConverters();
            defaultConverters.RegisterDefault(this);
        }
コード例 #2
0
        public LightningEnvironment(string directory, EnvironmentOpenFlags openFlags)
        {
            if (String.IsNullOrWhiteSpace(directory))
                throw new ArgumentException("Invalid directory name");

            IntPtr handle = default(IntPtr);
            Native.Execute(() => Native.mdb_env_create(out handle));

            _shouldDispose = true;
            
            _handle = handle;

            this.Directory = directory;
            _openFlags = openFlags;

            _mapSize = DefaultMapSize;
            _maxDbs = DefaultMaxDatabases;

            _openedDatabases = new ConcurrentDictionary<string, LightningDatabase>();
            _databasesForReuse = new HashSet<uint>();

            ConverterStore = new ConverterStore();
            var defaultConverters = new DefaultConverters();
            defaultConverters.RegisterDefault(this);
        }
コード例 #3
0
        public object Deserialize(XElement root, Deserializer deserializer)
        {
            object crObject = deserializer.GetCRObject(root);

            if (crObject != null)
            {
                return(crObject);
            }

            Body    body    = (Body)deserializer.DeserializeObject(root.Element("Body"));
            Shape   shape   = (Shape)deserializer.DeserializeObject(root.Element("Shape"));
            Fixture fixture = new Fixture(body, shape);

            deserializer.DeserializeMetadata(root, fixture);
            deserializer.AddToCRList(root, fixture);

            fixture.CollisionCategories = (Category)DefaultConverters.StringToInt(root.Attribute("CategoryBits").Value);
            fixture.CollidesWith        = (Category)DefaultConverters.StringToInt(root.Attribute("MaskBits").Value);
            fixture.CollisionGroup      = (short)DefaultConverters.StringToShort(root.Attribute("GroupIndex").Value);
            fixture.Friction            = (float)DefaultConverters.StringToFloat(root.Attribute("Friction").Value);
            fixture.IsSensor            = (bool)DefaultConverters.StringToBool(root.Attribute("IsSensor").Value);
            fixture.Restitution         = (float)DefaultConverters.StringToFloat(root.Attribute("Restitution").Value);

            return(fixture);
        }
コード例 #4
0
ファイル: TypeDescriptor.cs プロジェクト: ununian/WPFLight
        public static TypeConverter GetConverter(Type type)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            var attributes = type.GetCustomAttributes(
                typeof(TypeConverterAttribute), true);

            if (attributes.Length > 0)
            {
                return(( TypeConverter )Activator.CreateInstance(
                           Type.GetType(
                               ((TypeConverterAttribute)attributes[0]).ConverterTypeName, true)
                           ));
            }

            if (DefaultConverters.ContainsKey(type))
            {
                return(( TypeConverter )
                       Activator.CreateInstance(DefaultConverters[type]));
            }
            return(null);
        }
コード例 #5
0
 public void GetPolicies(JsonSerializerOptions options)
 {
     if (ClassType == ClassType.Enumerable)
     {
         EnumerableConverter = DefaultConverters.GetEnumerableConverter(Type, propertyInfo: null, Type, options);
     }
 }
コード例 #6
0
        public LightningEnvironment(string directory, EnvironmentOpenFlags openFlags, UnixAccessMode accessMode = UnixAccessMode.Default)
        {
            if (String.IsNullOrWhiteSpace(directory))
                throw new ArgumentException("Invalid directory name");

            IntPtr handle = default(IntPtr);
            Native.Execute(lib => lib.mdb_env_create(out handle));

            _shouldDispose = true;
            
            _handle = handle;
            _accessMode = accessMode;

            this.Directory = directory;
            _openFlags = openFlags;

            _mapSize = DefaultMapSize;
            _maxDbs = DefaultMaxDatabases;

            _openedDatabases = new ConcurrentDictionary<string, LightningDatabase>();
            _databasesForReuse = new HashSet<uint>();

            ConverterStore = new ConverterStore();
            var defaultConverters = new DefaultConverters();
            defaultConverters.RegisterDefault(this);
        }
コード例 #7
0
            public ValueBinder <TParams, TField> Compile(bool withDefaults)
            {
                IEnumerable <Converter <TField> > converters;

                if (withDefaults)
                {
                    Converter <TField>[] defaultConverters = DefaultConverters.To <TField>();
                    if (Converters.Count > 0)
                    {
                        Converters.AddRange(defaultConverters);
                        converters = Converters;
                    }
                    else
                    {
                        converters = defaultConverters;
                    }
                }
                else
                {
                    converters = Converters;
                }
                return(new ValueBinder <TParams, TField>(
                           Member?.Name,
                           CompileGetter(Member),
                           converters));
            }
コード例 #8
0
 /// <summary>
 /// Initializes a new instance of the <see cref="XmlSerializerSettings"/> class.
 /// </summary>
 /// <remarks>
 /// The following table shows the initial property values for an instance of <see cref="DefaultXmlConverter"/>.
 /// <list type="table">
 ///     <listheader>
 ///         <term>Property</term>
 ///         <description>Initial Value</description>
 ///     </listheader>
 ///     <item>
 ///         <term><see cref="Reader"/></term>
 ///         <description><see cref="XmlReaderUtility.CreateSettings"/></description>
 ///     </item>
 ///     <item>
 ///         <term><see cref="Writer"/></term>
 ///         <description><see cref="XmlWriterUtility.CreateSettings"/></description>
 ///     </item>
 ///     <item>
 ///         <term><see cref="Converters"/></term>
 ///         <description><see cref="List{XmlConverter}"/></description>
 ///     </item>
 ///     <item>
 ///         <term><see cref="RootName"/></term>
 ///         <description><c>null</c></description>
 ///     </item>
 /// </list>
 /// </remarks>
 public XmlSerializerSettings()
 {
     Writer     = XmlWriterUtility.CreateSettings();
     Reader     = XmlReaderUtility.CreateSettings();
     Converters = new List <XmlConverter>();
     DefaultConverters?.Invoke(Converters);
 }
コード例 #9
0
ファイル: JsonClassInfo.cs プロジェクト: zenntenn/corefx
        internal static ClassType GetClassType(Type type)
        {
            Debug.Assert(type != null);

            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable <>))
            {
                type = Nullable.GetUnderlyingType(type);
            }

            if (DefaultConverters.IsValueConvertable(type))
            {
                return(ClassType.Value);
            }

            if (typeof(IDictionary).IsAssignableFrom(type) ||
                (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(IDictionary <,>) ||
                                        type.GetGenericTypeDefinition() == typeof(IReadOnlyDictionary <,>))))
            {
                return(ClassType.Dictionary);
            }

            if (typeof(IEnumerable).IsAssignableFrom(type))
            {
                return(ClassType.Enumerable);
            }

            if (type == typeof(object))
            {
                return(ClassType.Unknown);
            }

            return(ClassType.Object);
        }
コード例 #10
0
        public XElement Serialize(string name, object rootObject, Serializer serializer)
        {
            XElement root = new XElement(name);

            //Обрабатываем кольцевые ссылки
            if (serializer.CheckCircularReferences(root, rootObject))
            {
                return(root);
            }

            //Сериализуем метаданные
            Serializer.SerializeMetadata(root, rootObject);
            //Сериализуем имя типа
            Serializer.SerializeTypeName(root, typeof(Fixture));

            Fixture fixture = (Fixture)rootObject;

            root.Add(serializer.SerializeObject("Shape", fixture.Shape));
            root.Add(
                new XAttribute("CategoryBits", DefaultConverters.IntToString((int)fixture.CollisionCategories)),
                new XAttribute("MaskBits", DefaultConverters.IntToString((int)fixture.CollidesWith)),
                new XAttribute("GroupIndex", DefaultConverters.ShortToString(fixture.CollisionGroup)),
                new XAttribute("Friction", DefaultConverters.FloatToString(fixture.Friction)),
                new XAttribute("IsSensor", DefaultConverters.BoolToString(fixture.IsSensor)),
                new XAttribute("Restitution", DefaultConverters.FloatToString(fixture.Restitution)),
                serializer.SerializeObject("Body", fixture.Body));
            return(root);
        }
コード例 #11
0
        protected JsonValueConverter <TValue> GetPropertyValueConverter(JsonSerializerOptions options)
        {
            JsonValueConverterAttribute attr = DefaultConverters.GetPropertyValueConverter(ParentClassType, PropertyInfo, PropertyType, options);

            if (attr != null)
            {
                return(attr.GetConverter <TValue>());
            }

            return(null);
        }
コード例 #12
0
        /// <summary>
        /// <see cref="CsvConverter"/>を返します。<see cref="CsvConverter"/>が存在しない場合は例外をスローします。
        /// </summary>
        /// <param name="property"><see cref="PropertyInfo"/>。</param>
        /// <returns><see cref="CsvConverter"/>。</returns>
        private CsvConverter GetConverter(PropertyInfo property)
        {
            if (this.converter != null)
            {
                return(this.converter);
            }

            var converter = DefaultConverters.GetOrNull(property.PropertyType);

            if (converter != null)
            {
                return(converter);
            }

            throw new InvalidOperationException("I couldn't find a converter for the property type.");
        }
コード例 #13
0
ファイル: CsvParserBuilder.cs プロジェクト: yamahix/NCsv
        /// <summary>
        /// <see cref="CsvConverter"/>を返します。<see cref="CsvConverter"/>が存在しない場合は例外をスローします。
        /// </summary>
        /// <param name="property"><see cref="PropertyInfo"/>。</param>
        /// <returns><see cref="CsvConverter"/>。</returns>
        private static CsvConverter GetConverter(PropertyInfo property)
        {
            var a = property.GetCustomAttribute <CsvConverterAttribute>();

            if (a != null)
            {
                return(a.CreateConverter());
            }

            var converter = DefaultConverters.GetOrNull(property.PropertyType);

            if (converter != null)
            {
                return(converter);
            }

            throw new InvalidOperationException("I couldn't find a converter for the property type.");
        }
コード例 #14
0
        public static ClassType GetClassType(Type type)
        {
            Debug.Assert(type != null);

            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable <>))
            {
                type = Nullable.GetUnderlyingType(type);
            }

            if (DefaultConverters.IsValueConvertable(type))
            {
                return(ClassType.Value);
            }

            if (DefaultImmutableDictionaryConverter.IsImmutableDictionary(type) ||
                IsDeserializedByConstructingWithIDictionary(type))
            {
                return(ClassType.IDictionaryConstructible);
            }

            if (typeof(IDictionary).IsAssignableFrom(type) ||
                (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(IDictionary <,>) ||
                                        type.GetGenericTypeDefinition() == typeof(IReadOnlyDictionary <,>))))
            {
                return(ClassType.Dictionary);
            }

            if (IsKeyValuePair(type))
            {
                return(ClassType.KeyValuePair);
            }

            if (typeof(IEnumerable).IsAssignableFrom(type))
            {
                return(ClassType.Enumerable);
            }

            if (type == typeof(object))
            {
                return(ClassType.Unknown);
            }

            return(ClassType.Object);
        }
コード例 #15
0
        public XElement Serialize(string name, object rootObject, Serializer serializer)
        {
            XElement root = new XElement(name);

            //Обрабатываем кольцевые ссылки
            if (serializer.CheckCircularReferences(root, rootObject))
            {
                return(root);
            }

            //Сериализуем метаданные
            Serializer.SerializeMetadata(root, rootObject);
            //Сериализуем имя типа
            Serializer.SerializeTypeName(root, typeof(Body));

            Body body = (Body)rootObject;

            root.Add(
                new XAttribute("BodyType", DefaultConverters.IntToString((int)body.BodyType)),
                new XAttribute("Active", DefaultConverters.BoolToString(body.Enabled)),
                new XAttribute("AllowSleep", DefaultConverters.BoolToString(body.SleepingAllowed)),
                new XAttribute("Angle", DefaultConverters.FloatToString(body.Rotation)),
                new XAttribute("AngularDamping", DefaultConverters.FloatToString(body.AngularDamping)),
                new XAttribute("AngularVelocity", DefaultConverters.FloatToString(body.AngularVelocity)),
                new XAttribute("Awake", DefaultConverters.BoolToString(body.Awake)),
                new XAttribute("Bullet", DefaultConverters.BoolToString(body.IsBullet)),
                new XAttribute("FixedRotation", DefaultConverters.BoolToString(body.FixedRotation)),
                new XAttribute("LinearDamping", DefaultConverters.FloatToString(body.LinearDamping)),
                new XAttribute("LinearVelocity", DefaultConverters.Vector2ToString(body.LinearVelocity)),
                new XAttribute("Position", DefaultConverters.Vector2ToString(body.Position)),
                serializer.SerializeObject("World", SerializerHelpers.GetFieldValue(body, "World")));

            XElement fixtures = new XElement("Fixtures");

            for (int i = 0; i < body.FixtureList.Count; i++)
            {
                fixtures.Add(serializer.SerializeObject("Fixture", body.FixtureList[i]));
            }

            root.Add(fixtures);
            return(root);
        }
コード例 #16
0
        public XElement Serialize(string name, object rootObject, Serializer serializer)
        {
            XElement root = new XElement(name);

            //Обрабатываем кольцевые ссылки
            if (serializer.CheckCircularReferences(root, rootObject))
            {
                return(root);
            }

            //Сериализуем метаданные
            Serializer.SerializeMetadata(root, rootObject);
            //Сериализуем имя типа
            Serializer.SerializeTypeName(root, typeof(World));

            //Сериализуем гравитацию
            World world = (World)rootObject;

            root.Add(
                new XAttribute("Gravity", DefaultConverters.Vector2ToString(world.Gravity)));

            //Сериализуем bodies
            XElement bodies = new XElement("Bodies");

            for (int i = 0; i < world.BodyList.Count; i++)
            {
                bodies.Add(serializer.SerializeObject("Body", world.BodyList[i]));
            }

            //Сериализуем joint'ы
            XElement joints = new XElement("Joints");

            foreach (Joint joint in world.JointList)
            {
                joints.Add(serializer.SerializeObject("Joint", joint));
            }

            root.Add(bodies);
            root.Add(joints);

            return(root);
        }
コード例 #17
0
        public virtual void GetPolicies(JsonSerializerOptions options)
        {
            {
                PropertyNamePolicyAttribute attr = DefaultConverters.GetPolicy <PropertyNamePolicyAttribute>(ParentClassType, PropertyInfo, options);
                if (attr != null)
                {
                    NameConverter = attr;
                }
            }

            {
                _skipNullValuesOnRead  = DefaultConverters.GetPropertyClassAssemblyPolicy(ParentClassType, PropertyInfo, options, attr => attr.SkipNullValuesOnRead);
                _skipNullValuesOnWrite = DefaultConverters.GetPropertyClassAssemblyPolicy(ParentClassType, PropertyInfo, options, attr => attr.SkipNullValuesOnWrite);
            }

            if (ElementClassInfo != null)
            {
                EnumerableConverter = DefaultConverters.GetEnumerableConverter(ParentClassType, PropertyInfo, PropertyType, options);
            }
        }
コード例 #18
0
        public object Deserialize(XElement root, Deserializer deserializer)
        {
            //Проверяем, был ли уже сериализован данный объект
            object crObject = deserializer.GetCRObject(root);

            if (crObject != null)
            {
                return(crObject);
            }

            //Десериализуем гравитацию и создаём новый world
            Vector2 gravity = (Vector2)DefaultConverters.StringToVector2(root.Attribute("Gravity").Value);
            World   world   = new World(gravity);

            deserializer.DeserializeMetadata(root, world);
            //Добавляем world в список уже десериализованных объектов
            deserializer.AddToCRList(root, world);

            //Десериализуем bodies
            var bodiesElement = root.Element("Bodies");
            var bodyElements  = bodiesElement.Elements("Body");

            foreach (XElement bodyElement in bodyElements)
            {
                Body body = (Body)deserializer.DeserializeObject(bodyElement);
                world.BodyList.Add(body);
            }

            //Десериализуем joint'ы
            var jointsElement = root.Element("Joints");
            var jointElements = jointsElement.Elements("Joint");

            foreach (XElement jointElement in jointElements)
            {
                Joint joint = (Joint)deserializer.DeserializeObject(jointElement);
                world.AddJoint(joint);
            }

            return(world);
        }
コード例 #19
0
        public object Deserialize(XElement root, Deserializer deserializer)
        {
            object crObject = deserializer.GetCRObject(root);

            if (crObject != null)
            {
                return(crObject);
            }

            World world = (World)deserializer.DeserializeObject(root.Element("World"));
            Body  body  = new Body(world);

            deserializer.DeserializeMetadata(root, body);
            deserializer.AddToCRList(root, body);

            body.BodyType        = (BodyType)DefaultConverters.StringToInt(root.Attribute("BodyType").Value);
            body.Enabled         = (bool)DefaultConverters.StringToBool(root.Attribute("Active").Value);
            body.SleepingAllowed = (bool)DefaultConverters.StringToBool(root.Attribute("AllowSleep").Value);
            body.Rotation        = (float)DefaultConverters.StringToFloat(root.Attribute("Angle").Value);
            body.AngularDamping  = (float)DefaultConverters.StringToFloat(root.Attribute("AngularDamping").Value);
            body.AngularVelocity = (float)DefaultConverters.StringToFloat(root.Attribute("AngularVelocity").Value);
            body.Awake           = (bool)DefaultConverters.StringToBool(root.Attribute("Awake").Value);
            body.IsBullet        = (bool)DefaultConverters.StringToBool(root.Attribute("Bullet").Value);
            body.FixedRotation   = (bool)DefaultConverters.StringToBool(root.Attribute("FixedRotation").Value);
            body.LinearDamping   = (float)DefaultConverters.StringToFloat(root.Attribute("LinearDamping").Value);
            body.LinearVelocity  = (Vector2)DefaultConverters.StringToVector2(root.Attribute("LinearVelocity").Value);
            body.Position        = (Vector2)DefaultConverters.StringToVector2(root.Attribute("Position").Value);

            var fixturesElement = root.Element("Fixtures");
            var fixtureElements = fixturesElement.Elements("Fixture");

            foreach (XElement fixtureElement in fixtureElements)
            {
                Fixture fixture = (Fixture)deserializer.DeserializeObject(fixtureElement);
                body.FixtureList.Add(fixture);
            }

            return(body);
        }
コード例 #20
0
        internal override void GetPolicies(JsonSerializerOptions options)
        {
            Type propertyType = PropertyType;
            bool isNullable   = propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable <>);

            if (isNullable)
            {
                propertyType = Nullable.GetUnderlyingType(propertyType);
            }

            // For Enums, support both the type Enum plus strongly-typed Enums.
            if (propertyType.IsEnum || propertyType == typeof(Enum))
            {
                ValueConverter = s_enumConverter;
            }
            else
            {
                ValueConverter = (JsonValueConverter <TProperty>)DefaultConverters.GetDefaultPropertyValueConverter(propertyType, isNullable);
            }

            base.GetPolicies(options);
        }
コード例 #21
0
 private static void RegisterDefaultConverter <T>(Func <string, T> converter)
 {
     DefaultConverters.Add(typeof(T), converter);
 }
コード例 #22
0
        protected PropertyValueConverterAttribute GetPropertyValueConverter(JsonSerializerOptions options)
        {
            PropertyValueConverterAttribute attr = DefaultConverters.GetPropertyValueConverter(ParentClassType, PropertyInfo, PropertyType, options);

            return(attr);
        }
コード例 #23
0
        public static Func <string, T> GetDefaultConverter <T>() //TODO: nasty. Way that doesn't compromise compile-time type safety?
        {
            object converter;

            return(DefaultConverters.TryGetValue(typeof(T), out converter) ? (Func <string, T>)converter : DefaultDotNet <T>());
        }