Ejemplo n.º 1
0
        public void UpsertAllocatesNewNode()
        {
            var txn = Substitute.For <ITransaction>();

            transactionFactory.NewTransaction(client).Returns(txn);

            txn.Query(Arg.Any <string>()).Returns(Results.Ok <string>("{\"q\":[]}"));
            txn.Mutate(Arg.Any <string>()).Returns(Results.Ok <IDictionary <string, string> >(new Dictionary <string, string> {
                { "upsertNode", "0x1bf" }
            }));
            txn.Commit().Returns(Results.Ok());

            var result = client.Upsert("aPredicate", GraphValue.BuildStringValue("aString"));

            Assert.IsTrue(result.IsSuccess);
            var(node, existed) = result.Value;
            Assert.IsFalse(existed);
            switch (node)
            {
            case UIDNode uidnode:
                Assert.AreEqual((ulong)447, uidnode.UID);
                break;

            default:
                Assert.Fail("Wrong node type");
                break;
            }
        }
Ejemplo n.º 2
0
        private async Task ProcessGenres(IDgraphBatchingClient client)
        {
            // Each line in genre file looks like
            //
            // genre-name|genreID
            //
            // We'll use a client-side node named "genre<genreID>" to identify each genre node.
            // That name isn't persisted in the store in this example, it's just for client-side reference.
            using (FileStream fs = new FileStream(genreFile, FileMode.Open)) {
                using (StreamReader genres = new StreamReader(fs)) {
                    string line;

                    while ((line = genres.ReadLine()) != null)
                    {
                        Interlocked.Increment(ref numProcessed);

                        var split = line.Split(new char[] { '|' });

                        if (split.Length == 2)
                        {
                            var node = await client.GetOrCreateNode("genre" + split[1]);

                            if (node.IsSuccess)
                            {
                                var edge = Clients.BuildProperty(node.Value, "name", GraphValue.BuildStringValue(split[0]));
                                if (edge.IsSuccess)
                                {
                                    await client.BatchAddProperty(edge.Value);
                                }
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 3
0
        public void ToStringWorks()
        {
            Assert.AreEqual(
                "True",
                GraphValue.BuildBoolValue(true).ToString());

            var bytes = System.Text.Encoding.UTF8.GetBytes("test");

            Assert.AreEqual(
                System.Text.Encoding.UTF8.GetString(bytes),
                GraphValue.BuildBytesValue(bytes).ToString());

            var now    = DateTime.Now;
            var format = "yyyy-MM-dd'T'HH:mm:ss.fffzzz";

            Assert.AreEqual(
                now.ToString(format, DateTimeFormatInfo.InvariantInfo),
                GraphValue.BuildDateValue(
                    Encoding.UTF8.GetBytes(
                        now.ToString(format, DateTimeFormatInfo.InvariantInfo))).ToString());

            var geojson    = "{'type':'Point','coordinates':[-122.4220186,37.772318]}";
            var geojsonVal = GraphValue.BuildGeoValue(geojson);

            Assert.AreEqual(
                geojson,
                geojsonVal.ToString());
        }
Ejemplo n.º 4
0
        public void CanUseGraphValueResolver_ToResolveValues_InAJob(NodeSet.RenderExecutionModel computeType)
        {
            using (var results = new NativeArray <float>(1, Allocator.Persistent))
                using (var set = new RenderGraphTests.PotentiallyJobifiedNodeSet(computeType))
                {
                    var root = set.Create <RenderPipe>();

                    GraphValue <float> rootValue = set.CreateGraphValue(root, RenderPipe.KernelPorts.Output);

                    for (int i = 0; i < 100; ++i)
                    {
                        set.SendMessage(root, RenderPipe.SimulationPorts.Input, i);

                        set.Update();

                        GraphValueReadbackJob job;

                        job.Value    = rootValue;
                        job.Result   = results;
                        job.Resolver = set.GetGraphValueResolver(out var valueResolverDependency);

                        set.InjectDependencyFromConsumer(job.Schedule(valueResolverDependency));

                        // Automatically fences before CopyWorlds. Results is accessible now.
                        set.Update();

                        Assert.AreEqual(i, results[0]);
                        Assert.AreEqual(i, set.GetValueBlocking(rootValue));
                    }

                    set.Destroy(root);
                    set.ReleaseGraphValue(rootValue);
                }
        }
Ejemplo n.º 5
0
        public async Task UpsertHandlesTransactionConflict()
        {
            var txn = Substitute.For <ITransaction>();

            transactionFactory.NewTransaction(client).Returns(txn);

            txn.Query(Arg.Any <string>()).Returns(Results.Ok <string>("{\"q\":[]}"), Results.Ok <string>("{\"q\":[{\"uid\":\"0x1bf\"}]}"));
            txn.Mutate(Arg.Any <string>()).Returns(Results.Ok <IDictionary <string, string> >(new Dictionary <string, string> {
                { "blank-0", "0xfff" }
            }));
            txn.Commit().Returns(Results.Fail("This transaction had a conflict"));

            var result = await client.Upsert("aPredicate", GraphValue.BuildStringValue("aString"), "a mutation");

            Assert.IsTrue(result.IsSuccess);
            var(node, existed) = result.Value;
            Assert.IsTrue(existed);
            switch (node)
            {
            case UIDNode uidnode:
                Assert.AreEqual((ulong)447, uidnode.UID);
                break;

            default:
                Assert.Fail("Wrong node type");
                break;
            }
        }
Ejemplo n.º 6
0
        public void FeedbackTraversalOrder_IsCoherent([Values] NodeSet.RenderExecutionModel model)
        {
            using (var set = new NodeSet())
            {
                set.RendererModel = model;

                var node1 = set.Create <KernelAdderNode>();
                var node2 = set.Create <KernelAdderNode>();
                GraphValue <int> node1GV = set.CreateGraphValue(node1, KernelAdderNode.KernelPorts.Output);
                GraphValue <int> node2GV = set.CreateGraphValue(node2, KernelAdderNode.KernelPorts.Output);

                set.Connect(node1, KernelAdderNode.KernelPorts.Output, node2, KernelAdderNode.KernelPorts.Input, NodeSet.ConnectionType.Feedback);

                for (int i = 0; i < 10; ++i)
                {
                    set.SetData(node1, KernelAdderNode.KernelPorts.Input, i);
                    set.Update();
                    Assert.AreEqual(i + 1, set.GetValueBlocking(node1GV));
                    Assert.AreEqual(i + 1, set.GetValueBlocking(node2GV));
                }

                set.ReleaseGraphValue(node1GV);
                set.ReleaseGraphValue(node2GV);
                set.Destroy(node1, node2);
            }
        }
Ejemplo n.º 7
0
        public void ResolvedGraphBuffers_AreReadOnly()
        {
            using (var results = new NativeArray <int>(1, Allocator.Persistent))
                using (var set = new RenderGraphTests.PotentiallyJobifiedNodeSet(NodeSet.RenderExecutionModel.MaximallyParallel))
                {
                    var root = set.Create <RenderPipeAggregate>();

                    GraphValue <Aggregate> rootValue = set.CreateGraphValue(root, RenderPipeAggregate.KernelPorts.Output);

                    Aggregate aggr = default;
                    aggr.InputPlusOneI = Buffer <int> .SizeRequest(1);

                    set.SetBufferSize(root, RenderPipeAggregate.KernelPorts.Output, aggr);

                    set.Update();

                    CheckReadOnlyNess_OfResolvedGraphBuffer job;

                    job.Value    = rootValue;
                    job.Result   = results;
                    job.Resolver = set.GetGraphValueResolver(out var valueResolverDependency);

                    set.InjectDependencyFromConsumer(job.Schedule(valueResolverDependency));

                    set.Update();

                    Assert.AreEqual(1, results[0]);

                    set.Destroy(root);
                    set.ReleaseGraphValue(rootValue);
                }
        }
Ejemplo n.º 8
0
        public void TwoNodeFeedbackLoop_Works([Values] NodeSet.RenderExecutionModel model)
        {
            using (var set = new NodeSet())
            {
                set.RendererModel = model;

                var node1 = set.Create <KernelAdderNode>();
                var node2 = set.Create <KernelAdderNode>();
                GraphValue <int> node1GV = set.CreateGraphValue(node1, KernelAdderNode.KernelPorts.Output);
                GraphValue <int> node2GV = set.CreateGraphValue(node2, KernelAdderNode.KernelPorts.Output);

                set.Connect(node1, KernelAdderNode.KernelPorts.Output, node2, KernelAdderNode.KernelPorts.Input);
                set.Connect(node2, KernelAdderNode.KernelPorts.Output, node1, KernelAdderNode.KernelPorts.Input, NodeSet.ConnectionType.Feedback);

                // After the first update, we expect GVs 1,2. On the next update, the 2 should be fedback into node1, so we expect 3,4. Next, 5,6...
                for (int i = 0; i < 10; ++i)
                {
                    set.Update();
                    Assert.AreEqual(i * 2 + 1, set.GetValueBlocking(node1GV));
                    Assert.AreEqual(i * 2 + 2, set.GetValueBlocking(node2GV));
                }

                set.ReleaseGraphValue(node1GV);
                set.ReleaseGraphValue(node2GV);
                set.Destroy(node1, node2);
            }
        }
Ejemplo n.º 9
0
        static void FillTestData()
        {
            long count = Db.SQL <long>("SELECT COUNT(g) FROM Simplified.Ring6.Graph g").First;

            if (count > 5)
            {
                return;
            }

            Db.Transact(() => {
                Simplified.Ring6.Graph gr = new Simplified.Ring6.Graph()
                {
                    Name = "Graph" + (count + 1), Description = "Test graph " + (count + 1)
                };
                string[] names = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.MonthNames;
                for (int i = 0; i < names.Length; i++)
                {
                    GraphValue v = new GraphValue()
                    {
                        Graph  = gr,
                        XValue = i + 1,
                        XLabel = names[i],
                        YValue = Math.Round(1.0M / ((i + 1) / (decimal)(names.Length / 2)), 4)
                    };
                }
            });
        }
Ejemplo n.º 10
0
        public async Task UpsertReturnsExistingNode()
        {
            var txn = Substitute.For <ITransaction>();

            transactionFactory.NewTransaction(client).Returns(txn);

            txn.Query(Arg.Any <string>()).Returns(Results.Ok <string>("{\"q\":[{\"uid\":\"0x1bf\"}]}"));

            var result = await client.Upsert(
                "aPredicate",
                GraphValue.BuildStringValue("aString"),
                "a mutation",
                "aBlankName");

            Assert.IsTrue(result.IsSuccess);
            var(node, existed) = result.Value;
            Assert.IsTrue(existed);
            switch (node)
            {
            case UIDNode uidnode:
                Assert.AreEqual((ulong)447, uidnode.UID);
                break;

            default:
                Assert.Fail("Wrong node type");
                break;
            }
        }
        public VertexProperty SetProperty([NotNull] string key, GraphValue value)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            if (value == null)
            {
                return(new VertexProperty(key, null));
            }

            var property = new VertexProperty(key, value);

            if (vertexProperties.ContainsKey(key))
            {
                vertexProperties[key] = property;
            }
            else
            {
                vertexProperties.Add(key, property);
            }

            return(property);
        }
Ejemplo n.º 12
0
        public void ValuesAreRight()
        {
            Assert.AreEqual(
                true,
                GraphValue.BuildBoolValue(true).BoolValue);

            Assert.AreEqual(
                new byte[] { 0x20, 0x20, 0x20 },
                GraphValue.BuildBytesValue(new byte[] { 0x20, 0x20, 0x20 }).Bytesvalue);

            var now = DateTime.Now;

            Assert.AreEqual(
                Encoding.UTF8.GetBytes(
                    now.ToString("yyyy-MM-dd'T'HH:mm:ss.fffzzz", DateTimeFormatInfo.InvariantInfo)),
                GraphValue.BuildDateValue(
                    Encoding.UTF8.GetBytes(
                        now.ToString("yyyy-MM-dd'T'HH:mm:ss.fffzzz", DateTimeFormatInfo.InvariantInfo))).DateValue);

            var valNow = GraphValue.BuildDateValue(now);

            Assert.AreEqual(
                now.ToString("yyyy-MM-dd'T'HH:mm:ss.fffzzz", DateTimeFormatInfo.InvariantInfo),
                Encoding.UTF8.GetString(valNow.DateValue, 0, valNow.DateValue.Length));

            Assert.AreEqual(
                "blaa",
                GraphValue.BuildDefaultValue("blaa").DefaultValue);

            Assert.AreEqual(
                123,
                GraphValue.BuildDoubleValue(123).DoubleValue);

            Assert.AreEqual(
                Encoding.UTF8.GetBytes("{'type':'Point','coordinates':[-122.4220186,37.772318]}"),
                GraphValue.BuildGeoValue(
                    Encoding.UTF8.GetBytes("{'type':'Point','coordinates':[-122.4220186,37.772318]}")).GeoValue);

            var geojson    = "{'type':'Point','coordinates':[-122.4220186,37.772318]}";
            var geojsonVal = GraphValue.BuildGeoValue(geojson);

            Assert.AreEqual(
                geojson,
                Encoding.UTF8.GetString(geojsonVal.GeoValue, 0, geojsonVal.GeoValue.Length));

            Assert.AreEqual(
                123,
                GraphValue.BuildIntValue(123).IntValue);

            Assert.AreEqual(
                "secret",
                GraphValue.BuildPasswordValue("secret").PasswordValue);

            Assert.AreEqual(
                "something",
                GraphValue.BuildStringValue("something").StringValue);
        }
Ejemplo n.º 13
0
        static void Main(string[] args)
        {
            using (IDgraphMutationsClient client = DgraphDotNet.Clients.NewDgraphMutationsClient("127.0.0.1:5080")) {
                client.Connect("127.0.0.1:9080");

                client.AlterSchema(
                    "Username: string @index(hash) .\n"
                    + "Password: password .");

                while (true)
                {
                    Console.WriteLine("Hi, please enter your new username");
                    var username = Console.ReadLine();

                    // use Upsert to test for a node and value, and create if
                    // not already in the graph as an atomic operation.
                    var result = client.Upsert("Username", GraphValue.BuildStringValue(username));

                    if (result.IsFailed)
                    {
                        Console.WriteLine("Something went wrong : " + result);
                        continue;
                    }

                    var(node, existed) = result.Value;

                    if (existed)
                    {
                        Console.WriteLine("This user already existed.  Try another username.");
                        continue;
                    }

                    Console.WriteLine("Hi, please enter a password for the new user");
                    var password = Console.ReadLine();

                    using (var txn = client.NewTransactionWithMutations()) {
                        var mutation = txn.NewMutation();
                        var property = Clients.BuildProperty(node, "Password", GraphValue.BuildPasswordValue(password));
                        if (property.IsFailed)
                        {
                            // ... something went wrong
                        }
                        else
                        {
                            mutation.AddProperty(property.Value);
                            var err = mutation.Submit();
                            if (err.IsFailed)
                            {
                                // ... something went wrong
                            }
                        }
                        txn.Commit();
                    }
                }
            }
        }
Ejemplo n.º 14
0
        public void NumDeletionsIsCorrect()
        {
            Mutation mut = new DgraphDotNet.Mutation();

            Edge     edge     = new Edge(new NamedNode(1, "N1"), "AnEdge", new NamedNode(2, "N2"));
            Property property = new Property(new NamedNode(1, "N1"), "AProperty", GraphValue.BuildBoolValue(true));

            mut.DeleteEdge(edge);
            mut.DeleteProperty(property);

            Assert.AreEqual(2, mut.NumDeletions);
        }
Ejemplo n.º 15
0
        public async Task UpsertReturnsError()
        {
            var txn = Substitute.For <ITransaction>();

            transactionFactory.NewTransaction(client).Returns(txn);

            txn.Query(Arg.Any <string>()).Returns(Results.Fail <string>("This didn't work"));

            var node = await client.Upsert("aPredicate", GraphValue.BuildStringValue("aString"), "a mutation");

            Assert.IsTrue(node.IsFailed);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="persisted"></param>
        public VertexProperty([NotNull] string key, [CanBeNull] GraphValue value, bool persisted = false)
        {
            Key       = key ?? throw new ArgumentNullException(nameof(key));
            Value     = value;
            Persisted = persisted;

            if (!persisted && key != "partition")
            {
                SetMeta("createdOn", DateTime.Now);
                SetMeta("createdBy", $"'{RequestContext.Get("User")}'");
            }
        }
Ejemplo n.º 17
0
        public void TestLong()
        {
            const long a = 123456789012345;
            GraphValue b = a;

            var c = b.ToGraphString();

            Assert.Equal("123456789012345", c);

            GraphValue d = c;
            long       e = d;

            Assert.Equal(a, e);
        }
Ejemplo n.º 18
0
        public void TestBoolean()
        {
            const bool a = true;
            GraphValue b = a;

            var c = b.ToGraphString();

            Assert.Equal("true", c);

            GraphValue d = c;
            bool       e = d;

            Assert.Equal(a, e);
        }
Ejemplo n.º 19
0
        public void TestString()
        {
            const string a = "Seattle, WA";
            GraphValue   b = a;

            var c = b.ToGraphString();

            Assert.Equal("'Seattle, WA'", c);

            GraphValue d = c;
            string     e = d;

            Assert.Equal(a, e);
        }
Ejemplo n.º 20
0
        public void TestDateTime()
        {
            var        a = DateTime.Parse("2017-10-06T11:59:51.4023776Z");
            GraphValue b = a;

            var c = b.ToGraphString();

            Assert.Equal("'2017-10-06T11:59:51.4023776Z'", c);

            GraphValue d = c;
            DateTime   e = d;

            Assert.Equal(a, e);
        }
Ejemplo n.º 21
0
        private async Task UpsertExistingNodeReturnsTrue(IDgraphClient client)
        {
            var upsertResult =
                await client.Upsert(
                    nameof(User.Username),
                    GraphValue.BuildStringValue(User1.Username),
                    JsonConvert.SerializeObject(User1));

            AssertResultIsSuccess(upsertResult);

            var(node, existing) = upsertResult.Value;
            existing.Should().BeTrue();
            string.Format("0x{0:x}", node.UID).Should().Be(User1.uid);
        }
Ejemplo n.º 22
0
        public void TestFloat()
        {
            const float a = 123.45f;
            GraphValue  b = a;

            var c = b.ToGraphString();

            Assert.Equal("123.45", c);

            GraphValue d = c;
            float      e = d;

            Assert.Equal(a, e);
        }
Ejemplo n.º 23
0
        public void TestGuid()
        {
            var        a = Guid.ParseExact("1a189755-8322-443e-8cca-a5c4c83d6207", "D");
            GraphValue b = a;

            var c = b.ToGraphString();

            Assert.Equal("'1a189755-8322-443e-8cca-a5c4c83d6207'", c);

            GraphValue d = c;
            Guid       e = d;

            Assert.Equal(a, e);
        }
Ejemplo n.º 24
0
        public void TestInt()
        {
            const int  a = 123;
            GraphValue b = a;

            var c = b.ToGraphString();

            Assert.Equal("123", c);

            GraphValue d = c;
            int        e = d;

            Assert.Equal(a, e);
        }
Ejemplo n.º 25
0
        public void TestDouble()
        {
            const double a = 123.456754567;
            GraphValue   b = a;

            var c = b.ToGraphString();

            Assert.Equal("123.456754567", c);

            GraphValue d = c;
            double     e = d;

            Assert.Equal(a, e);
        }
Ejemplo n.º 26
0
        public void TestDecimal()
        {
            const decimal a = 123.456754567m;
            GraphValue    b = a;

            var c = b.ToGraphString();

            Assert.Equal("123.456754567", c);

            GraphValue d = c;
            decimal    e = d;

            Assert.Equal(a, e);
        }
Ejemplo n.º 27
0
        public void NumAdditonsIsCorrect()
        {
            Mutation mut = new DgraphDotNet.Mutation();

            var      n1       = new UIDNode(1);
            var      n2       = new UIDNode(2);
            Edge     edge     = new Edge(n1, "AnEdge", n2);
            Property property = new Property(n1, "AProperty", GraphValue.BuildBoolValue(true));

            mut.AddEdge(edge);
            mut.AddProperty(property);

            Assert.AreEqual(2, mut.NumAdditions);
        }
        IEdgeResult IEdgeResult.property(string key, GraphValue value)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            queryBuilder.Append($".property('{key}',{value.ToGraphString()})");
            return(this);
        }
Ejemplo n.º 29
0
        IVertexResult IVertexResult.has(string label, string key, GraphValue value)
        {
            if (label == null)
            {
                throw new ArgumentNullException(nameof(label));
            }
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            queryBuilder.Append($".has('{label}','{key}',{value.ToGraphString()})");

            return(this);
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Gives back the geoloactionData of all the items
        /// </summary>
        public WidgetData GetGeoLocationData(DateTime?timestamp = null)
        {
            //Create Widgetdata
            WidgetData geoData = new WidgetData()
            {
                KeyValue    = "geo",
                GraphValues = new List <GraphValue>()
            };

            //Get all persons
            IEnumerable <Person> persons = new ItemManager().GetAllItemsWithInformations();

            if (persons == null || persons.Count() == 0)
            {
                return(geoData);
            }

            //Determine timestamp
            if (timestamp == null)
            {
                timestamp = DateTime.Now.AddDays(-30);
            }

            //Fill geoData
            foreach (Person item in persons)
            {
                //Check is district already exsists
                GraphValue graphValue;
                graphValue = geoData.GraphValues.Where(value => value.Value.ToLower().Equals(item.District.ToLower())).SingleOrDefault();
                int numberOfInfos = item.Informations.Where(info => info.CreationDate >= timestamp).Count();

                if (graphValue == null)
                {
                    graphValue = new GraphValue()
                    {
                        Value         = item.District,
                        NumberOfTimes = numberOfInfos
                    };
                    geoData.GraphValues.Add(graphValue);
                }
                else
                {
                    graphValue.NumberOfTimes += numberOfInfos;
                }
            }

            return(geoData);
        }
Ejemplo n.º 31
0
        static void FillTestData() {
            long count = Db.SQL<long>("SELECT COUNT(g) FROM Simplified.Ring6.Graph g").First;
            if (count > 5) {
                return;
            }

            Db.Transact(() => {
                Simplified.Ring6.Graph gr = new Simplified.Ring6.Graph() { Name = "Graph" + (count + 1), Description = "Test graph " + (count + 1) };
                string[] names = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.MonthNames;
                for (int i = 0; i < names.Length; i++) {
                    GraphValue v = new GraphValue() {
                        Graph = gr,
                        XValue = i + 1,
                        XLabel = names[i],
                        YValue = Math.Round(1.0M / ((i + 1) / (decimal)(names.Length / 2)), 4)
                    };
                }
            });
        }