Exemplo n.º 1
0
        public int CompareTo(IValueContainer <T, V> other)
        {
            int result = 0;

            if (!other.Equals(this))
            {
                if (other.PlusInfinity)
                {
                    result = -1; // this is smaller
                }
                else if (other.MinusInfinity)
                {
                    result = 1; // this is bigger
                }
                else if (this.PlusInfinity)
                {
                    result = 1; // this is bigger
                }
                else if (this.MinusInfinity)
                {
                    result = -1; // this is smaller
                }
                else
                {
                    result = this.Points.CompareTo(other.Points);
                }
            }

            return(result);
        }
Exemplo n.º 2
0
                bool IMultiTreeHandleable.Handle(IValueContainer valueContainer, Promise owner, int index)
                {
                    bool done   = --_waitCount == 0;
                    bool handle = false;

                    if (_valueOrPrevious == null)
                    {
                        owner._wasWaitedOn = true;
                        if (owner._state != State.Resolved | done)
                        {
                            valueContainer.Retain();
                            _valueOrPrevious = valueContainer;
                            handle           = true;
                        }
                        else
                        {
                            IncrementProgress(owner);
                        }
                    }
                    if (done)
                    {
                        while (_passThroughs.IsNotEmpty)
                        {
                            _passThroughs.Pop().Release();
                        }
                        ReleaseInternal();
                    }
                    return(handle);
                }
Exemplo n.º 3
0
        public object Compose(IValueContainer container, Type valueType)
        {
            var values = (TaskContainer)container;

            var resultType = TaskAccessor.GetTaskResultType(valueType);

            Task task = TaskAccessor.CreateTask(values.State, resultType);

            if (values.Status == TaskStatus.Canceled)
            {
                task.TrySetCanceled();
            }
            else if (values.Status == TaskStatus.Faulted)
            {
                task.TrySetException(values.Exception);
            }
            else if (values.Status == TaskStatus.RanToCompletion)
            {
                var result = values.Result;
                //if (result != null && resultType != result.GetType())
                //    result = Convert.ChangeType(result, resultType);
                task.TrySetResult(result);
            }

            task.SetStatus(values.Status);

            // TODO: task.SetCreationOptions(values.Options);

            return(task);
        }
Exemplo n.º 4
0
        private static int FindIndex(IValueContainer container, string nameToFind, int startIndex)
        {
            var count = container.GetCount();

            if (startIndex < 0 || startIndex >= count)
            {
                startIndex = 0;
            }

            for (var i = startIndex; i < count; i++)
            {
                var name = container.GetName(i);
                if (string.Equals(name, nameToFind, StringComparison.Ordinal))
                {
                    return(i);
                }
            }

            for (var i = 0; i < startIndex; i++)
            {
                var name = container.GetName(i);
                if (string.Equals(name, nameToFind, StringComparison.Ordinal))
                {
                    return(i);
                }
            }

            return(-1);
        }
Exemplo n.º 5
0
 public CancelDelegatePromiseCancel(Action <ReasonContainer> callback, Promise previous)
 {
     _callback               = callback;
     _previous               = previous;
     _valueContainer         = null;
     cancelationRegistration = default(CancelationRegistration);
 }
Exemplo n.º 6
0
        private void ReadAttribute(IValueContainer element, ref int offset)
        {
            byte attributeType = this.buffer[offset];

            switch (attributeType)
            {
            case 0x05:
                offset += 2;

                int valueCharCount = BitConverter.ToInt16(this.buffer, offset) * 2;

                offset       += 2;
                element.Value = Encoding.Unicode.GetString(this.buffer, offset, valueCharCount);
                offset       += valueCharCount;

                break;

            case 0x0E:
                offset++;
                element.ValueIndex = BitConverter.ToInt16(this.buffer, offset);
                offset            += 2;

                element.ValueType = (BinaryValueType)this.buffer[offset];
                offset++;

                ////we will have to find this with value descriptors
                element.Value = null;

                return;
            }

            return;
        }
Exemplo n.º 7
0
        public static bool TryConvert <TConvert>(IValueContainer valueContainer, out TConvert converted)
        {
            // Try to avoid boxing value types.
#if CSHARP_7_OR_LATER
            if (((object)valueContainer) is IValueContainer <TConvert> directContainer)
#else
            var directContainer = valueContainer as IValueContainer <TConvert>;
            if (directContainer != null)
#endif
            {
                converted = directContainer.Value;
                return(true);
            }

            if (typeof(TConvert).IsAssignableFrom(valueContainer.ValueType))
            {
                // Unfortunately, this will box if converting from a non-nullable value type to nullable.
                // I couldn't find any way around that without resorting to Expressions (which won't work for this purpose with the IL2CPP AOT compiler).
                converted = (TConvert)valueContainer.Value;
                return(true);
            }

            converted = default(TConvert);
            return(false);
        }
Exemplo n.º 8
0
            public Task ReadRoutineStateAsync(IValueContainer target, CancellationToken ct)
            {
                var routineRecord = _fabric.DataStore.GetRoutineRecord(_routineDescriptor.RoutineId);

                _fabric.Serializer.Populate(routineRecord.State, target);
                return(Task.FromResult(true));
            }
Exemplo n.º 9
0
 public void CopyValues(IValueContainer source, IValueContainer destination)
 {
     if (source is ISerializedValueContainer serializedValueContainer)
     {
         var format         = serializedValueContainer.GetFormat();
         var serializer     = _serializerProvider.GetSerializer(format);
         var serializedForm = serializedValueContainer.GetSerializedForm();
         if (serializedForm is string stringContent)
         {
             serializer.Populate(stringContent, destination);
         }
         else if (serializedForm is byte[] byteContent)
         {
             serializer.Populate(byteContent, destination);
         }
         else
         {
             throw new InvalidOperationException($"Unsupported runtime type '{serializedForm?.GetType()}' for a serialized form of '{format}'.");
         }
     }
     else
     {
         // TODO: type conversion
         source.CopyTo(destination);
     }
 }
Exemplo n.º 10
0
        private async Task <InvokeRoutineResult> RunRoutineAsync(
            ITransitionCarrier transitionCarrier,
            TransitionDescriptor transitionDescriptor,
            CancellationToken ct)
        {
            var invocationResult = new InvokeRoutineResult();

            using (_transitionScope.Enter(transitionDescriptor))
            {
                var transitionMonitor = _transitionScope.CurrentMonitor;

                var serviceId = await transitionCarrier.GetServiceIdAsync(ct);

                var methodId = await transitionCarrier.GetRoutineDescriptorAsync(ct);

                var serviceReference = _serviceResolver.Resolve(serviceId);
                var methodReference  = _methodResolver.Resolve(serviceReference.Definition, methodId);

                object serviceInstance = serviceReference.GetInstance();

                //var serviceStateContainer = _serviceStateValueContainerProvider.CreateContainer(serviceInstance);
                //var isStatefullService = serviceStateContainer.GetCount() > 0;
                //if (isStatefullService)
                //    await transitionCarrier.ReadServiceStateAsync(serviceStateContainer, ct);

                Type taskResultType =
                    methodReference.Definition.MethodInfo.ReturnType == typeof(void)
                    ? TaskAccessor.VoidTaskResultType
                    : TaskAccessor.GetTaskResultType(methodReference.Definition.MethodInfo.ReturnType);

                Task            completionTask;
                IValueContainer asmValueContainer = null;

                if (TryCreateAsyncStateMachine(methodReference.Definition.MethodInfo, methodId.IntentId, out var asmInstance, out var asmMetadata))
                {
                    var isContinuation = transitionDescriptor.Type == TransitionType.ContinueRoutine;
                    asmValueContainer = await LoadRoutineStateAsync(transitionCarrier, asmInstance, asmMetadata, isContinuation, ct);

                    asmMetadata.Owner.FieldInfo?.SetValue(asmInstance, serviceInstance);

                    transitionMonitor.OnRoutineStart(
                        serviceReference,
                        methodReference,
                        methodId,
                        serviceInstance,
                        asmInstance,
                        (transitionCarrier as TransitionCarrier)?.Caller);

                    try
                    {
                        asmInstance.MoveNext();
                        completionTask = GetCompletionTask(asmInstance, asmMetadata);
                    }
                    catch (Exception ex)
                    {
                        // The MoveNext() must not throw, but instead complete the task with an error.
                        // try-catch is added just in case for a non-compiler-generated state machine.
                        completionTask = TaskAccessor.FromException(taskResultType, ex);
                    }
                }
Exemplo n.º 11
0
 public object Compose(IValueContainer container, Type valueType)
 {
     return(typeof(HashsetSerializer)
            .GetMethod(nameof(Compose), BindingFlags.Static | BindingFlags.NonPublic)
            .MakeGenericMethod(valueType.GetGenericArguments()[0])
            .Invoke(null, new object[] { container, valueType }));
 }
Exemplo n.º 12
0
        private bool TryDecomposeValue(
            Type type, object value,
            out TypeSerializationInfo typeInfo,
            out IValueContainer container)
        {
            type = value?.GetType() ?? type;

            var decomposer = _decomposerSelector.SelectDecomposer(type);

            if (decomposer == null)
            {
                typeInfo  = null;
                container = null;
                return(false);
            }

            container = decomposer.Decompose(value);

            if (container is IValueContainerWithTypeInfo typeInfoProvider)
            {
                type = typeInfoProvider.GetObjectType();
            }

            typeInfo = GetTypeSerializationInfo(type);
            return(true);
        }
Exemplo n.º 13
0
        public object Compose(IValueContainer container, Type valueType)
        {
            var values = (ServiceProxyContainer)container;
            var proxy  = _serviceProxyBuilder.Build(values.ServiceId, values.Interfaces);

            return(proxy);
        }
Exemplo n.º 14
0
        public ValueContainerBase()
        {
            var delegatedMembers = new List <MemberInfo>();

            foreach (var mi in GetType().GetMembers(BindingFlags.Instance | BindingFlags.Public))
            {
                if (mi is FieldInfo fieldInfo)
                {
                    if (!fieldInfo.IsInitOnly && !fieldInfo.IsStatic)
                    {
                        delegatedMembers.Add(fieldInfo);
                    }
                    continue;
                }

                if (mi is PropertyInfo propertyInfo)
                {
                    if (propertyInfo.CanRead && propertyInfo.CanWrite && !propertyInfo.GetMethod.IsStatic)
                    {
                        delegatedMembers.Add(propertyInfo);
                    }
                    continue;
                }
            }

            var containerType = ValueContainerTypeBuilder.Build(GetType(), delegatedMembers);

            _impl = (IValueContainer)Activator.CreateInstance(containerType, new object[] { this });
        }
Exemplo n.º 15
0
 public void Populate(TextReader reader, IValueContainer target)
 {
     using (var valueReader = _valueTextReaderFactory.Create(reader))
     {
         var reconstructor = new ObjectReconstructor(_composerSelector, target, _typeSerializerHelper);
         valueReader.Read(reconstructor);
     }
 }
Exemplo n.º 16
0
 public Task ReadRoutineParametersAsync(IValueContainer target, CancellationToken ct)
 {
     if (_message.TryGetValue("Parameters", out var data))
     {
         _fabric.Serializer.Populate(data, target);
     }
     return(Task.FromResult(true));
 }
Exemplo n.º 17
0
            public Task ReadServiceStateAsync(IValueContainer target, CancellationToken ct)
            {
#warning pre-cache
                var serviceId   = GetServiceIdAsync(ct).Result;
                var stateRecord = _fabric.GetOrCreateServiceStateRecord(serviceId);
                _fabric.Serializer.Populate(stateRecord.State, target);
                return(Task.FromResult(true));
            }
Exemplo n.º 18
0
            public void InvokeFromToken(IValueContainer valueContainer, IDisposableTreeHandleable owner)
            {
                // Disposing the owner sets _callback to null, so copy to stack first.
                var callback = _callback;

                owner.Dispose();
                callback.Invoke(new ReasonContainer(valueContainer));
            }
Exemplo n.º 19
0
        public object Compose(IValueContainer container, Type valueType)
        {
            var values  = (AwaiterContainer)container;
            var awaiter = Activator.CreateInstance(valueType);

            TaskAwaiterUtils.SetTask(awaiter, values.Task);
            return(awaiter);
        }
Exemplo n.º 20
0
 public Task ReadRoutineParametersAsync(IValueContainer target, CancellationToken ct)
 {
     if (!string.IsNullOrEmpty(EventData.Parameters))
     {
         _fabric.Serializer.Populate(EventData.Parameters, target);
     }
     return(Task.FromResult(true));
 }
Exemplo n.º 21
0
 void Dispose()
 {
     _onCanceled     = null;
     _valueContainer = null;
     if (Config.ObjectPooling != PoolType.None)
     {
         _pool.Push(this);
     }
 }
Exemplo n.º 22
0
 void Dispose()
 {
     _capturedValue  = default(TCapture);
     _onCanceled     = null;
     _valueContainer = null;
     if (Config.ObjectPooling != PoolType.None)
     {
         _pool.Push(this);
     }
 }
Exemplo n.º 23
0
 public Task ReadRoutineStateAsync(IValueContainer target, CancellationToken ct)
 {
     if (FileBasedFabricConnector.TryReadRoutineData(
             _fabric.RoutinesDirectory, EventData.Routine.RoutineId,
             out var dataEnvelope, out var eTag) && dataEnvelope.State != null)
     {
         _fabric.Serializer.Populate(dataEnvelope.State, target);
     }
     return(Task.FromResult(true));
 }
Exemplo n.º 24
0
        public static object[] GetValues(this IValueContainer container)
        {
            var values = new object[container.GetCount()];

            for (var i = 0; i < values.Length; i++)
            {
                values[i] = container.GetValue(i);
            }
            return(values);
        }
Exemplo n.º 25
0
        public object Compose(IValueContainer container, Type valueType)
        {
            var entityKeyContainer = (EntityKeyContainer)container;
            var entityClrType      = entityKeyContainer.GetObjectType();
            var dbContextType      = _entityToContextTypeMap[entityClrType];
            var dbContext          = (DbContext)_scopedServiceProvider.GetService(dbContextType);
            var entity             = dbContext.Find(entityClrType, entityKeyContainer.GetValues());

            // What if an entity does not exist anymore? Is returning NULL ok?
            return(entity);
        }
Exemplo n.º 26
0
        public ResultType Fetch <ResultType>(string identifier)
        {
            if (containers.ContainsKey(identifier) == false)
            {
                containers[identifier] = factory.Make(identifier);
            }
            IValueContainer result = containers[identifier].currentContainer;

            Assert.IsTrue(result is ResultType);
            return((ResultType)result);
        }
Exemplo n.º 27
0
        public static IValueContainer Clone(this IValueContainer container)
        {
            var copy       = new ValueContainer();
            var valueCount = container.GetCount();

            for (var i = 0; i < valueCount; i++)
            {
                copy.Add(container.GetName(i), container.GetType(i), container.GetValue(i));
            }
            return(copy);
        }
Exemplo n.º 28
0
        public object Compose(IValueContainer container, Type valueType)
        {
            var c = (EntityProjectionContainer)container;
            var projectionInterface = _typeNameShortener.TryExpand(c.Type, out var type) ? type : Type.GetType(c.Type);
            var result = EntityProjection.CreateInstance(projectionInterface);

            if (c.Properties != null)
            {
                foreach (var pair in c.Properties)
                {
                    // BAD CODE
                    // The problem is in JSON serialization, so we have to perform some extra type checks and conversion.
                    // I know, it's bad, just need to make it work as a quick-fix without going back to the drawing board.
                    var value = pair.Value;
                    if (value != null)
                    {
                        var expectedValueType = projectionInterface.GetProperty(pair.Key).PropertyType;
                        var actualValueType   = value.GetType();
                        if (actualValueType != expectedValueType)
                        {
                            if ((expectedValueType == typeof(Guid) || expectedValueType == typeof(Guid?)) && actualValueType == typeof(string))
                            {
                                value = Guid.Parse((string)value);
                            }
                            else if (expectedValueType == typeof(Uri) && actualValueType == typeof(string))
                            {
                                value = new Uri((string)value);
                            }
                            else if (expectedValueType.IsEnum)
                            {
                                value = Enum.ToObject(expectedValueType, value);
                            }
                            else if (expectedValueType.IsGenericType && !expectedValueType.IsClass && expectedValueType.Name == "Nullable`1")
                            {
                                var nullableValueType = expectedValueType.GetGenericArguments()[0];
                                if (nullableValueType != actualValueType)
                                {
                                    value = Convert.ChangeType(value, nullableValueType);
                                }
                                value = Activator.CreateInstance(expectedValueType, value);
                            }
                            else
                            {
                                value = Convert.ChangeType(value, expectedValueType);
                            }
                        }
                    }
                    // BAD CODE

                    EntityProjection.SetValue(result, pair.Key, value);
                }
            }
            return(result);
        }
        private ISqlExpression GetDateParm(IValueContainer parameter)
        {
            if (parameter != null && parameter is SqlParameter)
            {
                var p = ((SqlParameter)parameter);
                p.DataType = DataType.Date;
                return(p);
            }

            return(null);
        }
Exemplo n.º 30
0
 public void Populate(Stream stream, IValueContainer target)
 {
     using (var textReader = new StreamReader(stream, UTF8, true, 4096, leaveOpen: true))
     {
         using (var valueReader = _valueTextReaderFactory.Create(textReader))
         {
             var reconstructor = new ObjectReconstructor(_composerSelector, target, _typeSerializerHelper);
             valueReader.Read(reconstructor);
         }
     }
 }