Example #1
0
 public int Sum(IImmutableStack <int> stack) =>
 map(pop(stack), (newstack, option) =>
     match(option,
           Some: value => value + Sum(newstack),
           None: () => 0
           )
     );
        public ResolverTask(
            IExecutionContext executionContext,
            ObjectType objectType,
            FieldSelection fieldSelection,
            Path path,
            IImmutableStack <object> source,
            OrderedDictionary result)
        {
            _executionContext = executionContext;

            Source         = source;
            ObjectType     = objectType;
            FieldSelection = fieldSelection;
            FieldType      = fieldSelection.Field.Type;
            Path           = path;
            Result         = result;

            ResolverContext = new ResolverContext(
                executionContext, this,
                executionContext.RequestAborted);

            Options = executionContext.Options;

            ExecuteMiddleware = executionContext.GetMiddleware(
                objectType, fieldSelection.Selection);
            HasMiddleware = ExecuteMiddleware != null;
        }
Example #3
0
        private ResolverTask(
            ResolverTask parent,
            FieldSelection fieldSelection,
            Path path,
            IImmutableStack <object> source,
            IDictionary <string, object> result,
            Action propagateNonNullViolation)
        {
            _parent           = parent;
            _executionContext = parent._executionContext;
            Source            = source;
            ObjectType        = fieldSelection.Field.DeclaringType;
            FieldSelection    = fieldSelection;
            FieldType         = fieldSelection.Field.Type;
            Path                       = path;
            _result                    = result;
            ScopedContextData          = parent.ScopedContextData;
            _propagateNonNullViolation = propagateNonNullViolation;

            ResolverContext = new ResolverContext(
                parent._executionContext, this,
                parent._executionContext.RequestAborted);

            FieldDelegate = parent._executionContext.FieldHelper
                            .CreateMiddleware(fieldSelection);
        }
Example #4
0
        private void RetainEvent(PublishOptions options,
                                 Action <IRemoteWampTopicSubscriber, EventDetails> action)
        {
            Array[] all =
            {
                options.ExcludeAuthenticationIds,
                options.ExcludeAuthenticationRoles,
                options.Exclude,
                options.EligibleAuthenticationIds,
                options.EligibleAuthenticationRoles,
                options.Eligible
            };

            RetainedEvent retainedEvent = new RetainedEvent(options, action);

            // If the event has no restrictions, then it is the most recent event.
            bool hasNoRestrictions = all.All(x => x == null);

            lock (mLock)
            {
                if (hasNoRestrictions)
                {
                    mRetainedEvents = ImmutableStack <RetainedEvent> .Empty;
                }

                mRetainedEvents = mRetainedEvents.Push(retainedEvent);
            }
        }
Example #5
0
        public void Parse_Single_Chain_With_ScopedVariable()
        {
            // arrange
            var pathString = "foo(bar: $fields:foo)";

            // act
            IImmutableStack <SelectionPathComponent> path =
                SelectionPathParser.Parse(pathString);

            // assert
            Assert.Collection(path,
                              segment =>
            {
                Assert.Equal("foo", segment.Name.Value);
                Assert.Collection(segment.Arguments,
                                  argument =>
                {
                    Assert.Equal("bar", argument.Name.Value);

                    ScopedVariableNode variable =
                        Assert.IsType <ScopedVariableNode>(argument.Value);

                    Assert.Equal("fields", variable.Scope.Value);
                    Assert.Equal("foo", variable.Name.Value);
                });
            });
        }
Example #6
0
        public void Parse_PathWithoutArgs_ThreeComponentsFound()
        {
            // arrange
            var serializedPath = "foo.bar.baz";

            // act
            IImmutableStack <SelectionPathComponent> path =
                SelectionPathParser.Parse(serializedPath);

            // assert
            Assert.Collection(path.Reverse(),
                              t =>
            {
                Assert.Equal("foo", t.Name.Value);
                Assert.Empty(t.Arguments);
            },
                              t =>
            {
                Assert.Equal("bar", t.Name.Value);
                Assert.Empty(t.Arguments);
            },
                              t =>
            {
                Assert.Equal("baz", t.Name.Value);
                Assert.Empty(t.Arguments);
            });
        }
Example #7
0
        public void Parse_PathWithVarArgs_ThreeComponentsOneWithVarArgs()
        {
            // arrange
            var serializedPath = "foo(a: $foo:bar).bar.baz";

            // act
            IImmutableStack <SelectionPathComponent> path =
                SelectionPathParser.Parse(serializedPath);

            // assert
            Assert.Collection(path.Reverse(),
                              c =>
            {
                Assert.Equal("foo", c.Name.Value);
                Assert.Collection(c.Arguments,
                                  a =>
                {
                    Assert.Equal("a", a.Name.Value);
                    Assert.IsType <ScopedVariableNode>(a.Value);

                    var v = (ScopedVariableNode)a.Value;
                    Assert.Equal("foo_bar", v.ToVariableName());
                });
            },
                              c =>
            {
                Assert.Equal("bar", c.Name.Value);
                Assert.Empty(c.Arguments);
            },
                              c =>
            {
                Assert.Equal("baz", c.Name.Value);
                Assert.Empty(c.Arguments);
            });
        }
Example #8
0
        static IImmutableStack <T> GetNextElementInHierarchyCore <T>(IImmutableStack <T> rootStack, Func <T, IList <T> > getChildren, Func <IList <T>, T, int> indedOf, bool skipChildren) where T : class
        {
            var currentElement = rootStack.Peek();
            var children       = getChildren(currentElement);

            if (!skipChildren && children.Any())
            {
                return(rootStack.Push(children.First()));
            }

            var parents = rootStack.Pop();
            var parent  = parents.FirstOrDefault();

            if (parent == null)
            {
                return(rootStack);
            }

            var neighbors = getChildren(parent);
            var index     = indedOf(neighbors, currentElement);

            if (index < neighbors.Count - 1)
            {
                return(parents.Push(neighbors[index + 1]));
            }

            return(GetNextElementInHierarchyCore(parents, getChildren, indedOf, skipChildren: true));
        }
Example #9
0
        public void Setup()
        {
            List <string> list = new List <string> {
            };
            Dictionary <string, string> dict = new Dictionary <string, string> {
            };

            for (int i = 0; i < ElementCount; i++)
            {
                list.Add($"hello{i}");
                dict.Add($"hello{i}", $"world{i}");
            }

            _iimmutablelist            = ImmutableList.CreateRange(list);
            _iimmutablestack           = ImmutableStack.CreateRange(list);
            _iimmutablequeue           = ImmutableQueue.CreateRange(list);
            _iimmutableset             = ImmutableHashSet.CreateRange(list);
            _iimmutabledictionary      = ImmutableDictionary.CreateRange(dict);
            _immutablearray            = ImmutableArray.CreateRange(list);
            _immutablelist             = ImmutableList.CreateRange(list);
            _immutablestack            = ImmutableStack.CreateRange(list);
            _immutablequeue            = ImmutableQueue.CreateRange(list);
            _immutablesortedset        = ImmutableSortedSet.CreateRange(list);
            _immutablehashset          = ImmutableHashSet.CreateRange(list);
            _immutabledictionary       = ImmutableDictionary.CreateRange(dict);
            _immutablesorteddictionary = ImmutableSortedDictionary.CreateRange(dict);

            _jsonListString = System.Text.Json.JsonSerializer.Serialize(list);
            _jsonDictString = System.Text.Json.JsonSerializer.Serialize(dict);
        }
        public void TestPush()
        {
            int value = Generator.GetInt32();

            var stack = ImmutableTreeStack.Create <int>();

            Assert.Empty(stack);

            // Push doesn't change the original stack
            stack.Push(value);
            Assert.Empty(stack);

            stack = stack.Push(value);
            Assert.Single(stack);
            Assert.Equal(value, stack.Peek());
            int[] expected = { value };
            int[] actual   = stack.ToArray();
            Assert.Equal(expected, actual);

            // Test through the IImmutableStack<T> interface
            IImmutableStack <int> immutableStack = stack;

            immutableStack.Push(Generator.GetInt32());
            Assert.Equal(expected, immutableStack);

            int nextValue = Generator.GetInt32();

            immutableStack = immutableStack.Push(nextValue);
            Assert.Equal(new[] { nextValue, value }, immutableStack);
        }
Example #11
0
 private static void UpdateImmutableStack(IImmutableStack <object> stack)
 {
     if (!LogicalOperation.IsRunningInAdapter)
     {
         CallContext.LogicalSetData(LogicalOperation.CallContextDataSlotName, stack);
     }
 }
Example #12
0
        public void InterfaceCollectionTest()
        {
            IImmutableList <int> a = ImmutableList <int> .Empty.AddRange(new[] { 1, 10, 100 });

            IImmutableDictionary <int, int> b = ImmutableDictionary <int, int> .Empty.AddRange(new Dictionary <int, int> {
                { 1, 10 }, { 2, 10 }, { 3, 100 }
            });

            IImmutableSet <int> c = ImmutableHashSet <int> .Empty.Add(1).Add(10).Add(100);

            IImmutableQueue <int> d = ImmutableQueue <int> .Empty.Enqueue(1).Enqueue(10).Enqueue(100);

            IImmutableStack <int> e = ImmutableStack <int> .Empty.Push(1).Push(10).Push(100);

            Convert(a).IsStructuralEqual(a);
            Convert(b).IsStructuralEqual(b);
            Convert(c).IsStructuralEqual(c);
            Convert(d).IsStructuralEqual(d);
            Convert(e).IsStructuralEqual(e);

            a = null;
            b = null;
            c = null;
            d = null;
            e = null;
            Convert(a).IsNull();
            Convert(b).IsNull();
            Convert(c).IsNull();
            Convert(d).IsNull();
            Convert(e).IsNull();
        }
Example #13
0
        public static Tuple <IImmutableStack <T>, T> popUnsafe <T>(IImmutableStack <T> stack)
        {
            T   value;
            var newStack = stack.Pop(out value);

            return(tuple(newStack, value));
        }
Example #14
0
 public int Sum(IImmutableStack<int> stack) =>
     map( pop(stack), (newstack, option) =>
         match(option,
             Some: value => value + Sum(newstack),
             None: ()    => 0
         )
     );
        /// <summary>
        /// Saves the stack of <see cref="IAmbientDbContext"/> in the storage.
        /// </summary>
        /// <param name="stack">
        /// The stack of <see cref="IAmbientDbContext"/> to save.
        /// </param>
        public void SaveStack(IImmutableStack <IAmbientDbContext> stack)
        {
#if NET451
            var crossReferenceKey = _storage.GetValue <ContextualStorageItem>(AmbientDbContextStorageKey.Key);
#else
            var crossReferenceKey = _storage.GetValue <string>(AmbientDbContextStorageKey.Key);
#endif
            // This can only happen if something explicitly calls RemoveValue on the storage. Otherwise, there will
            // always be a value in storage.
            if (crossReferenceKey == null)
            {
                throw new AmbientDbContextException("Could not find ambient database context stack in the storage.");
            }

            IImmutableStack <IAmbientDbContext> value;

            // Drop the existing key and recreate because the value is immutable
#if NET451
            if (AmbientDbContextTable.TryGetValue(crossReferenceKey.Value, out value))
            {
                AmbientDbContextTable.Remove(crossReferenceKey.Value);
            }

            AmbientDbContextTable.Add(crossReferenceKey.Value, stack);
#else
            if (AmbientDbContextTable.TryGetValue(crossReferenceKey, out value))
            {
                AmbientDbContextTable.Remove(crossReferenceKey);
            }

            AmbientDbContextTable.Add(crossReferenceKey, stack);
#endif
        }
Example #16
0
        private static FieldNode CreateRequestedField(
            FieldNode requestedField,
            ref IImmutableStack <SelectionPathComponent> path)
        {
            path = path.Pop(out SelectionPathComponent component);

            string responseName = requestedField.Alias == null
                ? requestedField.Name.Value
                : requestedField.Alias.Value;

            NameNode alias = component.Name.Value.EqualsOrdinal(responseName)
                ? null
                : new NameNode(responseName);

            IReadOnlyList <ArgumentNode> arguments =
                component.Arguments.Count == 0
                ? requestedField.Arguments
                : RewriteVariableNames(component.Arguments).ToList();

            return(new FieldNode
                   (
                       null,
                       component.Name,
                       alias,
                       requestedField.Directives,
                       arguments,
                       requestedField.SelectionSet
                   ));
        }
        public void TestStackLikeBehavior()
        {
            var stack     = ImmutableTreeStack.Create <int>();
            var reference = new Stack <int>();

            for (int i = 0; i < 2 * 4 * 4; i++)
            {
                int item = Generator.GetInt32();
                stack = stack.Push(item);
                reference.Push(item);
            }

            while (!stack.IsEmpty)
            {
                var expected = reference.Peek();
                Assert.Equal(expected, stack.Peek());
                Assert.Equal(expected, reference.Pop());

                IImmutableStack <int> immutableStack = stack;

                stack = stack.Pop(out int value);
                Assert.Equal(expected, value);
                stack.Validate(ValidationRules.None);

                Assert.Equal(reference, stack);

                // Test through the IImmutableStack<T> interface (initialized above)
                immutableStack = immutableStack.Pop(out value);
                Assert.Equal(expected, value);
                Assert.Equal(reference, immutableStack);
            }

            Assert.Empty(stack);
            Assert.Empty(reference);
        }
Example #18
0
        private void Initialize(
            IExecutionContext executionContext,
            FieldSelection fieldSelection,
            IImmutableStack <object> source,
            IDictionary <string, object> serializedResult)
        {
            _executionContext = executionContext;
            _serializedResult = serializedResult;
            _fieldSelection   = fieldSelection;

            IsRoot            = true;
            Path              = Path.New(fieldSelection.ResponseName);
            Source            = source;
            SourceObject      = executionContext.Operation.RootValue;
            ScopedContextData = ImmutableDictionary <string, object> .Empty;

            _arguments = fieldSelection.CoerceArguments(
                executionContext.Variables,
                executionContext.Converter);

            string responseName = fieldSelection.ResponseName;

            PropagateNonNullViolation = () =>
            {
                serializedResult[responseName] = null;
            };
        }
Example #19
0
        public async Task InvokeAsync(IMiddlewareContext context)
        {
            DelegateDirective delegateDirective = context.Field
                                                  .Directives[DirectiveNames.Delegate]
                                                  .FirstOrDefault()?.ToObject <DelegateDirective>();

            if (delegateDirective != null)
            {
                IImmutableStack <SelectionPathComponent> path =
                    delegateDirective.Path is null
                    ? ImmutableStack <SelectionPathComponent> .Empty
                    : SelectionPathParser.Parse(delegateDirective.Path);

                IReadOnlyQueryRequest request =
                    CreateQuery(context, delegateDirective.Schema, path);

                IReadOnlyQueryResult result = await ExecuteQueryAsync(
                    context, request, delegateDirective.Schema)
                                              .ConfigureAwait(false);

                UpdateContextData(context, result, delegateDirective);

                context.Result = new SerializedData(
                    ExtractData(result.Data, path.Count()));
                ReportErrors(context, result.Errors);
            }

            await _next.Invoke(context).ConfigureAwait(false);
        }
Example #20
0
        public void Parse_Two_Chain_With_Literal()
        {
            // arrange
            var pathString = "foo(bar: 1).baz(quox: 2)";

            // act
            IImmutableStack <SelectionPathComponent> path =
                SelectionPathParser.Parse(pathString);

            // assert
            Assert.Collection(path.Reverse(),
                              segment =>
            {
                Assert.Equal("foo", segment.Name.Value);
                Assert.Collection(segment.Arguments,
                                  argument =>
                {
                    Assert.Equal("bar", argument.Name.Value);
                    Assert.Equal("1", argument.Value.Value);
                });
            },
                              segment =>
            {
                Assert.Equal("baz", segment.Name.Value);
                Assert.Collection(segment.Arguments,
                                  argument =>
                {
                    Assert.Equal("quox", argument.Name.Value);
                    Assert.Equal("2", argument.Value.Value);
                });
            });
        }
Example #21
0
 public IEnumerator <T> GetEnumerator()
 {
     for (IImmutableStack <T> stack = this; !stack.IsEmpty; stack = stack.Pop())
     {
         yield return(stack.Peek());
     }
 }
Example #22
0
        public static IImmutableStack <T> Pop <T>(this IImmutableStack <T> stack, out T value)
        {
            Requires.NotNull(stack, nameof(stack));

            value = stack.Peek();
            return(stack.Pop());
        }
Example #23
0
        public static IImmutableStack <T> Pop <T>(this IImmutableStack <T> stack, out T value)
        {
            Requires.NotNull(stack, "stack");
            Contract.Ensures(Contract.Result <IImmutableStack <T> >() != null);

            value = stack.Peek();
            return(stack.Pop());
        }
        /// <summary>
        /// Runs when the entire object graph has been deserialized.
        /// </summary>
        /// <param name="sender">Unused</param>
        public void OnDeserialization(object sender)
        {
            Stack <TValue> deserializedValues =
                (Stack <TValue>)m_serializationInfo.GetValue(SerializedFieldName, typeof(Stack <TValue>));

            m_store             = ImmutableStack.CreateRange(deserializedValues);
            m_serializationInfo = null;
        }
        public static IImmutableStack <T> Pop <T>(this IImmutableStack <T> stack, out T value)
        {
            //Assert.IsNotNull(stack, nameof(stack));
            Contract.Ensures(Contract.Result <IImmutableStack <T> >() != null);

            value = stack.Peek();
            return(stack.Pop());
        }
Example #26
0
 public TestClass(IImmutableDictionary <int, int> dictionary, IImmutableList <string> list, IImmutableQueue <string> queue, IImmutableSet <string> sortedSet, IImmutableSet <string> hashSet, IImmutableStack <string> stack)
 {
     Dictionary = dictionary;
     List       = list;
     Queue      = queue;
     SortedSet  = sortedSet;
     HashSet    = hashSet;
     Stack      = stack;
 }
        /// <summary>
        /// A test for Empty
        /// </summary>
        /// <typeparam name="T">The type of elements held in the stack.</typeparam>
        private void EmptyTestHelper <T>() where T : new()
        {
            IImmutableStack <T> actual = ImmutableStack <T> .Empty;

            Assert.NotNull(actual);
            Assert.True(actual.IsEmpty);
            AssertAreSame(ImmutableStack <T> .Empty, actual.Clear());
            AssertAreSame(ImmutableStack <T> .Empty, actual.Push(new T()).Clear());
        }
Example #28
0
        public static void WritePrimitiveIImmutableStackT()
        {
            IImmutableStack <int> input = ImmutableStack.CreateRange(new List <int> {
                1, 2
            });

            string json = JsonSerializer.Serialize(input);

            Assert.Equal("[2,1]", json);
        }
Example #29
0
        private static ImmutableStack <T> Reverse(IImmutableStack <T> stack)
        {
            ImmutableStack <T> immutableStack1 = ImmutableStack <T> .Empty;

            for (IImmutableStack <T> immutableStack2 = stack; !immutableStack2.IsEmpty; immutableStack2 = immutableStack2.Pop())
            {
                immutableStack1 = immutableStack1.Push(immutableStack2.Peek());
            }
            return(immutableStack1);
        }
Example #30
0
 public RemoteQueryBuilder SetSelectionPath(
     IImmutableStack <SelectionPathComponent> selectionPath)
 {
     if (selectionPath == null)
     {
         throw new ArgumentNullException(nameof(selectionPath));
     }
     _path = selectionPath;
     return(this);
 }
Example #31
0
 public void Popping5(IImmutableStack<int> test)
 {
     test = map(pop(test), (stack, value) => { Assert.IsTrue(value.IsSome); return stack; });
     test = map(pop(test), (stack, value) => { Assert.IsTrue(value.IsSome); return stack; });
     test = map(pop(test), (stack, value) => { Assert.IsTrue(value.IsSome); return stack; });
     test = map(pop(test), (stack, value) => { Assert.IsTrue(value.IsSome); return stack; });
     match(peek(test),
         Some: v => Assert.IsTrue(v == 1),
         None: () => Assert.Fail()
     );
 }
Example #32
0
 public static Option <T> peek <T>(IImmutableStack <T> stack)
 {
     try
     {
         return(Some(stack.Peek()));
     }
     catch (InvalidOperationException)
     {
         return(None);
     }
 }