Example #1
0
        private TList CopyInternal <TList>(ISerializationManager serializationManager, IEnumerable <T> source, TList target, ISerializationContext?context = null) where TList : IList <T>
        {
            target.Clear();

            foreach (var element in source)
            {
                var elementCopy = serializationManager.CreateCopy(element, context) !;
                target.Add(elementCopy);
            }

            return(target);
        }
Example #2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="XmlSerializer" /> class.
        /// </summary>
        /// <param name="serializationManager">The serialization manager.</param>
        /// <param name="dataContractSerializerFactory">The data contract serializer factory.</param>
        /// <param name="xmlNamespaceManager">The XML namespace manager.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="serializationManager" /> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="dataContractSerializerFactory" /> is <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="xmlNamespaceManager" /> is <c>null</c>.</exception>
        public XmlSerializer(ISerializationManager serializationManager, IDataContractSerializerFactory dataContractSerializerFactory,
                             IXmlNamespaceManager xmlNamespaceManager)
            : base(serializationManager)
        {
            Argument.IsNotNull("dataContractSerializerFactory", dataContractSerializerFactory);
            Argument.IsNotNull("xmlNamespaceManager", xmlNamespaceManager);

            _dataContractSerializerFactory = dataContractSerializerFactory;
            _xmlNamespaceManager           = xmlNamespaceManager;

            OptimalizationMode = XmlSerializerOptimalizationMode.Performance;
        }
Example #3
0
 public RabbitMqPublisher(ILoggerFactory loggerFactory,
                          IBusModule busModule,
                          IPublisherModule publisherModule,
                          ISerializationManager serializationManager,
                          IEntityScriptingService scripting)
 {
     Logger          = loggerFactory.CreateLogger <RabbitMqPublisher>();
     BusModule       = busModule ?? throw new ArgumentNullException(nameof(busModule));
     PublisherModule = publisherModule ?? throw new ArgumentNullException(nameof(publisherModule));
     Serialization   = serializationManager ?? throw new ArgumentNullException(nameof(serializationManager));
     Scripting       = scripting ?? throw new ArgumentNullException(nameof(scripting));
 }
Example #4
0
        private DataNode WriteInternal(ISerializationManager serializationManager, IEnumerable <T> value, bool alwaysWrite = false,
                                       ISerializationContext?context = null)
        {
            var sequence = new SequenceDataNode();

            foreach (var elem in value)
            {
                sequence.Add(serializationManager.WriteValue(typeof(T), elem, alwaysWrite, context));
            }

            return(sequence);
        }
Example #5
0
        DeserializationResult ITypeReader <EntityPrototype, ValueDataNode> .Read(
            ISerializationManager serializationManager, ValueDataNode node,
            IDependencyCollection dependencies,
            bool skipHook, ISerializationContext?context)
        {
            if (!IoCManager.Resolve <Prototypes.IPrototypeManager>().HasIndex <Prototypes.EntityPrototype>(node.Value))
            {
                throw new InvalidMappingException("Invalid Entity Prototype");
            }

            return(new DeserializedValue <EntityPrototype>(new EntityPrototype(node.Value)));
        }
Example #6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SerializerBase{TSerializationContext}" /> class.
        /// </summary>
        /// <param name="serializationManager">The serialization manager.</param>
        /// <param name="typeFactory">The type factory.</param>
        /// <param name="objectAdapter">The object adapter.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="serializationManager" /> is <c>null</c>.</exception>
        protected SerializerBase(ISerializationManager serializationManager, ITypeFactory typeFactory, IObjectAdapter objectAdapter)
        {
            Argument.IsNotNull("serializationManager", serializationManager);
            Argument.IsNotNull("typeFactory", typeFactory);
            Argument.IsNotNull("objectAdapter", objectAdapter);

            SerializationManager = serializationManager;
            TypeFactory          = typeFactory;
            ObjectAdapter        = objectAdapter;

            SerializationManager.CacheInvalidated += OnSerializationManagerCacheInvalidated;
        }
Example #7
0
 /// <summary>
 /// ctor for tests
 /// </summary>
 /// <param name="transportManager"></param>
 internal MessagingEngine(TransportManager transportManager)
 {
     if (transportManager == null)
     {
         throw new ArgumentNullException("transportManager");
     }
     m_TransportManager      = transportManager;
     m_SubscriptionManager   = new SubscriptionManager(m_TransportManager);
     m_SerializationManager  = new SerializationManager();
     m_RequestTimeoutManager = new SchedulingBackgroundWorker("RequestTimeoutManager", () => stopTimeoutedRequests());
     createMessagingHandle(() => stopTimeoutedRequests(true));
 }
 public MessageConsumer(
     IOptions <ConfigRabbitMQ> config,
     IConnectionHelper connectionFactory,
     ISerializationManager serialization,
     ILogger <MessageConsumer> logger
     )
 {
     _config        = config.Value;
     _connection    = connectionFactory.CreateConnection(_config);
     _serialization = serialization;
     _logger        = logger;
 }
        public DeserializationResult Read(ISerializationManager serializationManager,
                                          MappingDataNode node,
                                          IDependencyCollection dependencies,
                                          bool skipHook,
                                          ISerializationContext?context = null)
        {
            var type = GetType(node) ??
                       throw new ArgumentException(
                                 "Tried to convert invalid YAML node mapping to ConstructionGraphStep!");

            return(serializationManager.Read(type, node, context, skipHook));
        }
Example #10
0
        private static void TestSerializationOnSerializers(List <ISerializer> serializers, Action <ISerializer, ISerializationConfiguration, string> action,
                                                           ISerializationManager serializationManager = null)
        {
            var serializerConfigurations = new Dictionary <Type, List <ISerializationConfiguration> >();

            serializerConfigurations[typeof(XmlSerializer)] = new List <ISerializationConfiguration>(new[]
            {
                new XmlSerializationConfiguration
                {
                    // Default config
                },
            });

#pragma warning disable CS0618
            serializerConfigurations[typeof(BinarySerializer)] = new List <ISerializationConfiguration>(new[]
            {
                new SerializationConfiguration()
            });
#pragma warning restore CS0618

            serializerConfigurations[typeof(JsonSerializer)] = new List <ISerializationConfiguration>(new[]
            {
                new JsonSerializationConfiguration
                {
                    UseBson = false
                },
                new JsonSerializationConfiguration
                {
                    UseBson = true
                },
            });

            foreach (var serializer in serializers)
            {
                var type     = serializer.GetType();
                var typeName = type.GetSafeFullName(false);

                var configurations = serializerConfigurations[type];
                foreach (var configuration in configurations)
                {
                    Log.Info();
                    Log.Info();
                    Log.Info();
                    Log.Info("=== TESTING SERIALIZER: {0} ===", typeName);
                    Log.Info();
                    Log.Info();
                    Log.Info();

                    action(serializer, configuration, typeName);
                }
            }
        }
        public DataNode Write(ISerializationManager serializationManager, int value, bool alwaysWrite = false,
                              ISerializationContext?context = null)
        {
            var constType    = serializationManager.GetConstantTypeFromTag(typeof(TTag));
            var constantName = Enum.GetName(constType, value);

            if (constantName == null)
            {
                throw new InvalidOperationException($"No constant corresponding to value {value} in {constType}.");
            }

            return(new ValueDataNode(constantName));
        }
Example #12
0
        public ValidationNode Validate(ISerializationManager serializationManager, MappingDataNode node,
                                       IDependencyCollection dependencies,
                                       ISerializationContext?context = null)
        {
            var type = GetType(node);

            if (type == null)
            {
                return(new ErrorNode(node, "No construction graph step type found.", true));
            }

            return(serializationManager.ValidateNode(type, node, context));
        }
Example #13
0
        public ImmutableList <T> Copy(ISerializationManager serializationManager, ImmutableList <T> source,
                                      ImmutableList <T> target, bool skipHook, ISerializationContext?context = null)
        {
            var builder = ImmutableList.CreateBuilder <T>();

            foreach (var element in source)
            {
                var elementCopy = serializationManager.CreateCopy(element, context) !;
                builder.Add(elementCopy);
            }

            return(builder.ToImmutable());
        }
Example #14
0
        public ComponentRegistry Copy(ISerializationManager serializationManager, ComponentRegistry source,
                                      ComponentRegistry target, bool skipHook, ISerializationContext?context = null)
        {
            target.Clear();
            target.EnsureCapacity(source.Count);

            foreach (var(id, component) in source)
            {
                target.Add(id, serializationManager.CreateCopy(component, context) !);
            }

            return(target);
        }
Example #15
0
        public RabbitMQBroker(IOptions <MessageBrokerOptions> options)
        {
            this.syncLock             = new object();
            this.messageBrokerOptions = options.Value;
            this.serializationManager = new JsonSerializationManager();
            channels = new Dictionary <string, IModel>();

            this.connectionFactory = new ConnectionFactory();
            this.connectionFactory.AutomaticRecoveryEnabled = true;
            this.connectionFactory.UserName = this.messageBrokerOptions.MessageBrokerUsername;
            this.connectionFactory.Password = this.messageBrokerOptions.MessageBrokerPassword;
            this.connectionFactory.HostName = this.messageBrokerOptions.MessageBrokerHost;
        }
        public ImmutableHashSet <T> Copy(ISerializationManager serializationManager, ImmutableHashSet <T> source,
                                         ImmutableHashSet <T> target, bool skipHook, ISerializationContext?context = null)
        {
            var builder = ImmutableHashSet.CreateBuilder <T>();

            foreach (var element in source)
            {
                var elementCopy = serializationManager.CreateCopy(element, context) ?? throw new NullReferenceException();
                builder.Add(elementCopy);
            }

            return(builder.ToImmutable());
        }
Example #17
0
        public void PopulateElementDescriptor(MappingDataNode node, ISerializationManager serializationManager)
        {
            MappingDataNode original = (MappingDataNode)serializationManager.WriteValue(ElementDescriptor.GetType(), ElementDescriptor);

            foreach (var key in node.Keys)
            {
                original.Remove(key);
            }

            MappingDataNode newNode = original.Merge(node);

            ElementDescriptor = (ElementDescriptor)serializationManager.Read(ElementDescriptor.GetType(), newNode);
            UpdateElementDescriptor();
        }
Example #18
0
 public static IEnumerable<IValuePair> Get(Func<object> oldValue, Func<object> newValue, string propertyName, EntityState state, ISerializationManager serializer)
 {
     var pair = new ValuePair(oldValue, newValue, propertyName, state, serializer);
     if (pair.Type.IsA(typeof(System.Data.IDataRecord)))
     {
         // Is it a complex type? If so, retrieve the value pairs for each sub-property.
         return new DataRecordValuePair(pair, serializer).SubValuePairs;
     }
     else
     {
         // Otherwise just return the change
         return new List<ValuePair>() { pair };
     }
 }
Example #19
0
 public AggregateRepository(IEventStore eventStore,
                            ISnapshotManager snapshotManager,
                            ISerializationManager serializeManager,
                            IEventPublisher eventPublisher,
                            ICommitNotifier commitNotifier,
                            IIntegrityValidator integrityValidator)
 {
     _eventStore         = eventStore;
     _snapshotManager    = snapshotManager;
     _serializeManager   = serializeManager;
     _eventPublisher     = eventPublisher;
     _commitNotifier     = commitNotifier;
     _integrityValidator = integrityValidator;
 }
Example #20
0
        public ValidationNode Validate(ISerializationManager serializationManager, ValueDataNode node,
                                       IDependencyCollection dependencies,
                                       ISerializationContext?context = null)
        {
            if (!VectorSerializerUtility.TryParseArgs(node.Value, 2, out var args))
            {
                throw new InvalidMappingException($"Could not parse {nameof(Vector2)}: '{node.Value}'");
            }

            return(float.TryParse(args[0], NumberStyles.Any, CultureInfo.InvariantCulture, out _) &&
                   float.TryParse(args[1], NumberStyles.Any, CultureInfo.InvariantCulture, out _)
                ? new ValidatedValueNode(node)
                : new ErrorNode(node, "Failed parsing values for Vector2."));
        }
Example #21
0
        public static object Deserialize(this ISerializationManager manager, SerializationFormat format, byte[] message, Type type)
        {
            Func <ISerializationManager, SerializationFormat, byte[], object> deserialize;

            lock (m_Deserializers)
            {
                if (!m_Deserializers.TryGetValue(type, out deserialize))
                {
                    deserialize = CreateDeserializer(type);
                    m_Deserializers.Add(type, deserialize);
                }
            }
            return(deserialize(manager, format, message));
        }
Example #22
0
        public DeserializationResult Read(ISerializationManager serializationManager, ValueDataNode node,
                                          IDependencyCollection dependencies,
                                          bool skipHook,
                                          ISerializationContext?context = null)
        {
            var nodeContents = node.Value;

            var angle = nodeContents.EndsWith("rad")
                ? new Angle(double.Parse(nodeContents.Substring(0, nodeContents.Length - 3),
                                         CultureInfo.InvariantCulture))
                : Angle.FromDegrees(double.Parse(nodeContents, CultureInfo.InvariantCulture));

            return(new DeserializedValue <Angle>(angle));
        }
Example #23
0
        private T CopyInternal <T>(ISerializationManager serializationManager, IReadOnlyDictionary <TKey, TValue> source, T target, ISerializationContext?context) where T : IDictionary <TKey, TValue>
        {
            target.Clear();

            foreach (var(key, value) in source)
            {
                var keyCopy   = serializationManager.CreateCopy(key, context) ?? throw new NullReferenceException();
                var valueCopy = serializationManager.CreateCopy(value, context) !;

                target.Add(keyCopy, valueCopy);
            }

            return(target);
        }
        public ValidationNode Validate(ISerializationManager serializationManager, MappingDataNode node,
                                       IDependencyCollection dependencies, ISerializationContext?context = null)
        {
            if (node.Has(SoundPathSpecifier.Node) && node.Has(SoundCollectionSpecifier.Node))
            {
                return(new ErrorNode(node, "You can only specify either a sound path or a sound collection!"));
            }

            if (!node.Has(SoundPathSpecifier.Node) && !node.Has(SoundCollectionSpecifier.Node))
            {
                return(new ErrorNode(node, "You need to specify either a sound path or a sound collection!"));
            }

            return(serializationManager.ValidateNode(GetType(node), node, context));
        }
Example #25
0
        public ValidationNode Validate(ISerializationManager serializationManager, ValueDataNode node,
                                       IDependencyCollection dependencies,
                                       ISerializationContext?context = null)
        {
            try
            {
                _ = new Regex(node.Value);
            }
            catch (Exception)
            {
                return(new ErrorNode(node, "Failed compiling regex."));
            }

            return(new ValidatedValueNode(node));
        }
        public HashSet <T> Copy(ISerializationManager serializationManager, HashSet <T> source, HashSet <T> target,
                                bool skipHook,
                                ISerializationContext?context = null)
        {
            target.Clear();
            target.EnsureCapacity(source.Count);

            foreach (var element in source)
            {
                var elementCopy = serializationManager.CreateCopy(element, context) ?? throw new NullReferenceException();
                target.Add(elementCopy);
            }

            return(target);
        }
Example #27
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ConfigurationService" /> class.
        /// </summary>
        /// <param name="serializationManager">The serialization manager.</param>
        /// <param name="objectConverterService">The object converter service.</param>
        /// <param name="serializer">The serializer.</param>
        public ConfigurationService(ISerializationManager serializationManager,
                                    IObjectConverterService objectConverterService, ISerializer serializer)
        {
            Argument.IsNotNull("serializationManager", serializationManager);
            Argument.IsNotNull("objectConverterService", objectConverterService);
            Argument.IsNotNull("serializer", serializer);

            _serializationManager   = serializationManager;
            _objectConverterService = objectConverterService;
            _serializer             = serializer;

#if NET || NETSTANDARD
            SetLocalConfigFilePath(DefaultLocalConfigFilePath);
            SetRoamingConfigFilePath(DefaultRoamingConfigFilePath);
#endif
        }
Example #28
0
        public DeserializationResult Read(ISerializationManager serializationManager, MappingDataNode node,
                                          IDependencyCollection dependencies,
                                          bool skipHook,
                                          ISerializationContext?context = null)
        {
            if (node.Children.Count != 1)
            {
                throw new InvalidMappingException("Less than or more than 1 mappings provided to ValueTupleSerializer");
            }

            var entry = node.Children.First();
            var v1    = serializationManager.ReadValueOrThrow <T1>(entry.Key, context, skipHook);
            var v2    = serializationManager.ReadValueOrThrow <T2>(entry.Value, context, skipHook);

            return(new DeserializedValue <ValueTuple <T1, T2> >(new ValueTuple <T1, T2>(v1, v2)));
        }
Example #29
0
        public DataNode Write(ISerializationManager serializationManager, SpriteSpecifier value, bool alwaysWrite = false,
                              ISerializationContext?context = null)
        {
            return(value switch
            {
                Rsi rsi
                => Write(serializationManager, rsi, alwaysWrite, context),

                Texture texture
                => Write(serializationManager, texture, alwaysWrite, context),

                EntityPrototype entityPrototype
                => Write(serializationManager, entityPrototype, alwaysWrite, context),

                _ => throw new InvalidOperationException("Invalid SpriteSpecifier specified!")
            });
Example #30
0
        public DeserializationResult Read(ISerializationManager serializationManager, ValueDataNode node,
                                          IDependencyCollection dependencies,
                                          bool skipHook,
                                          ISerializationContext?context = null)
        {
            if (!VectorSerializerUtility.TryParseArgs(node.Value, 2, out var args))
            {
                throw new InvalidMappingException($"Could not parse {nameof(Vector2)}: '{node.Value}'");
            }

            var x      = float.Parse(args[0], CultureInfo.InvariantCulture);
            var y      = float.Parse(args[1], CultureInfo.InvariantCulture);
            var vector = new Vector2(x, y);

            return(new DeserializedValue <Vector2>(vector));
        }
Example #31
0
        public void Initialize(MessageBrokerState brokerState)
        {
            Check.NotNull(brokerState, nameof(brokerState));
            Check.NotNull(brokerState.ConnectionMgr, nameof(brokerState.ConnectionMgr));
            Check.NotNull(brokerState.SerializationMgr, nameof(brokerState.SerializationMgr));
            Check.NotNull(brokerState.Exchanges, nameof(brokerState.Exchanges));

            _brokerState = brokerState;

            _connMgr            = brokerState.ConnectionMgr;
            _serializationMgr   = brokerState.SerializationMgr;
            _brokerInitializers = new List <IBrokerInitializer>();

            InitializePublishers();
            InitializeConsumers();
        }
Example #32
0
 /// <summary>
 /// Returns the changes for a property as ValuePair objects.
 /// We can have more than one change for a single property if it is a complex type
 /// (A complex type is another class with its own properties that is mapped not as a 
 /// foreign key but as columns of the same table.)
 /// </summary>
 public static IEnumerable<IValuePair> Get(ObjectStateEntry entry, string propertyName, ISerializationManager serializer)
 {
     var state = entry.State;
     switch (state)
     {
         case EntityState.Added:
             return Get(() => null, () => entry.CurrentValues[propertyName], propertyName, state, serializer);
         case EntityState.Deleted:
             var knowValue = entry.OriginalValues[propertyName];
             return Get(() => knowValue, () => null, propertyName, state, serializer);
         case EntityState.Modified:
             return Get(() => entry.OriginalValues[propertyName],
                 () => entry.CurrentValues[propertyName], propertyName, state, serializer);
         default:
             throw new NotImplementedException(string.Format("Unable to deal with ObjectStateEntry in '{0}' state",
                 state));
     }
 }
Example #33
0
        private static void TestSerializationOnAllSerializers(Action<ISerializer, ISerializationConfiguration, string> action, 
            bool testWithoutGraphIdsAsWell = true, ISerializationManager serializationManager = null)
        {
            if (serializationManager == null)
            {
                serializationManager = new SerializationManager();
            }

            var serializerConfigurations = new Dictionary<Type, List<ISerializationConfiguration>>();

            serializerConfigurations[typeof(XmlSerializer)] = new List<ISerializationConfiguration>(new[]
            {
                new SerializationConfiguration()
            });

            serializerConfigurations[typeof(BinarySerializer)] = new List<ISerializationConfiguration>(new[]
            {
                new SerializationConfiguration()
            });

            serializerConfigurations[typeof(JsonSerializer)] = new List<ISerializationConfiguration>(new[]
            {
                new JsonSerializationConfiguration
                {
                    UseBson = false
                },
                new JsonSerializationConfiguration
                {
                    UseBson = true
                },
            });

            var serializers = new List<ISerializer>();

            serializers.Add(SerializationTestHelper.GetXmlSerializer(XmlSerializerOptimalizationMode.Performance, serializationManager));
            serializers.Add(SerializationTestHelper.GetXmlSerializer(XmlSerializerOptimalizationMode.PrettyXml, serializationManager));
            serializers.Add(SerializationTestHelper.GetBinarySerializer(serializationManager));
            serializers.Add(SerializationTestHelper.GetJsonSerializer(serializationManager));

            if (testWithoutGraphIdsAsWell)
            {
                var basicJsonSerializer = SerializationTestHelper.GetJsonSerializer(serializationManager);
                basicJsonSerializer.PreserveReferences = false;
                basicJsonSerializer.WriteTypeInfo = false;
                serializers.Add(basicJsonSerializer);
            }

            foreach (var serializer in serializers)
            {
                var type = serializer.GetType();
                var typeName = type.GetSafeFullName(false);

                var configurations = serializerConfigurations[type];
                foreach (var configuration in configurations)
                {
                    Log.Info();
                    Log.Info();
                    Log.Info();
                    Log.Info("=== TESTING SERIALIZER: {0} ===", typeName);
                    Log.Info();
                    Log.Info();
                    Log.Info();

                    action(serializer, configuration, typeName);
                }
            }
        }
Example #34
0
        /// <summary>
        /// Returns the sequence of properties of the specified type.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <param name="schema">The schema.</param>
        /// <param name="schemaSet">The schema set.</param>
        /// <param name="serializationManager">The serialization manager.</param>
        /// <returns>Sequence containing all properties.</returns>
        private static XmlSchemaSequence GetPropertiesSequence(Type type, XmlSchema schema, XmlSchemaSet schemaSet, ISerializationManager serializationManager)
        {
            Argument.IsNotNull("type", type);
            Argument.IsNotNull("schema", schema);
            Argument.IsNotNull("schemaSet", schemaSet);

            var propertiesSequence = new XmlSchemaSequence();

            if (typeof(ModelBase).IsAssignableFromEx(type))
            {
                var members = new List<MemberInfo>();
                members.AddRange(from field in serializationManager.GetFieldsToSerialize(type)
                                 select type.GetFieldEx(field));
                members.AddRange(from property in serializationManager.GetPropertiesToSerialize(type)
                                 select type.GetPropertyEx(property));

                foreach (var member in members)
                {
                    var propertySchemaElement = new XmlSchemaElement();
                    propertySchemaElement.Name = member.Name;

                    var memberType = typeof(object);
                    var fieldInfo = member as FieldInfo;
                    if (fieldInfo != null)
                    {
                        memberType = fieldInfo.FieldType;
                    }

                    var propertyInfo = member as PropertyInfo;
                    if (propertyInfo != null)
                    {
                        memberType = propertyInfo.PropertyType;
                    }

                    propertySchemaElement.IsNillable = memberType.IsNullableType();
                    propertySchemaElement.MinOccurs = 0;

                    var exporter = new XsdDataContractExporter(schemaSet);
                    exporter.Export(memberType);

                    propertySchemaElement.SchemaType = exporter.GetSchemaType(memberType);
                    propertySchemaElement.SchemaTypeName = exporter.GetSchemaTypeName(memberType);

                    propertiesSequence.Items.Add(propertySchemaElement);
                }
            }

            return propertiesSequence;
        }
 internal DataRecordValuePair(IValuePair pair, ISerializationManager serializer)
     : base(pair.OriginalValue, pair.NewValue, pair.PropertyName, pair.State, serializer)
 {
 }
Example #36
0
        /// <summary>
        /// Returns the sequence of properties of the specified type.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <param name="schema">The schema.</param>
        /// <param name="schemaSet">The schema set.</param>
        /// <param name="serializationManager">The serialization manager.</param>
        /// <returns>Sequence containing all properties.</returns>
        private static XmlSchemaSequence GetPropertiesSequence(Type type, XmlSchema schema, XmlSchemaSet schemaSet, ISerializationManager serializationManager)
        {
            Argument.IsNotNull("type", type);
            Argument.IsNotNull("schema", schema);
            Argument.IsNotNull("schemaSet", schemaSet);

            var propertiesSequence = new XmlSchemaSequence();

            if (typeof(ModelBase).IsAssignableFromEx(type))
            {
                var typeNs = GetTypeNamespaceForSchema(type);

                var members = new List<MemberInfo>();
                members.AddRange(from field in serializationManager.GetFieldsToSerialize(type)
                                 select type.GetFieldEx(field));
                members.AddRange(from property in serializationManager.GetPropertiesToSerialize(type)
                                 select type.GetPropertyEx(property));

                foreach (var member in members)
                {
                    var propertySchemaElement = new XmlSchemaElement();
                    propertySchemaElement.Name = member.Name;

                    var memberType = typeof(object);
                    var fieldInfo = member as FieldInfo;
                    if (fieldInfo != null)
                    {
                        memberType = fieldInfo.FieldType;
                    }

                    var propertyInfo = member as PropertyInfo;
                    if (propertyInfo != null)
                    {
                        memberType = propertyInfo.PropertyType;
                    }

                    if (memberType.ImplementsInterfaceEx(typeof(IEnumerable)) && memberType != typeof(string))
                    {
                        propertySchemaElement.SchemaTypeName = new XmlQualifiedName(string.Format("{0}", member.Name), typeNs);

                        var collectionPropertyType = new XmlSchemaComplexType();
                        collectionPropertyType.Name = string.Format("{0}", member.Name);
                        schema.Items.Add(collectionPropertyType);

                        foreach (var genericArgument in memberType.GetGenericArguments())
                        {
                            AddTypeToSchemaSet(genericArgument, schemaSet, serializationManager);
                        }
                    }
                    else
                    {
                        propertySchemaElement.SchemaTypeName = AddTypeToSchemaSet(memberType, schemaSet, serializationManager);
                        propertySchemaElement.IsNillable = TypeHelper.IsTypeNullable(memberType);
                        propertySchemaElement.MinOccurs = 0;
                    }

                    propertiesSequence.Items.Add(propertySchemaElement);
                }
            }

            return propertiesSequence;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="DynamicConfigurationSerializerModifier"/> class.
        /// </summary>
        /// <param name="serializationManager">The serialization manager.</param>
        public DynamicConfigurationSerializerModifier(ISerializationManager serializationManager)
        {
            Argument.IsNotNull("serializationManager", serializationManager);

            _serializationManager = serializationManager;
        }
Example #38
0
        /// <summary>
        /// Creates the an xml schema for a complex type. This method automatically takes care of
        /// any base classes that must be added.
        /// <para />
        /// This method already adds the <see cref="XmlSchemaComplexType" /> to the <see cref="XmlSchemaSet" />.
        /// </summary>
        /// <param name="type">The type to create the complex schema for.</param>
        /// <param name="schema">The schema.</param>
        /// <param name="schemaSet">The schema set.</param>
        /// <param name="serializationManager">The serialization manager.</param>
        /// <param name="generateFlatSchema">A value indicating whether the schema should be generated as flat schema.</param>
        /// <returns>The complex schema for the specified type.</returns>
        private static XmlSchemaComplexType CreateSchemaComplexType(Type type, XmlSchema schema, XmlSchemaSet schemaSet, ISerializationManager serializationManager, bool generateFlatSchema)
        {
            // Determine name, which is complex in generic types
            string typeName = GetTypeNameForSchema(type);

            // First, add the type, otherwise we might get into a stackoverflow when using generic base types
            // <xs:complexType>
            var modelBaseType = new XmlSchemaComplexType();
            modelBaseType.Name = typeName;
            modelBaseType.IsMixed = false;

            schema.Items.Add(modelBaseType);

            var propertiesSequence = GetPropertiesSequence(type, schema, schemaSet, serializationManager);

            // If flat, don't generate base classes, just the type itself
            if (generateFlatSchema)
            {
                modelBaseType.Particle = propertiesSequence;
                return modelBaseType;
            }

            if (type.IsGenericType)
            {
                var genericComplexType = new XmlSchemaComplexType();
                genericComplexType.Name = typeName;

                // <xs:annotation>
                var annotation = new XmlSchemaAnnotation();

                // <xs:appinfo>
                var appInfo = new XmlSchemaAppInfo();

                //<GenericType xmlns="http://schemas.microsoft.com/2003/10/Serialization/" Name="DataContractBaseOf{0}{#}" Namespace="http://schemas.datacontract.org/2004/07/STC">
                //  <GenericParameter Name="ProfileDateRange2" Namespace="http://schemas.datacontract.org/2004/07/STC.Meter.ProfileData"/>
                //</GenericType>
                var genericTypeElement = new XElement("GenericType");
                genericTypeElement.Add(new XAttribute("Name", string.Format("{0}Of{{0}}{{#}}", typeName)));
                genericTypeElement.Add(new XAttribute("Namespace", GetTypeNamespaceForSchema(type)));

                foreach (var genericArgument in type.GetGenericArgumentsEx())
                {
                    var genericArgumentQualifiedName = AddTypeToSchemaSet(genericArgument, schemaSet, serializationManager);
                    var genericArgumentElement = new XElement("GenericParameter");
                    genericArgumentElement.Add(new XAttribute("Name", genericArgumentQualifiedName.Name));
                    genericArgumentElement.Add(new XAttribute("Namespace", genericArgumentQualifiedName.Namespace));
                    genericTypeElement.Add(genericArgumentElement);
                }

                var conversionDoc = new XmlDocument();
                appInfo.Markup = new XmlNode[] { conversionDoc.CreateTextNode(genericTypeElement.ToString()) };

                annotation.Items.Add(appInfo);
            }

            var baseTypeQualifiedName = AddTypeToSchemaSet(type.BaseType, schemaSet, serializationManager);
            if (baseTypeQualifiedName != null)
            {
                // <xs:extensions base="address">
                var complexContentExtension = new XmlSchemaComplexContentExtension();
                complexContentExtension.BaseTypeName = baseTypeQualifiedName;
                complexContentExtension.Particle = propertiesSequence;

                // <xs:complexContent>
                var complexContent = new XmlSchemaComplexContent();
                complexContent.Content = complexContentExtension;

                modelBaseType.ContentModel = complexContent;
            }

            return modelBaseType;
        }
Example #39
0
        /// <summary>
        /// Returns the sequence of properties of the specified type.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <param name="schema">The schema.</param>
        /// <param name="schemaSet">The schema set.</param>
        /// <param name="serializationManager">The serialization manager.</param>
        /// <param name="exportedTypes">The exported types.</param>
        /// <returns>Sequence containing all properties.</returns>
        private static XmlSchemaSequence GetPropertiesSequence(Type type, XmlSchema schema, XmlSchemaSet schemaSet, ISerializationManager serializationManager, HashSet<string> exportedTypes)
        {
            Argument.IsNotNull("type", type);
            Argument.IsNotNull("schema", schema);
            Argument.IsNotNull("schemaSet", schemaSet);

            var propertiesSequence = new XmlSchemaSequence();

            if (type.IsModelBase())
            {
                var members = new List<MemberMetadata>();
                members.AddRange(from field in serializationManager.GetFieldsToSerialize(type)
                                 select field.Value);
                members.AddRange(from property in serializationManager.GetCatelPropertiesToSerialize(type)
                                 select property.Value);
                members.AddRange(from property in serializationManager.GetRegularPropertiesToSerialize(type)
                                 select property.Value);

                foreach (var member in members)
                {
                    var propertySchemaElement = new XmlSchemaElement();
                    propertySchemaElement.Name = member.MemberName;

                    var memberType = member.MemberType;

                    propertySchemaElement.IsNillable = memberType.IsNullableType();
                    propertySchemaElement.MinOccurs = 0;

                    var exporter = new XsdDataContractExporter(schemaSet);

                    var alreadyExported = IsAlreadyExported(schemaSet, memberType, exporter, exportedTypes);
                    if (!alreadyExported)
                    {
                        if (!exportedTypes.Contains(memberType.FullName))
                        {
                            exportedTypes.Add(memberType.FullName);
                        }

                        try
                        {
                            if (exporter.CanExport(memberType))
                            {
                                exporter.Export(memberType);
                            }
                        }
                        catch (Exception)
                        {
                            // Ignore
                        }
                    }

                    propertySchemaElement.SchemaType = exporter.GetSchemaType(memberType);
                    propertySchemaElement.SchemaTypeName = exporter.GetSchemaTypeName(memberType);

                    propertiesSequence.Items.Add(propertySchemaElement);
                }
            }

            return propertiesSequence;
        }
Example #40
0
        /// <summary>
        /// Gets the or create schema from the schema set.
        /// <para />
        /// If the namespace does not yet exists, it is created and added. Otherwise the existing
        /// one is returned.
        /// </summary>
        /// <param name="xmlns">The xml namespace.</param>
        /// <param name="schemaSet">The schema set.</param>
        /// <param name="serializationManager">The serialization manager.</param>
        /// <returns>The xml schema to use.</returns>
        private static XmlSchema GetOrCreateSchema(string xmlns, XmlSchemaSet schemaSet, ISerializationManager serializationManager)
        {
            var schemas = schemaSet.Schemas(xmlns);

            foreach (XmlSchema schema in schemas)
            {
                return schema;
            }

            var newSchema = new XmlSchema();
            newSchema.TargetNamespace = xmlns;
            newSchema.ElementFormDefault = XmlSchemaForm.Qualified;

            schemaSet.Add(newSchema);

            return newSchema;
        }
Example #41
0
        /// <summary>
        /// Adds the type to schema set by reading the <see cref="XmlSchemaProviderAttribute" /> or by
        /// using the known schema sets information.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <param name="schemaSet">The schema set.</param>
        /// <param name="serializationManager">The serialization manager.</param>
        /// <returns>The xml qualified name.</returns>
        private static XmlQualifiedName AddTypeToSchemaSet(Type type, XmlSchemaSet schemaSet, ISerializationManager serializationManager)
        {
            var attribute = (from x in type.GetCustomAttributesEx(typeof(XmlSchemaProviderAttribute), false)
                             select x as XmlSchemaProviderAttribute).FirstOrDefault();
            if (attribute == null)
            {
                if (TypeHelper.IsBasicType(type))
                {
                    return new XmlQualifiedName(type.Name.ToLower(), Xmlns);
                }

                return null;
            }

            var methodToInvoke = type.GetMethodEx(attribute.MethodName, BindingFlags.Public | BindingFlags.Static);
            if (methodToInvoke == null)
            {
                Log.Error("Expected method '{0}.{1}' because of the XmlSchemaProvider attribute, but it was not found", type.FullName, attribute.MethodName);
                return null;
            }

            var qualifiedName = (XmlQualifiedName)methodToInvoke.Invoke(null, new object[] { schemaSet });
            return qualifiedName;
        }