示例#1
0
        public void SparqlConflictingParamNames()
        {
            String baseQuery = @"SELECT * WHERE {
    ?s a @type ; a @type1 ; a @type2 .
}";
            SparqlParameterizedString query  = new SparqlParameterizedString(baseQuery);
            SparqlQueryParser         parser = new SparqlQueryParser();

            query.SetUri("type", new Uri("http://example.org/type"));

            Console.WriteLine("Only one of the type parameters should be replaced here");
            Console.WriteLine(query.ToString());
            Console.WriteLine();

            query.SetUri("type1", new Uri("http://example.org/anotherType"));
            query.SetUri("type2", new Uri("http://example.org/yetAnotherType"));

            Console.WriteLine("Now all the type parameters should have been replaced");
            Console.WriteLine(query.ToString());
            Console.WriteLine();

            Assert.Throws <FormatException>(() =>
            {
                query.SetUri("not valid", new Uri("http://example.org/invalidParam"));
            });

            query.SetUri("is_valid", new Uri("http://example.org/validParam"));
        }
示例#2
0
        public void SparqlParameterizedStringWithNulls2()
        {
            SparqlParameterizedString query = new SparqlParameterizedString();
            query.CommandText = "SELECT * WHERE { @s ?p ?o }";

            //Set a URI to a valid value
            query.SetUri("s", new Uri("http://example.org"));
            Console.WriteLine(query.ToString());
            Console.WriteLine();

            //Set the URI to a null
            query.SetUri("s", null);
        }
 private IEnumerable<SparqlUpdateCommand> GetDeleteEntityCommands(IEnumerable<EntityId> entityGraphs)
 {
     foreach (EntityId entityId in entityGraphs)
     {
         SparqlParameterizedString delete = new SparqlParameterizedString(DeleteEntityGraphCommandText);
         delete.SetUri("metaGraph", _metaGraphUri);
         delete.SetUri("entityId", entityId.Uri);
         foreach (var command in _parser.ParseFromString(delete).Commands)
         {
             yield return command;
         }
     }
 }
示例#4
0
        public void SparqlParameterizedStringWithNulls2()
        {
            SparqlParameterizedString query = new SparqlParameterizedString();

            query.CommandText = "SELECT * WHERE { @s ?p ?o }";

            //Set a URI to a valid value
            query.SetUri("s", new Uri("http://example.org"));
            Console.WriteLine(query.ToString());
            Console.WriteLine();

            //Set the URI to a null
            Assert.Throws <ArgumentNullException>(() => query.SetUri("s", null));
        }
示例#5
0
        public void SparqlParameterizedStringShouldNotEncodeUri()
        {
            SparqlParameterizedString query = new SparqlParameterizedString("DESCRIBE @uri");

            query.SetUri("uri", new Uri("http://example.com/some@encoded/uri"));
            Assert.AreEqual("DESCRIBE <http://example.com/some@encoded/uri>", query.ToString(), "The query should contain the encoded form of the given uri");
        }
示例#6
0
        public void SparqlParameterizedStringShouldNotEncodeUri()
        {
            SparqlParameterizedString query = new SparqlParameterizedString("DESCRIBE @uri");

            query.SetUri("uri", new Uri("http://example.com/some@encoded/uri"));
            Assert.Equal("DESCRIBE <http://example.com/some@encoded/uri>", query.ToString());
        }
示例#7
0
        public void SparqlConflictingParamNames()
        {
            String baseQuery = @"SELECT * WHERE {
    ?s a @type ; a @type1 ; a @type2 .
}";
            SparqlParameterizedString query  = new SparqlParameterizedString(baseQuery);
            SparqlQueryParser         parser = new SparqlQueryParser();

            query.SetUri("type", new Uri("http://example.org/type"));

            Console.WriteLine("Only one of the type parameters should be replaced here");
            Console.WriteLine(query.ToString());
            Console.WriteLine();

            query.SetUri("type1", new Uri("http://example.org/anotherType"));
            query.SetUri("type2", new Uri("http://example.org/yetAnotherType"));

            Console.WriteLine("Now all the type parameters should have been replaced");
            Console.WriteLine(query.ToString());
            Console.WriteLine();

            try
            {
                query.SetUri("not valid", new Uri("http://example.org/invalidParam"));
                Assert.Fail("Should reject bad parameter names");
            }
            catch (FormatException ex)
            {
                //This is ok
                Console.WriteLine("Bad Parameter Name was rejected - " + ex.Message);
            }

            try
            {
                query.SetUri("is_valid", new Uri("http://example.org/validParam"));
            }
            catch (FormatException)
            {
                Assert.Fail("Should have been a valid parameter name");
            }
        }
示例#8
0
        public void SparqlParameterizedString()
        {
            String test = @"INSERT DATA { GRAPH @graph {
                            <http://uri> <http://uri> <http://uri>
                            }}";
            SparqlParameterizedString cmdString = new SparqlParameterizedString(test);

            cmdString.SetUri("graph", new Uri("http://example.org/graph"));

            SparqlUpdateParser     parser = new SparqlUpdateParser();
            SparqlUpdateCommandSet cmds   = parser.ParseFromString(cmdString);

            cmds.ToString();
        }
示例#9
0
        public void SparqlParsingHandlesDollarSignInUriParameter1()
        {
            const string queryString       = @"SELECT ?p ?o WHERE { @subject ?p ?o . }";
            const string expectedCondition = @"<http://dbpedia.org/resource/$_(film)> ?p ?o";
            var          uri = new Uri("http://dbpedia.org/resource/$_(film)");

            var parametrizedQueryString = new SparqlParameterizedString(queryString);

            parametrizedQueryString.SetUri("subject", uri);
            var sparqlQuery = new SparqlQueryParser().ParseFromString(parametrizedQueryString);

            Console.WriteLine(sparqlQuery.ToString());

            Assert.That(sparqlQuery.ToString(), Contains.Substring(expectedCondition));
        }
示例#10
0
        public void SparqlParameterizedStringWithNulls()
        {
            SparqlParameterizedString query = new SparqlParameterizedString();

            query.CommandText = "SELECT * WHERE { @s ?p ?o }";

            //Set a URI to a valid value
            query.SetUri("s", new Uri("http://example.org"));
            Console.WriteLine(query.ToString());
            Console.WriteLine();

            //Set the parameter to a null
            query.SetParameter("s", null);
            Console.WriteLine(query.ToString());
        }
        private IEnumerable<SparqlUpdateCommand> GetDeleteDataCommands(IEnumerable<RomanticWeb.Model.EntityQuad> quads)
        {
            foreach (var quad in quads)
            {
                SparqlParameterizedString insert = new SparqlParameterizedString(DeleteDataCommandText);
                insert.SetParameter("subject", quad.Subject.UnWrapNode(_nodeFactory));
                insert.SetParameter("predicate", quad.Predicate.UnWrapNode(_nodeFactory));
                insert.SetParameter("object", quad.Object.UnWrapNode(_nodeFactory));
                insert.SetUri("graph", quad.Graph.UnWrapGraphUri());

                foreach (var command in _parser.ParseFromString(insert).Commands)
                {
                    yield return command;
                }
            }
        }
示例#12
0
        private void ExpandByDataset(UriToExpand u, ExpansionContext context, ExpansionDataset dataset)
        {
            if (u.Depth == context.Profile.MaxExpansionDepth) return;
            if (dataset.Ignore) return;

            foreach (Uri endpoint in dataset.SparqlEndpoints)
            {
                Thread.Sleep(HttpRequestInterval);
                SparqlRemoteEndpoint sparqlEndpoint = new SparqlRemoteEndpoint(endpoint);
                try
                {
                    SparqlParameterizedString queryString = new SparqlParameterizedString("DESCRIBE @uri");
                    queryString.SetUri("uri", u.Uri);
                    Object temp = sparqlEndpoint.QueryWithResultGraph(queryString.ToString());
                    if (temp is Graph)
                    {
                        Graph g = (Graph)temp;
                        this.ExpandGraph(u, g, context);
                    }
                }
                catch (RdfException rdfEx)
                {
                    this.DebugErrors("Error: Tried to DESCRIBE <" + u.Uri.ToString() + "> against the SPARQL Endpoint <" + endpoint.ToString() + "> but an error occurred:", rdfEx);
                }
                catch (WebException webEx)
                {
                    this.DebugErrors("Error: Tried to DESCRIBE <" + u.Uri.ToString() + "> against the SPARQL Endpoint <" + endpoint.ToString() + "> but an error occurred:", webEx);
                }
            }

            foreach (Uri endpoint in dataset.UriLookupEndpoints)
            {
                this.ExpandByUriLookup(u, context, endpoint);
            }

            foreach (Uri endpoint in dataset.UriDiscoveryEndpoints)
            {
                this.ExpandByUriDiscovery(u, context, endpoint);
            }
        }
        /// <summary>
        /// Determines whether a Graph with the given URI exists
        /// </summary>
        /// <param name="graphUri">Graph URI</param>
        /// <returns></returns>
        protected override bool HasGraph(Uri graphUri)
        {
            //Generate an ASK query based on the Graph URI
            SparqlParameterizedString ask = new SparqlParameterizedString();
            if (graphUri != null)
            {
                ask.CommandText = "ASK WHERE { GRAPH @graph { ?s ?p ?o . } }";
                ask.SetUri("graph", graphUri);
            }
            else
            {
                ask.CommandText = "ASK WHERE { ?s ?p ?o }";
            }
            SparqlQueryParser parser = new SparqlQueryParser();
            SparqlQuery q = parser.ParseFromString(ask);

            Object results = this._queryProcessor.ProcessQuery(q);
            if (results is SparqlResultSet)
            {
                return ((SparqlResultSet)results).Result;
            }
            else
            {
                throw new SparqlHttpProtocolException("Failed to retrieve a Boolean Result since the query processor did not return a valid SPARQL Result Set as expected");
            }
        }
        /// <summary>
        /// Retrieves the Graph with the given URI
        /// </summary>
        /// <param name="graphUri">Graph URI</param>
        /// <returns></returns>
        protected override IGraph GetGraph(Uri graphUri)
        {
            //Generate a CONSTRUCT query based on the Graph URI
            SparqlParameterizedString construct = new SparqlParameterizedString();
            if (graphUri != null)
            {
                construct.CommandText = "CONSTRUCT { ?s ?p ?o . } WHERE { GRAPH @graph { ?s ?p ?o . } }";
                construct.SetUri("graph", graphUri);
            }
            else
            {
                construct.CommandText = "CONSTRUCT { ?s ?p ?o . } WHERE { ?s ?p ?o }";
            }
            SparqlQueryParser parser = new SparqlQueryParser();
            SparqlQuery q = parser.ParseFromString(construct);

            Object results = this._queryProcessor.ProcessQuery(q);
            if (results is IGraph)
            {
                return (IGraph)results;
            }
            else
            {
                throw new SparqlHttpProtocolException("Failed to retrieve a Graph since the query processor did not return a valid Graph as expected");
            }
        }
        /// <summary>
        /// Processes a DELETE operation
        /// </summary>
        /// <param name="context">HTTP Context</param>
        public override void ProcessDelete(HttpContext context)
        {
            //Get the Graph URI of the Graph to delete
            Uri graphUri = this.ResolveGraphUri(context);

            //Must return a 404 if the Graph doesn't exist
            if (!this.HasGraph(graphUri))
            {
                context.Response.StatusCode = (int)HttpStatusCode.NotFound;
                return;
            }

            //Generate a DROP GRAPH command based on this
            SparqlParameterizedString drop = new SparqlParameterizedString("DROP ");
            if (graphUri != null)
            {
                drop.CommandText += "GRAPH @graph";
                drop.SetUri("graph", graphUri);
            }
            else
            {
                drop.CommandText += "DEFAULT";
            }
            SparqlUpdateCommandSet dropCmd = this._parser.ParseFromString(drop);
            this._updateProcessor.ProcessCommandSet(dropCmd);
            this._updateProcessor.Flush();
        }
        private IEnumerable<SparqlUpdateCommand> GetInsertCommands(Uri entityGraphUri, EntityId entityId, string entityPatterns, IDictionary<string, INode> variables, bool withDelete = true)
        {
            SparqlParameterizedString modify = new SparqlParameterizedString(
                (withDelete ? DeleteEntityGraphCommandText : System.String.Empty) +
                (entityId is BlankId ? InsertBlankNodeCommandText : InsertEntityCommandText).Replace("@subject @predicate @object . ", entityPatterns));
            modify.SetUri("metaGraph", _metaGraphUri);
            modify.SetUri("graph", entityGraphUri);
            if (!(entityId is BlankId))
            {
                modify.SetUri("entityId", entityId.Uri);
            }

            foreach (var variable in variables)
            {
                modify.SetParameter(variable.Key, variable.Value);
            }

            foreach (var command in _parser.ParseFromString(modify).Commands)
            {
                yield return command;
            }
        }
        static XElement CreateNuspecMetadataFrameworkAssembly(TripleStore store, Uri packageUri)
        {
            SparqlParameterizedString sparql = new SparqlParameterizedString();
            sparql.CommandText = Utils.GetResource("sparql.SelectPackageFrameworkAssembly.rq");
            sparql.SetUri("package", packageUri);
            SparqlResultSet packageFrameworkAssembly = SparqlHelpers.Select(store, sparql.ToString());

            if (packageFrameworkAssembly.Count > 0)
            {
                XElement frameworkAssemblies = new XElement(nuget.GetName("frameworkAssemblies"));

                foreach (SparqlResult row in packageFrameworkAssembly)
                {
                    string targetFramework = row["targetFramework"].ToString();
                    string assembly = row["assembly"].ToString();

                    XElement frameworkAssembly = new XElement(nuget.GetName("frameworkAssembly"));

                    frameworkAssembly.Add(new XAttribute("assemblyName", assembly));
                    frameworkAssembly.Add(new XAttribute("targetFramework", targetFramework));

                    frameworkAssemblies.Add(frameworkAssembly);
                }

                return frameworkAssemblies;
            }

            return null;
        }
        static XElement CreateNuspecMetadataDependencies(TripleStore store, Uri packageUri)
        {
            SparqlParameterizedString sparql = new SparqlParameterizedString();
            sparql.CommandText = Utils.GetResource("sparql.SelectPackageDependencies.rq");
            sparql.SetUri("package", packageUri);
            SparqlResultSet packageDependencies = SparqlHelpers.Select(store, sparql.ToString());

            if (packageDependencies.Count > 0)
            {
                XElement dependencies = new XElement(nuget.GetName("dependencies"));

                IDictionary<string, IDictionary<string, string>> groups = new Dictionary<string, IDictionary<string, string>>();

                foreach (SparqlResult row in packageDependencies)
                {
                    string targetFramework = row["targetFramework"].ToString();

                    IDictionary<string, string> group;
                    if (!groups.TryGetValue(targetFramework, out group))
                    {
                        group = new Dictionary<string, string>();
                        groups.Add(targetFramework, group);
                    }

                    string id = row["id"].ToString();

                    string range = row.HasBoundValue("range") ? row["range"].ToString() : null;

                    group.Add(id, range);
                }

                if (groups.Count == 1 && groups.First().Key == "")
                {
                    AddDependencies(dependencies, groups.First().Value);
                }
                else
                {
                    foreach (KeyValuePair<string, IDictionary<string, string>> groupsItem in groups)
                    {
                        XElement group = new XElement(nuget.GetName("group"));

                        if (groupsItem.Key != "")
                        {
                            group.Add(new XAttribute("targetFramework", groupsItem.Key));
                        }

                        AddDependencies(group, groupsItem.Value);

                        dependencies.Add(group);
                    }
                }

                return dependencies;
            }

            return null;
        }
示例#19
0
        public void SparqlConflictingParamNames()
        {
            String baseQuery = @"SELECT * WHERE {
    ?s a @type ; a @type1 ; a @type2 .
}";
            SparqlParameterizedString query = new SparqlParameterizedString(baseQuery);
            SparqlQueryParser parser = new SparqlQueryParser();

            query.SetUri("type", new Uri("http://example.org/type"));

            Console.WriteLine("Only one of the type parameters should be replaced here");
            Console.WriteLine(query.ToString());
            Console.WriteLine();

            query.SetUri("type1", new Uri("http://example.org/anotherType"));
            query.SetUri("type2", new Uri("http://example.org/yetAnotherType"));

            Console.WriteLine("Now all the type parameters should have been replaced");
            Console.WriteLine(query.ToString());
            Console.WriteLine();

            try
            {
                query.SetUri("not valid", new Uri("http://example.org/invalidParam"));
                Assert.Fail("Should reject bad parameter names");
            }
            catch (FormatException ex)
            {
                //This is ok
                Console.WriteLine("Bad Parameter Name was rejected - " + ex.Message);
            }

            try
            {
                query.SetUri("is_valid", new Uri("http://example.org/validParam"));
            }
            catch (FormatException)
            {
                Assert.Fail("Should have been a valid parameter name");
            }

        }
示例#20
0
        public void SparqlParameterizedString()
        {
            String test = @"INSERT DATA { GRAPH @graph {
                            <http://uri> <http://uri> <http://uri>
                            }}";
            SparqlParameterizedString cmdString = new SparqlParameterizedString(test);
            cmdString.SetUri("graph", new Uri("http://example.org/graph"));

            SparqlUpdateParser parser = new SparqlUpdateParser();
            SparqlUpdateCommandSet cmds = parser.ParseFromString(cmdString);
            cmds.ToString();
        }
        /// <summary>
        /// Saves a Graph into the Store (see remarks for notes on merge/overwrite behaviour)
        /// </summary>
        /// <param name="g">Graph to save</param>
        /// <remarks>
        /// <para>
        /// If the Graph has no URI then the contents will be appended to the Store's Default Graph. If the Graph has a URI then existing Graph associated with that URI will be replaced. To append to a named Graph use the <see cref="BlazegraphConnector.UpdateGraph(Uri,IEnumerable{Triple},IEnumerable{Triple})">UpdateGraph()</see> method instead
        /// </para>
        /// </remarks>
        public virtual void SaveGraph(IGraph g)
        {
            string activeTID;
            string tID = null;
            lock (transLock)
            {
                activeTID = this._activeTrans;
            }

            try
            {
                //Get a Transaction ID, if there is no active Transaction then this operation will be auto-committed
                tID = activeTID ?? this.BeginTransaction();

                Dictionary<string, string> queryParams = new Dictionary<string, string>();
                if (activeTID == null)
                {
                    queryParams.Add("timestamp", tID);
                }

                HttpWebRequest request;
                string boundary = String.Format("----------{0:N}", Guid.NewGuid());
                StringBuilder sb = new StringBuilder();

                if (g.BaseUri != null)
                {
                    SparqlParameterizedString construct = new SparqlParameterizedString();
                    construct.CommandText = "CONSTRUCT { ?s ?p ?o } WHERE { GRAPH @graph { ?s ?p ?o } }";
                    construct.SetUri("graph", g.BaseUri);
                    queryParams.Add("query", construct.ToString());

                    request = this.CreateRequest("/sparql", MimeTypesHelper.Any, "PUT", queryParams);
                    request.ContentType = MimeTypesHelper.GetDefinitionsByFileExtension(MimeTypesHelper.DefaultTriGExtension).First().MimeTypes.First();
                }
                else
                {
                    request = this.CreateRequest("/sparql?updatePost", MimeTypesHelper.Any, "POST", queryParams);
                    request.ContentType = MimeTypesHelper.FormMultipart + "; boundary=" + boundary;

                    string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\nContent-Type: {2}\r\n\r\n{3}",
                        boundary,
                        "add",
                        MimeTypesHelper.GetDefinitionsByFileExtension(MimeTypesHelper.DefaultTriGExtension).First().MimeTypes.First(),
                        "");
                    sb.Append(postData);
                }

                //Save the Data as TriG to the Request Stream
                TripleStore store = new TripleStore();
                store.Add(g);
                this._writer.Save(store, new System.IO.StringWriter(sb));

                if (g.BaseUri == null)
                {
                    string footer = "\r\n--" + boundary + "--\r\n";
                    sb.Append(footer);
                }

                using (StreamWriter writer = new StreamWriter(request.GetRequestStream(), new UTF8Encoding()))
                {
                    writer.Write(sb.ToString());
                    writer.Close();
                }

                Tools.HttpDebugRequest(request);

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    Tools.HttpDebugResponse(response);
                    //If we get here then it was OK
                    response.Close();
                }

                //Commit Transaction only if in auto-commit mode (active transaction will be null)
                if (activeTID != null) return;
                try
                {
                    this.CommitTransaction(tID);
                }
                catch (Exception ex)
                {
                    throw new RdfStorageException("Blazegraph failed to commit a Transaction", ex);
                }
            }
            catch (WebException webEx)
            {
                //Rollback Transaction only if got as far as creating a Transaction
                //and in auto-commit mode
                if (tID != null)
                {
                    if (activeTID == null)
                    {
                        try
                        {
                            this.RollbackTransaction(tID);
                        }
                        catch (Exception ex)
                        {
                            StorageHelper.HandleHttpError(webEx, "");
                            throw new RdfStorageException("Blazegraph failed to rollback a Transaction", ex);
                        }
                    }
                }

                throw StorageHelper.HandleHttpError(webEx, "saving a Graph to");
            }
        }
        protected virtual void SaveGraphAsync(bool autoCommit, IGraph g, AsyncStorageCallback callback, object state)
        {
            try
            {
                Dictionary<string, string> queryParams = new Dictionary<string, string>();

                HttpWebRequest request;
                string boundary = String.Format("----------{0:N}", Guid.NewGuid());
                StringBuilder sb = new StringBuilder();

                if (g.BaseUri != null)
                {
                    SparqlParameterizedString construct = new SparqlParameterizedString();
                    construct.CommandText = "CONSTRUCT { ?s ?p ?o } WHERE { GRAPH @graph { ?s ?p ?o } }";
                    construct.SetUri("graph", g.BaseUri);
                    queryParams.Add("query", construct.ToString());

                    request = this.CreateRequest("/sparql", MimeTypesHelper.Any, "PUT", queryParams);
                    request.ContentType = MimeTypesHelper.GetDefinitionsByFileExtension(MimeTypesHelper.DefaultTriGExtension).First().MimeTypes.First();
                }
                else
                {
                    request = this.CreateRequest("/sparql?updatePost", MimeTypesHelper.Any, "POST", queryParams);
                    request.ContentType = MimeTypesHelper.FormMultipart + "; boundary=" + boundary;

                    string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\nContent-Type: {2}\r\n\r\n{3}",
                        boundary,
                        "add",
                        MimeTypesHelper.GetDefinitionsByFileExtension(MimeTypesHelper.DefaultTriGExtension).First().MimeTypes.First(),
                        "");
                    sb.Append(postData);
                }

                //Save the Data as TriG to the Request Stream
                TripleStore store = new TripleStore();
                store.Add(g);
                this._writer.Save(store, new System.IO.StringWriter(sb));

                if (g.BaseUri == null)
                {
                    string footer = "\r\n--" + boundary + "--\r\n";
                    sb.Append(footer);
                }

                request.BeginGetRequestStream(r =>
                {
                    try
                    {
                        //Save the Data as TriG to the Request Stream
                        using (StreamWriter writer = new StreamWriter(request.EndGetRequestStream(r), new UTF8Encoding()))
                        {
                            writer.Write(sb.ToString());
                            writer.Close();
                        }

                        Tools.HttpDebugRequest(request);
                        request.BeginGetResponse(r2 =>
                        {
                            try
                            {
                                using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(r2))
                                {
                                    Tools.HttpDebugResponse(response);

                                    //If we get here then it was OK
                                    response.Close();
                                }

                                //Commit Transaction only if in auto-commit mode (active transaction will be null)
                                if (autoCommit)
                                {
                                    this.Commit((sender, args, st) =>
                                    {
                                        if (args.WasSuccessful)
                                        {
                                            callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SaveGraph, g), state);
                                        }
                                        else
                                        {
                                            callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SaveGraph, args.Error), state);
                                        }
                                    }, state);
                                }
                                else
                                {
                                    callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SaveGraph, g), state);
                                }
                            }
                            catch (WebException webEx)
                            {
                                if (autoCommit)
                                {
                                    //If something went wrong try to rollback, don't care what the rollback response is
                                    this.Rollback((sender, args, st) => { }, state);
                                }
                                callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SaveGraph, StorageHelper.HandleHttpError(webEx, "saving a Graph asynchronously to")), state);
                            }
                            catch (Exception ex)
                            {
                                if (autoCommit)
                                {
                                    //If something went wrong try to rollback, don't care what the rollback response is
                                    this.Rollback((sender, args, st) => { }, state);
                                }
                                callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SaveGraph, StorageHelper.HandleError(ex, "saving a Graph asynchronously to")), state);
                            }
                        }, state);
                    }
                    catch (WebException webEx)
                    {
                        if (autoCommit)
                        {
                            //If something went wrong try to rollback, don't care what the rollback response is
                            this.Rollback((sender, args, st) => { }, state);
                        }
                        callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SaveGraph, StorageHelper.HandleHttpError(webEx, "saving a Graph asynchronously to")), state);
                    }
                    catch (Exception ex)
                    {
                        if (autoCommit)
                        {
                            //If something went wrong try to rollback, don't care what the rollback response is
                            this.Rollback((sender, args, st) => { }, state);
                        }
                        callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SaveGraph, StorageHelper.HandleError(ex, "saving a Graph asynchronously to")), state);
                    }
                }, state);
            }
            catch (WebException webEx)
            {
                if (autoCommit)
                {
                    //If something went wrong try to rollback, don't care what the rollback response is
                    this.Rollback((sender, args, st) => { }, state);
                }
                callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SaveGraph, StorageHelper.HandleHttpError(webEx, "saving a Graph asynchronously to")), state);
            }
            catch (Exception ex)
            {
                if (autoCommit)
                {
                    //If something went wrong try to rollback, don't care what the rollback response is
                    this.Rollback((sender, args, st) => { }, state);
                }
                callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.SaveGraph, StorageHelper.HandleError(ex, "saving a Graph asynchronously to")), state);
            }
        }
        static void AddExistingItem(IDictionary<RegistrationEntryKey, RegistrationCatalogEntry> resources, TripleStore store, Uri catalogEntry)
        {
            Trace.TraceInformation("RegistrationPersistence.AddExistingItem: catalogEntry = {0}", catalogEntry);

            SparqlParameterizedString sparql = new SparqlParameterizedString();
            sparql.CommandText = Utils.GetResource("sparql.ConstructCatalogEntryGraph.rq");
            sparql.SetUri("catalogEntry", catalogEntry);

            IGraph graph = SparqlHelpers.Construct(store, sparql.ToString());

            resources.Add(RegistrationCatalogEntry.Promote(catalogEntry.AbsoluteUri, graph));
        }
        /// <summary>
        /// Processes a POST operation
        /// </summary>
        /// <param name="context">HTTP Context</param>
        public override void ProcessPost(HttpContext context)
        {
            //Get the payload assuming there is one
            IGraph g = this.ParsePayload(context);

            if (g == null)
            {
                //Q: What should the behaviour be when the payload is null for a POST?  Assuming a 200 OK response
                return;
            }

            //Get the Graph URI of the Graph to be added
            Uri graphUri = this.ResolveGraphUri(context, g);

            //First we need a 

            //Generate an INSERT DATA command for the POST
            StringBuilder insert = new StringBuilder();
            if (graphUri != null)
            {
                insert.AppendLine("INSERT DATA { GRAPH @graph {");
            }
            else
            {
                insert.AppendLine("INSERT DATA {");
            }

            TurtleFormatter formatter = new TurtleFormatter(g.NamespaceMap);
            foreach (Triple t in g.Triples)
            {
                insert.AppendLine(t.ToString(formatter));
            }

            if (graphUri != null)
            {
                insert.AppendLine("} }");
            }
            else
            {
                insert.AppendLine("}");
            }

            //Parse and evaluate the command
            SparqlParameterizedString insertCmd = new SparqlParameterizedString(insert.ToString());
            insertCmd.Namespaces = g.NamespaceMap;
            if (graphUri != null) insertCmd.SetUri("graph", graphUri);
            SparqlUpdateCommandSet cmds = this._parser.ParseFromString(insertCmd);
            this._updateProcessor.ProcessCommandSet(cmds);
            this._updateProcessor.Flush();
        }
        /// <summary>
        /// Loads a Graph from the Store
        /// </summary>
        /// <param name="g">Graph to load into</param>
        /// <param name="graphUri">Uri of the Graph to load</param>
        /// <remarks>
        /// If an empty/null Uri is specified then the Default Graph of the Store will be loaded
        /// </remarks>
        public void LoadGraph(IGraph g, string graphUri)
        {
            try
            {
                HttpWebRequest request;
                Dictionary<String, String> serviceParams = new Dictionary<string, string>();

                String tID = (this._activeTrans.Value == null) ? String.Empty : "/" + this._activeTrans.Value;
                String requestUri = this._kb + tID + "/query";
                SparqlParameterizedString construct = new SparqlParameterizedString();
                if (!graphUri.Equals(String.Empty))
                {
                    construct.CommandText = "CONSTRUCT { ?s ?p ?o } WHERE { GRAPH @graph { ?s ?p ?o } }";
                    construct.SetUri("graph", new Uri(graphUri));
                    if (g.IsEmpty) g.BaseUri = new Uri(graphUri);
                }
                else
                {
                    construct.CommandText = "CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }";
                }
                serviceParams.Add("query", construct.ToString());

                request = this.CreateRequest(requestUri, MimeTypesHelper.HttpAcceptHeader, "GET", serviceParams);

#if DEBUG
                if (Options.HttpDebugging)
                {
                    Tools.HttpDebugRequest(request);
                }
#endif

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
#if DEBUG
                    if (Options.HttpDebugging)
                    {
                        Tools.HttpDebugResponse(response);
                    }
#endif
                    IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType);
                    parser.Load(g, new StreamReader(response.GetResponseStream()));
                    response.Close();
                }
            }
            catch (WebException webEx)
            {
#if DEBUG
                if (Options.HttpDebugging)
                {
                    if (webEx.Response != null) Tools.HttpDebugResponse((HttpWebResponse)webEx.Response);
                }
#endif
                throw new RdfStorageException("A HTTP Error occurred while trying to load a Graph from the Store", webEx);
            }
        }
        /// <summary>
        /// Processes a POST operation which adds triples to a new Graph in the Store and returns the URI of the newly created Graph
        /// </summary>
        /// <param name="context">HTTP Context</param>
        /// <remarks>
        /// <para>
        /// This operation allows clients to POST data to an endpoint and have it create a Graph and assign a URI for them.
        /// </para>
        /// </remarks>
        public override void ProcessPostCreate(HttpContext context)
        {
            //Get the payload assuming there is one
            IGraph g = this.ParsePayload(context);

            //Mint a URI for the Graph
            Uri graphUri = this.MintGraphUri(context, g);

            //First generate a CREATE to ensure that the Graph exists
            //We don't do a CREATE SILENT as this operation is supposed to generate a new Graph URI
            //so if MintGraphUri() fails to deliver a unused Graph URI then the operation should fail
            StringBuilder insert = new StringBuilder();
            insert.AppendLine("CREATE GRAPH @graph ;");

            //Then Generate an INSERT DATA command for the actual POST
            //Note that if the payload is empty this still has the effect of creating a Graph
            if (g != null)
            {
                insert.AppendLine("INSERT DATA { GRAPH @graph {");
                TurtleFormatter formatter = new TurtleFormatter(g.NamespaceMap);
                foreach (Triple t in g.Triples)
                {
                    insert.AppendLine(t.ToString(formatter));
                }
                insert.AppendLine("} }");
            }

            //Parse and evaluate the command
            SparqlParameterizedString insertCmd = new SparqlParameterizedString(insert.ToString());
            insertCmd.Namespaces = g.NamespaceMap;
            insertCmd.SetUri("graph", graphUri);
            SparqlUpdateCommandSet cmds = this._parser.ParseFromString(insertCmd);
            this._updateProcessor.ProcessCommandSet(cmds);
            this._updateProcessor.Flush();

            //Finally return a 201 Created and a Location header with the new Graph URI
            context.Response.StatusCode = (int)HttpStatusCode.Created;
            try
            {
                context.Response.Headers.Add("Location", graphUri.ToString());
            }
            catch (PlatformNotSupportedException)
            {
                context.Response.AddHeader("Location", graphUri.ToString());
            }
        }
        static XElement CreateNuspecMetadata(TripleStore store, Uri packageUri)
        {
            SparqlParameterizedString sparql = new SparqlParameterizedString();
            sparql.CommandText = Utils.GetResource("sparql.SelectPackageDetails.rq");
            sparql.SetUri("package", packageUri);
            SparqlResult packageInfo = SparqlHelpers.Select(store, sparql.ToString()).FirstOrDefault();

            if (packageInfo == null)
            {
                throw new ArgumentException(string.Format("no package details for {0}", packageUri));
            }

            XElement metadata = new XElement(nuget.GetName("metadata"));

            metadata.Add(new XElement(nuget.GetName("id"), packageInfo["id"].ToString()));
            metadata.Add(new XElement(nuget.GetName("version"), packageInfo["version"].ToString()));

            //  in the nuspec the published and owners fields are not present and ignored respectfully

            //if (packageInfo.HasBoundValue("published"))
            //{
            //    DateTime val = DateTime.Parse(((ILiteralNode)packageInfo["published"]).Value);
            //    metadata.Add(new XElement(nuget.GetName("published"), val.ToUniversalTime().ToString("O")));
            //}

            if (packageInfo.HasBoundValue("authors"))
            {
                metadata.Add(new XElement(nuget.GetName("authors"), packageInfo["authors"].ToString()));
            }

            if (packageInfo.HasBoundValue("description"))
            {
                metadata.Add(new XElement(nuget.GetName("description"), packageInfo["description"].ToString()));
            }

            if (packageInfo.HasBoundValue("summary"))
            {
                metadata.Add(new XElement(nuget.GetName("summary"), packageInfo["summary"].ToString()));
            }

            if (packageInfo.HasBoundValue("language"))
            {
                metadata.Add(new XElement(nuget.GetName("language"), packageInfo["language"].ToString()));
            }

            if (packageInfo.HasBoundValue("title"))
            {
                metadata.Add(new XElement(nuget.GetName("title"), packageInfo["title"].ToString()));
            }

            if (packageInfo.HasBoundValue("targetFramework"))
            {
                metadata.Add(new XElement(nuget.GetName("targetFramework"), packageInfo["targetFramework"].ToString()));
            }

            if (packageInfo.HasBoundValue("requireLicenseAcceptance"))
            {
                bool val = bool.Parse(((ILiteralNode)packageInfo["requireLicenseAcceptance"]).Value);
                metadata.Add(new XElement(nuget.GetName("requireLicenseAcceptance"), val));
            }

            if (packageInfo.HasBoundValue("licenseUrl"))
            {
                metadata.Add(new XElement(nuget.GetName("licenseUrl"), packageInfo["licenseUrl"].ToString()));
            }

            if (packageInfo.HasBoundValue("iconUrl"))
            {
                metadata.Add(new XElement(nuget.GetName("iconUrl"), packageInfo["iconUrl"].ToString()));
            }

            if (packageInfo.HasBoundValue("projectUrl"))
            {
                metadata.Add(new XElement(nuget.GetName("projectUrl"), packageInfo["projectUrl"].ToString()));
            }

            if (packageInfo.HasBoundValue("releaseNotes"))
            {
                metadata.Add(new XElement(nuget.GetName("releaseNotes"), packageInfo["releaseNotes"].ToString()));
            }

            if (packageInfo.HasBoundValue("copyright"))
            {
                metadata.Add(new XElement(nuget.GetName("copyright"), packageInfo["copyright"].ToString()));
            }

            if (packageInfo.HasBoundValue("minClientVersion"))
            {
                metadata.Add(new XAttribute("minClientVersion", packageInfo["minClientVersion"].ToString()));
            }

            if (packageInfo.HasBoundValue("developmentDependency"))
            {
                bool val = bool.Parse(((ILiteralNode)packageInfo["developmentDependency"]).Value);
                metadata.Add(new XElement(nuget.GetName("developmentDependency"), val));
            }

            return metadata;
        }
        /// <summary>
        /// Processes a PUT operation
        /// </summary>
        /// <param name="context">HTTP Context</param>
        public override void ProcessPut(HttpContext context)
        {
            //Get the payload assuming there is one
            IGraph g = this.ParsePayload(context);

            //Get the Graph URI of the Graph to be added
            Uri graphUri = this.ResolveGraphUri(context, g);

            //Determine whether the Graph already exists or not, if it doesn't then we have to send a 201 Response
            bool created = false;
            try
            {
                SparqlQueryParser parser = new SparqlQueryParser();
                SparqlParameterizedString graphExistsQuery = new SparqlParameterizedString();
                graphExistsQuery.CommandText = "ASK WHERE { GRAPH @graph { } }";
                graphExistsQuery.SetUri("graph", graphUri);

                Object temp = this._queryProcessor.ProcessQuery(parser.ParseFromString(graphExistsQuery));
                if (temp is SparqlResultSet)
                {
                    created = !((SparqlResultSet)temp).Result;
                }
            }
            catch
            {
                //If any error occurs assume the Graph doesn't exist and so we'll return a 201 created
                created = true;
            }            

            //Generate a set of commands based upon this
            StringBuilder cmdSequence = new StringBuilder();
            if (graphUri != null)
            {
                cmdSequence.AppendLine("DROP SILENT GRAPH @graph ;");
                cmdSequence.Append("CREATE SILENT GRAPH @graph");
            }
            else
            {
                cmdSequence.Append("DROP SILENT DEFAULT");
            }
            if (g != null)
            {
                cmdSequence.AppendLine(" ;");
                if (graphUri != null)
                {
                    cmdSequence.AppendLine("INSERT DATA { GRAPH @graph {");
                }
                else
                {
                    cmdSequence.AppendLine("INSERT DATA { ");
                }

                TurtleFormatter formatter = new TurtleFormatter(g.NamespaceMap);
                foreach (Triple t in g.Triples)
                {
                    cmdSequence.AppendLine(t.ToString(formatter));
                }

                if (graphUri != null)
                {
                    cmdSequence.AppendLine("} }");
                }
                else
                {
                    cmdSequence.AppendLine("}");
                }
            }

            SparqlParameterizedString put = new SparqlParameterizedString(cmdSequence.ToString());
            put.Namespaces = g.NamespaceMap;
            if (graphUri != null) put.SetUri("graph", graphUri);
            SparqlUpdateCommandSet putCmds = this._parser.ParseFromString(put);
            this._updateProcessor.ProcessCommandSet(putCmds);
            this._updateProcessor.Flush();

            //Return a 201 if required, otherwise the default behaviour of returning a 200 will occur automatically
            if (created)
            {
                context.Response.StatusCode = (int)HttpStatusCode.Created;
            }
        }
        public override IGraph CreatePageContent(CatalogContext context)
        {
            try
            {
                IGraph content;

                using (TripleStore store = new TripleStore())
                {
                    store.Add(_catalogItem, true);

                    SparqlParameterizedString sparql = new SparqlParameterizedString();
                    sparql.CommandText = Utils.GetResource("sparql.ConstructPackagePageContentGraph.rq");

                    sparql.SetUri("package", GetItemAddress());
                    sparql.SetUri("catalogPackage", _catalogUri);
                    sparql.SetUri("baseAddress", BaseAddress);
                    sparql.SetUri("packageContent", GetPackageContentAddress());
                    sparql.SetUri("registrationBaseAddress", _registrationBaseAddress);

                    content = SparqlHelpers.Construct(store, sparql.ToString());
                }

                return content;
            }
            catch (Exception e)
            {
                throw new Exception(string.Format("Exception processing catalog item {0}", _catalogUri), e);
            }
        }
        /// <summary>
        /// Loads a Graph from the Store asynchronously
        /// </summary>
        /// <param name="handler">Handler to load with</param>
        /// <param name="graphUri">URI of the Graph to load</param>
        /// <param name="callback">Callback</param>
        /// <param name="state">State to pass to the callback</param>
        public override void LoadGraph(IRdfHandler handler, string graphUri, AsyncStorageCallback callback, object state)
        {
            try
            {
                HttpWebRequest request;
                Dictionary<String, String> serviceParams = new Dictionary<string, string>();
                Uri baseUri = null;

                SparqlParameterizedString construct = new SparqlParameterizedString();
                if (!graphUri.Equals(string.Empty))
                {
                    construct.CommandText = "CONSTRUCT { ?s ?p ?o } WHERE { GRAPH @graph { ?s ?p ?o } }";
                    baseUri = UriFactory.Create(graphUri);
                    construct.SetUri("graph", baseUri);
                }
                else
                {
                    construct.CommandText = "CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }";
                }
                serviceParams.Add("query", construct.ToString());

                request = this.CreateRequest("/sparql", MimeTypesHelper.HttpAcceptHeader, "GET", serviceParams);

                Tools.HttpDebugRequest(request);

                request.BeginGetResponse(r =>
                {
                    try
                    {
                        using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(r))
                        {
                            Tools.HttpDebugResponse(response);

                            IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType);
                            parser.Load(handler, new StreamReader(response.GetResponseStream()));
                            if (baseUri != null)
                            {
                                handler.StartRdf();
                                handler.HandleBaseUri(baseUri);
                                handler.EndRdf(true);
                            }
                            response.Close();
                        }

                        callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.LoadWithHandler, handler), state);
                    }
                    catch (WebException webEx)
                    {
                        callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.LoadWithHandler, StorageHelper.HandleHttpError(webEx, "loading a Graph from")), state);
                    }
                    catch (Exception ex)
                    {
                        callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.LoadWithHandler, StorageHelper.HandleError(ex, "loading a Graph from")), state);
                    }
                }, state);
            }
            catch (WebException webEx)
            {
                callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.LoadWithHandler, StorageHelper.HandleHttpError(webEx, "loading a Graph from")), state);
            }
            catch (Exception ex)
            {
                callback(this, new AsyncStorageCallbackArgs(AsyncStorageOperation.LoadWithHandler, StorageHelper.HandleError(ex, "loading a Graph from")), state);
            }
        }
        /// <summary>
        /// Determines whether a Graph with the given URI exists
        /// </summary>
        /// <param name="graphUri">Graph URI</param>
        /// <returns></returns>
        protected override bool HasGraph(Uri graphUri)
        {
            if (this._manager is IQueryableGenericIOManager)
            {
                //Generate an ASK query based on this
                SparqlParameterizedString ask = new SparqlParameterizedString();
                if (graphUri != null)
                {
                    ask.CommandText = "ASK WHERE { GRAPH @graph { ?s ?p ?o . } }";
                    ask.SetUri("graph", graphUri);
                }
                else
                {
                    ask.CommandText = "ASK WHERE { ?s ?p ?o }";
                }

                Object results = ((IQueryableGenericIOManager)this._manager).Query(ask.ToString());
                if (results is SparqlResultSet)
                {
                    return ((SparqlResultSet)results).Result;
                }
                else
                {
                    throw new SparqlHttpProtocolException("Failed to retrieve a Boolean Result since the query processor did not return a valid SPARQL Result Set as expected");
                }
            }
            else
            {
                IGraph g = this.GetGraph(graphUri);
                return !g.IsEmpty;
            }
        }
        static XElement CreateNuspecMetadataTags(TripleStore store, Uri packageUri)
        {
            SparqlParameterizedString sparql = new SparqlParameterizedString();
            sparql.CommandText = Utils.GetResource("sparql.SelectPackageTags.rq");
            sparql.SetUri("package", packageUri);
            SparqlResultSet packageTags = SparqlHelpers.Select(store, sparql.ToString());

            StringBuilder sb = new StringBuilder();

            foreach (SparqlResult row in packageTags)
            {
                sb.Append(row["tag"].ToString());
                sb.Append(' ');
            }

            string tags = sb.ToString().Trim(' ');

            if (tags.Length > 0)
            {
                return new XElement(nuget.GetName("tags"), tags);
            }

            return null;
        }