Exemple #1
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ConcurrentMutablePropertyContainer"/> class.
 /// </summary>
 /// <param name="sourceValues">Property values.</param>
 /// <param name="parentPropertySource">Parent property source.</param>
 /// <param name="searchOptions">Property search options.</param>
 public ConcurrentMutablePropertyContainer(
     IEnumerable <IPropertyValue>?sourceValues = null,
     IPropertyContainer?parentPropertySource   = null,
     SearchOptions?searchOptions = null)
 {
     _propertyContainer = new MutablePropertyContainer(sourceValues, parentPropertySource, searchOptions);
 }
Exemple #2
0
        /// <inheritdoc />
        public override IPropertyContainer ReadJson(
            JsonReader reader,
            Type objectType,
            IPropertyContainer?existingValue,
            bool hasExistingValue,
            JsonSerializer serializer)
        {
            IPropertySet?schema            = null;
            bool         hasSchemaFromType = false;
            bool         hasSchemaFromJson = false;

            var propertyContainer = new MutablePropertyContainer();

            IPropertySet?knownPropertySet = objectType.GetSchemaByKnownPropertySet();

            if (knownPropertySet != null)
            {
                schema            = knownPropertySet;
                hasSchemaFromType = true;
            }

            ISchemaRepository?schemaRepository = reader.AsMetadataProvider().GetMetadata <ISchemaRepository>();

            if (Options.ReadSchemaFirst)
            {
                JObject jObject = JObject.Load(reader);

                JProperty?jProperty = jObject.Property("$metadata.schema.compact");
                if (jProperty is { First : { } schemaBody })
Exemple #3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Operation{TOperationState}"/> class.
        /// </summary>
        /// <param name="id">Operation id.</param>
        /// <param name="state">Operation state.</param>
        /// <param name="status">Operation status.</param>
        /// <param name="startedAt">Date and time of start.</param>
        /// <param name="finishedAt">Date and time of finish.</param>
        /// <param name="exception">Exception occured on task execution.</param>
        /// <param name="metadata">Optional metadata.</param>
        public Operation(
            OperationId id,
            [DisallowNull] TOperationState state,
            OperationStatus status,
            LocalDateTime?startedAt,
            LocalDateTime?finishedAt,
            Exception?exception,
            IPropertyContainer?metadata)
        {
            state.AssertArgumentNotNull(nameof(state));

            Id     = id;
            State  = state;
            Status = status;

            StartedAt  = startedAt;
            FinishedAt = finishedAt;
            Exception  = exception;

            if (metadata == null)
            {
                // If state is metadata provider itself then use it as operation metadata.
                if (state is IMetadataProvider stateMetadataProvider &&
                    stateMetadataProvider.GetMetadataContainer(autoCreate: false) is { } stateMetadata)
                {
                    Metadata = stateMetadata.ToReadOnly();
                }
                else
                {
                    Metadata = PropertyContainer.Empty;
                }
            }
Exemple #4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="OperationManager{TSessionState, TOperationState}"/> class.
        /// </summary>
        /// <param name="sessionId">Session id.</param>
        /// <param name="sessionState">Initial session state.</param>
        /// <param name="sessionManager">Owner session manager.</param>
        /// <param name="executionOptions">Optional execution options. Also can be provided in Start method.</param>
        /// <param name="logger">Logger.</param>
        /// <param name="metadata">Optional metadata.</param>
        public OperationManager(
            OperationId sessionId,
            [DisallowNull] TSessionState sessionState,
            ISessionManager <TSessionState, TOperationState> sessionManager,
            IExecutionOptions <TSessionState, TOperationState>?executionOptions = null,
            ILogger?logger = null,
            IPropertyContainer?metadata = null)
        {
            sessionState.AssertArgumentNotNull(nameof(sessionState));
            sessionManager.AssertArgumentNotNull(nameof(sessionManager));

            _sessionManager = sessionManager;
            _logger         = logger ?? GetLoggerFactory().CreateLogger(sessionId.Value);
            _operations     = new ConcurrentDictionary <OperationId, IOperation <TOperationState> >();

            _session = Operation
                       .CreateNotStarted(sessionId, sessionState, metadata)
                       .ToSession(getOperations: GetOperations);

            if (executionOptions != null)
            {
                _session = _session.With(executionOptions: executionOptions);
            }

            ILoggerFactory GetLoggerFactory() =>
            (ILoggerFactory?)_sessionManager.Services.GetService(typeof(ILoggerFactory)) ?? NullLoggerFactory.Instance;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="PropertyContainer{TSchema}"/> class.
 /// </summary>
 /// <param name="sourceValues">Source property values.</param>
 /// <param name="parentPropertySource">Parent property source.</param>
 /// <param name="searchOptions">Property search options.</param>
 public PropertyContainer(
     IEnumerable <IPropertyValue>?sourceValues = null,
     IPropertyContainer?parentPropertySource   = null,
     SearchOptions?searchOptions = null)
     : base(sourceValues, parentPropertySource, searchOptions)
 {
 }
Exemple #6
0
        public void ReadObjectWithListWithSchema()
        {
            string testXml = @"
<Person>
  <FirstName>Alex</FirstName>
  <LastName>Smith</LastName>
  <Sex>Male</Sex>
  <Addresses>
    <Address>
      <City>NY</City>
      <Zip>111</Zip>
    </Address>
    <Address>
      <City>Moscow</City>
      <Zip>222</Zip>
    </Address>
  </Addresses>
  <Address>
    <City>NY</City>
    <Zip>333</Zip>
  </Address>
</Person>";

            IObjectSchema personSchema = new PersonSchema().GetObjectSchema();

            IPropertyContainer?container = XDocument
                                           .Parse(testXml, LoadOptions.SetLineInfo)
                                           .ParseXmlToContainer(personSchema, new XmlParserSettings(validateOnParse: true));

            container.Should().NotBeNull();

            IPropertyValue[] values = container.Properties.ToArray();
            values[0].PropertyUntyped.Name.Should().Be("FirstName");
            values[0].PropertyUntyped.Type.Should().Be(typeof(string));

            values[1].PropertyUntyped.Name.Should().Be("LastName");
            values[1].PropertyUntyped.Type.Should().Be(typeof(string));

            values[2].PropertyUntyped.Name.Should().Be("Sex");
            values[2].PropertyUntyped.Type.Should().Be(typeof(Sex));

            values[3].PropertyUntyped.Name.Should().Be("Addresses");
            values[3].PropertyUntyped.Type.Should().Be(typeof(IPropertyContainer));

            values[4].PropertyUntyped.Name.Should().Be("Address");
            values[4].PropertyUntyped.Type.Should().Be(typeof(IPropertyContainer));

            var addressSchema = container.GetSchema().GetProperty("Address").GetSchema().ToObjectSchema();

            addressSchema.GetProperty("Zip").Type.Should().Be(typeof(int));

            var address = (values[4].ValueUntyped as IPropertyContainer).Properties.ToArray();

            address[0].PropertyUntyped.Name.Should().Be("City");
            address[0].PropertyUntyped.Type.Should().Be(typeof(string));

            address[1].PropertyUntyped.Name.Should().Be("Zip");
            address[1].PropertyUntyped.Type.Should().Be(typeof(int));
            address[1].ValueUntyped.Should().Be(333);
        }
Exemple #7
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MutablePropertyContainer"/> class.
 /// </summary>
 /// <param name="sourceValues">Property values.</param>
 /// <param name="parentPropertySource">Parent property source.</param>
 /// <param name="searchOptions">Property search options.</param>
 public MutablePropertyContainer(
     IEnumerable <IPropertyValue>?sourceValues = null,
     IPropertyContainer?parentPropertySource   = null,
     SearchOptions?searchOptions = null)
 {
     ParentSource = parentPropertySource;
     if (sourceValues != null)
     {
         _propertyValues.AddRange(sourceValues);
     }
     _searchOptions = searchOptions ?? Search.Default;
 }
Exemple #8
0
        public static T GetFirstDefinedValue <T>(
            this IProperty <T> property,
            IPropertyContainer?source1 = null,
            IPropertyContainer?source2 = null,
            IPropertyContainer?source3 = null,
            IPropertyContainer?source4 = null)
        {
            IPropertyValue <T>?propertyValue;

            if (source1 != null)
            {
                propertyValue = source1.GetPropertyValue(property, SearchOptions.ExistingOnly);
                if (propertyValue.HasValue())
                {
                    return(propertyValue.Value);
                }
            }

            if (source2 != null)
            {
                propertyValue = source2.GetPropertyValue(property, SearchOptions.ExistingOnly);
                if (propertyValue.HasValue())
                {
                    return(propertyValue.Value);
                }
            }

            if (source3 != null)
            {
                propertyValue = source3.GetPropertyValue(property, SearchOptions.ExistingOnly);
                if (propertyValue.HasValue())
                {
                    return(propertyValue.Value);
                }
            }

            if (source4 != null)
            {
                propertyValue = source4.GetPropertyValue(property, SearchOptions.ExistingOnly);
                if (propertyValue.HasValue())
                {
                    return(propertyValue.Value);
                }
            }

            return(property.DefaultValue.Value);
        }
Exemple #9
0
 /// <summary>
 /// Creates new instance of operation with changed properties.
 /// </summary>
 /// <typeparam name="TOperationState">Operation state.</typeparam>
 /// <param name="operation">Source operation.</param>
 /// <param name="id">New id.</param>
 /// <param name="status">New status.</param>
 /// <param name="startedAt">New startedAt.</param>
 /// <param name="finishedAt">New finishedAt.</param>
 /// <param name="exception">New exception.</param>
 /// <param name="metadata">New metadata.</param>
 /// <returns>New instance of operation with changed properties.</returns>
 public static Operation <TOperationState> With <TOperationState>(
     this IOperation <TOperationState> operation,
     OperationId?id              = default,
     OperationStatus?status      = default,
     LocalDateTime?startedAt     = default,
     LocalDateTime?finishedAt    = default,
     Exception?exception         = null,
     IPropertyContainer?metadata = null)
 {
     return(new Operation <TOperationState>(
                id: id ?? operation.Id,
                state: operation.State,
                status: status ?? operation.Status,
                startedAt: startedAt ?? operation.StartedAt,
                finishedAt: finishedAt ?? operation.FinishedAt,
                exception: exception ?? operation.Exception,
                metadata: metadata ?? operation.Metadata));
 }
Exemple #10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PropertyContainer"/> class.
        /// </summary>
        /// <param name="sourceValues">Source property values.</param>
        /// <param name="parentPropertySource">Parent property source.</param>
        /// <param name="searchOptions">Property search options.</param>
        public PropertyContainer(
            IEnumerable <IPropertyValue>?sourceValues = null,
            IPropertyContainer?parentPropertySource   = null,
            SearchOptions?searchOptions = null)
        {
            if (sourceValues == null)
            {
                Properties = Array.Empty <IPropertyValue>();
            }
            else
            {
                if (sourceValues is IPropertyContainer propertyContainer)
                {
                    sourceValues = propertyContainer.Properties;
                }

                bool isWritableCollection = sourceValues is ICollection <IPropertyValue> {
                    IsReadOnly : false
                } || sourceValues is IList {
Exemple #11
0
        public IOperationManager <TSessionState, TOperationState> CreateOperationManager(
            OperationId sessionId,
            TSessionState sessionState,
            IPropertyContainer?operationManagerMetadata = null)
        {
            ISessionManager <TSessionState, TOperationState> sessionManager = BuildSessionManager();

            IOperationManager <TSessionState, TOperationState> operationManager = new OperationManager <TSessionState, TOperationState>(
                sessionId: sessionId,
                sessionState: sessionState,
                sessionManager: sessionManager,
                executionOptions: _executionOptions,
                logger: null,
                metadata: operationManagerMetadata);

            sessionManager.AddOperationManager(operationManager);

            return(operationManager);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="SessionManager{TSessionState, TOperationState}"/> class.
        /// </summary>
        /// <param name="configuration">Configuration.</param>
        /// <param name="loggerFactory">Logger factory.</param>
        /// <param name="sessionStorage">Session storage.</param>
        /// <param name="initServices">Initializes <see cref="Services"/> that can be used in operation managers.</param>
        /// <param name="metadata">Optional metadata.</param>
        public SessionManager(
            ISessionManagerConfiguration configuration,
            ILoggerFactory loggerFactory,
            ISessionStorage <TSessionState, TOperationState> sessionStorage,
            Action <IServiceContainer>?initServices = null,
            IPropertyContainer?metadata             = null)
        {
            Configuration  = configuration.AssertArgumentNotNull(nameof(configuration));
            LoggerFactory  = loggerFactory.AssertArgumentNotNull(nameof(loggerFactory));
            SessionStorage = sessionStorage.AssertArgumentNotNull(nameof(sessionStorage));

            _metadata = new MutablePropertyContainer(sourceValues: metadata);

            var serviceContainer = new ServiceContainer();

            serviceContainer.AddService(typeof(ILoggerFactory), LoggerFactory);
            initServices?.Invoke(serviceContainer);
            Services = serviceContainer;

            GlobalLock = new SemaphoreSlim(configuration.MaxConcurrencyLevel);
            _metadata.SetValue(SessionMetricsMeta.GlobalConcurrencyLevel, configuration.MaxConcurrencyLevel);
        }
Exemple #13
0
        /// <summary>
        /// Creates new instance of <see cref="ISession{TSessionState}"/> with changes.
        /// </summary>
        /// <typeparam name="TSessionState">Session state.</typeparam>
        /// <param name="source">Source session.</param>
        /// <param name="id">New session id.</param>
        /// <param name="status">New session status.</param>
        /// <param name="startedAt">New startedAt.</param>
        /// <param name="finishedAt">New finishedAt.</param>
        /// <param name="exception">Exception.</param>
        /// <param name="metadata">Metadata for session.</param>
        /// <param name="executionOptions">Session execution options.</param>
        /// <returns>New instance of session.</returns>
        public static ISession <TSessionState> With <TSessionState>(
            this ISession <TSessionState> source,
            OperationId?id                     = null,
            OperationStatus?status             = null,
            LocalDateTime?startedAt            = null,
            LocalDateTime?finishedAt           = null,
            Exception?exception                = null,
            IPropertyContainer?metadata        = null,
            IExecutionOptions?executionOptions = null)
        {
            var sessionOperation = source.Operation.With <TSessionState>(
                id: id,
                status: status,
                startedAt: startedAt,
                finishedAt: finishedAt,
                exception: exception,
                metadata: metadata);

            return(new LazySession <TSessionState>(
                       sessionOperation: sessionOperation,
                       messages: source.Messages,
                       getOperations: source.GetOperations,
                       executionOptions: executionOptions ?? source.ExecutionOptions));
        }
        private static IPropertyContainer?ParseXmlElement(
            XElement objectElement,
            IObjectSchema objectSchema,
            IXmlParserSettings settings,
            IXmlParserContext context,
            IMutablePropertyContainer?container = null)
        {
            if (objectElement.HasElements)
            {
                container ??= new MutablePropertyContainer();

                foreach (XElement propertyElement in objectElement.Elements())
                {
                    string    elementName  = settings.GetElementName(propertyElement);
                    string    propertyName = settings.StringProvider.GetString(elementName);
                    IProperty?property     = objectSchema.GetProperty(propertyName);

                    if (propertyElement.HasElements)
                    {
                        IObjectSchema propertyInternalSchema = context.GetOrCreateNewSchemaCached(property).ToObjectSchema();

                        IPropertyContainer?internalObject = ParseXmlElement(propertyElement, propertyInternalSchema, settings, context);
                        if (internalObject != null && internalObject.Count > 0)
                        {
                            if (settings.SetSchemaForObjects)
                            {
                                internalObject.SetSchema(propertyInternalSchema);
                            }

                            if (property == null)
                            {
                                property = new Property <IPropertyContainer>(propertyName)
                                           .SetIsNotFromSchema()
                                           .SetSchema(propertyInternalSchema);

                                if (objectSchema is IMutableObjectSchema mutableObjectSchema)
                                {
                                    property = mutableObjectSchema.AddProperty(property);
                                }
                            }

                            IPropertyValue propertyValue = settings.PropertyValueFactory.CreateUntyped(property, internalObject);
                            container.Add(propertyValue);

                            // Validate property.
                            if (settings.ValidateOnParse)
                            {
                                ValidateProperty(context, container, property, propertyElement);
                            }
                        }
                    }
                    else
                    {
                        if (property != null && property.Type == typeof(IPropertyContainer))
                        {
                            // Composite object, no value.
                            bool isNullAllowed = property.GetOrEvaluateNullability().IsNullAllowed;
                            if (!isNullAllowed)
                            {
                                context.Messages.AddError(
                                    $"Property '{property.Name}' can not be null but xml element has no value.{GetXmlLineInfo(propertyElement)}");
                            }

                            continue;
                        }

                        if (property == null)
                        {
                            property = new Property <string>(propertyName)
                                       .SetIsNotFromSchema();

                            if (objectSchema is IMutableObjectSchema mutableObjectSchema)
                            {
                                property = mutableObjectSchema.AddProperty(property);
                            }
                        }

                        IValueParser valueParser = context.GetParserCached(property);
                        if (valueParser != EmptyParser.Instance)
                        {
                            string elementValue = propertyElement.Value;

                            // Parse value.
                            IParseResult parseResult = valueParser.ParseUntyped(elementValue);

                            if (parseResult.IsSuccess)
                            {
                                // Add property to container.
                                object?        parsedValue   = parseResult.ValueUntyped;
                                IPropertyValue propertyValue = settings.PropertyValueFactory.CreateUntyped(property, parsedValue);
                                container.Add(propertyValue);

                                // Validate property.
                                if (settings.ValidateOnParse)
                                {
                                    ValidateProperty(context, container, property, propertyElement);
                                }
                            }
                            else
                            {
                                string?parseResultErrorMessage = parseResult.Error?.FormattedMessage;
                                string parseResultError        = parseResultErrorMessage != null ? $" Error: '{parseResultErrorMessage}'." : string.Empty;
                                string errorMessage            = $"Property '{property.Name}' failed to parse from string '{elementValue}'.{parseResultError}{GetXmlLineInfo(propertyElement)}";
                                context.Messages.AddError(errorMessage);
                            }
                        }
                        else
                        {
                            string errorMessage = $"Property '{property.Name}' can not be parsed because no parser found for type {property.Type}.{GetXmlLineInfo(propertyElement)}";
                            context.Messages.AddError(errorMessage);
                        }
                    }
                }

                return(container);
            }

            return(null);
        }
Exemple #15
0
 public OperationUpdateMessage(IPropertyContainer?metadata = null)
 {
     Metadata = metadata ?? new MutablePropertyContainer();
 }
Exemple #16
0
        public HierarchicalContainer(IPropertyContainer propertyContainer1, IPropertyContainer?propertyContainer2)
        {
            propertyContainer1.AssertArgumentNotNull(nameof(propertyContainer1));

            _propertyContainer = PropertyContainer.CreateHierarchicalContainer(propertyContainer1, propertyContainer2);
        }
Exemple #17
0
 public static IPropertyContainer CreateHierarchicalContainer(
     IPropertyContainer propertyContainer1,
     IPropertyContainer?propertyContainer2,
     bool mergeHierarchy = true)
 {
     propertyContainer1.AssertArgumentNotNull(nameof(propertyContainer1));
Exemple #18
0
        /// <inheritdoc />
        public IOperation <TOperationState> CreateOperation(OperationId operationId, [DisallowNull] TOperationState state, IPropertyContainer?metadata = null)
        {
            var operation = Operation.CreateNotStarted(id: operationId, state: state, metadata: metadata);

            _operations[operationId] = operation;
            return(operation);
        }
Exemple #19
0
 static bool HasParent(IPropertyContainer?container) => container?.ParentSource != null && container.ParentSource.Count > 0;