Ejemplo n.º 1
0
        /// <summary>
        /// Makes a SPARQL Query against the Knowledge Base
        /// </summary>
        /// <param name="sparqlQuery">SPARQL Query</param>
        /// <param name="graphCallback">Callback to invoke for queries that return a Graph</param>
        /// <param name="resultsCallback">Callback to invoke for queries that return a Result Set</param>
        /// <param name="state">State to pass to whichever callback function is invoked</param>
        /// <remarks>
        /// If the operation succeeds the callback will be invoked normally, if there is an error the callback will be invoked with a instance of <see cref="AsyncError"/> passed as the state which provides access to the error message and the original state passed in.
        /// </remarks>
        public void Query(String sparqlQuery, GraphCallback graphCallback, SparqlResultsCallback resultsCallback, Object state)
        {
            Graph           g       = new Graph();
            SparqlResultSet results = new SparqlResultSet();

            this.Query(new GraphHandler(g), new ResultSetHandler(results), sparqlQuery, (gh, rh, s) =>
            {
                if (s is AsyncError)
                {
                    if (graphCallback != null)
                    {
                        graphCallback(null, s);
                    }
                    if (resultsCallback != null)
                    {
                        resultsCallback(null, s);
                    }
                }
                else
                {
                    if (results.ResultsType != SparqlResultsType.Unknown)
                    {
                        resultsCallback(results, state);
                    }
                    else
                    {
                        graphCallback(g, state);
                    }
                }
            }, state);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Processes a SPARQL Query asynchronously invoking the relevant callback when the query completes.
        /// </summary>
        /// <param name="query">SPARQL QUery.</param>
        /// <param name="rdfCallback">Callback for queries that return a Graph.</param>
        /// <param name="resultsCallback">Callback for queries that return a Result Set.</param>
        /// <param name="state">State to pass to the callback.</param>
        /// <remarks>
        /// In the event of a success the appropriate callback will be invoked, if there is an error both callbacks will be invoked and passed an instance of <see cref="AsyncError"/> which contains details of the error and the original state information passed in.
        /// </remarks>
        public void ProcessQuery(SparqlQuery query, GraphCallback rdfCallback, SparqlResultsCallback resultsCallback, object state)
        {
            var resultGraph = new Graph();
            var resultSet   = new SparqlResultSet();

            Task.Factory.StartNew(() =>
                                  ProcessQuery(new GraphHandler(resultGraph), new ResultSetHandler(resultSet), query)).ContinueWith(
                antecedent =>
            {
                if (antecedent.Exception != null)
                {
                    var innerException = antecedent.Exception.InnerExceptions[0];
                    var queryException = innerException as RdfQueryException ??
                                         new RdfQueryException(
                        "Unexpected error while making an asynchronous query, see inner exception for details",
                        innerException);
                    rdfCallback?.Invoke(null, new AsyncError(queryException, state));
                    resultsCallback?.Invoke(null, new AsyncError(queryException, state));
                }
                else if (resultSet.ResultsType != SparqlResultsType.Unknown)
                {
                    resultsCallback?.Invoke(resultSet, state);
                }
                else
                {
                    rdfCallback?.Invoke(resultGraph, state);
                }
            });
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Processes a SPARQL Query asynchronously invoking the relevant callback when the query completes
        /// </summary>
        /// <param name="query">SPARQL QUery</param>
        /// <param name="rdfCallback">Callback for queries that return a Graph</param>
        /// <param name="resultsCallback">Callback for queries that return a Result Set</param>
        /// <param name="state">State to pass to the callback</param>
        /// <remarks>
        /// In the event of a success the appropriate callback will be invoked, if there is an error both callbacks will be invoked and passed an instance of <see cref="AsyncError"/> which contains details of the error and the original state information passed in.
        /// </remarks>
        public void ProcessQuery(SparqlQuery query, GraphCallback rdfCallback, SparqlResultsCallback resultsCallback, Object state)
        {
            query.QueryExecutionTime = null;
            DateTime start = DateTime.Now;

            try
            {
                switch (query.QueryType)
                {
                case SparqlQueryType.Ask:
                case SparqlQueryType.Select:
                case SparqlQueryType.SelectAll:
                case SparqlQueryType.SelectAllDistinct:
                case SparqlQueryType.SelectAllReduced:
                case SparqlQueryType.SelectDistinct:
                case SparqlQueryType.SelectReduced:
                    _endpoint.QueryWithResultSet(_formatter.Format(query), resultsCallback, state);
                    break;

                case SparqlQueryType.Construct:
                case SparqlQueryType.Describe:
                case SparqlQueryType.DescribeAll:
                    _endpoint.QueryWithResultGraph(_formatter.Format(query), rdfCallback, state);
                    break;

                default:
                    throw new RdfQueryException("Unable to execute an unknown query type against a Remote Endpoint");
                }
            }
            finally
            {
                TimeSpan elapsed = (DateTime.Now - start);
                query.QueryExecutionTime = elapsed;
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Gets the Raw Predictions Graph from the Knowledge Base
        /// </summary>
        /// <param name="individual">QName of an Individual</param>
        /// <param name="property">QName of a Property</param>
        /// <param name="callback">Callback to invoke when the operation completes</param>
        /// <param name="state">State to pass to the callback</param>
        public void PredictRaw(String individual, String property, GraphCallback callback, Object state)
        {
            String requestUri = this._predictUri + individual + "/" + property;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);

            request.Method = this.Endpoint.HttpMethods.First();
            request.Accept = MimeTypesHelper.CustomHttpAcceptHeader(this.MimeTypes.Where(t => !t.Equals("text/json")), MimeTypesHelper.SupportedRdfMimeTypes);

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

            request.BeginGetResponse(result =>
            {
                using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result))
                {
#if DEBUG
                    if (Options.HttpDebugging)
                    {
                        Tools.HttpDebugResponse(response);
                    }
#endif
                    IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType);
                    Graph g           = new Graph();
                    parser.Load(g, new StreamReader(response.GetResponseStream()));

                    response.Close();
                    callback(g, state);
                }
            }, null);
        }
Ejemplo n.º 5
0
        public async Task <ProfileResponse> GetProfile()
        {
            taskCompletion = new TaskCompletionSource <GraphResponse>();
            ProfileResponse profileResponse = null;
            GraphCallback   graphCallback   = new GraphCallback();

            graphCallback.RequestCompleted += GraphCallback_RequestCompleted;

            var graphRequest = new GraphRequest(
                AccessToken.CurrentAccessToken,
                "me",
                null,
                HttpMethod.Get,
                graphCallback
                );

            graphRequest.ExecuteAsync();

            var graphResponse = await taskCompletion.Task;

            profileResponse = Newtonsoft.Json.JsonConvert.DeserializeObject
                              <ProfileResponse>(graphResponse.RawResponse);

            return(profileResponse);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Gets the Graph which comprises the class hierarchy and individuals of those classes
        /// </summary>
        /// <param name="callback">Callback to invoke when the operation completes</param>
        /// <param name="state">State to pass to the callback</param>
        public void Realize(GraphCallback callback, Object state)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(this.Endpoint.Uri);

            request.Method = this.Endpoint.HttpMethods.First();
            request.Accept = MimeTypesHelper.CustomHttpAcceptHeader(this.MimeTypes, MimeTypesHelper.SupportedRdfMimeTypes);

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

            request.BeginGetResponse(result =>
            {
                using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result))
                {
#if DEBUG
                    if (Options.HttpDebugging)
                    {
                        Tools.HttpDebugResponse(response);
                    }
#endif
                    IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType);
                    Graph g           = new Graph();
                    parser.Load(g, new StreamReader(response.GetResponseStream()));

                    response.Close();
                    callback(g, state);
                }
            }, null);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Gets the raw Similarity Graph for the Knowledge Base
        /// </summary>
        /// <param name="number">Number of Similar Individuals</param>
        /// <param name="individual">QName of a Individual to find Similar Individuals to</param>
        /// <param name="callback">Callback to invoke when the operation completes</param>
        /// <param name="state">State to pass to the callback</param>
        public void SimilarityRaw(int number, String individual, GraphCallback callback, Object state)
        {
            if (number < 1)
            {
                throw new RdfReasoningException("Pellet Server requires the number of Similar Individuals to be at least 1");
            }

            String requestUri = this._similarityUri + number + "/" + individual;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);

            request.Method = this.Endpoint.HttpMethods.First();
            request.Accept = MimeTypesHelper.CustomHttpAcceptHeader(this.MimeTypes.Where(t => !t.Equals("text/json")), MimeTypesHelper.SupportedRdfMimeTypes);

            Tools.HttpDebugRequest(request);

            request.BeginGetResponse(result =>
            {
                using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result))
                {
                    Tools.HttpDebugResponse(response);
                    IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType);
                    Graph g           = new Graph();
                    parser.Load(g, new StreamReader(response.GetResponseStream()));

                    response.Close();
                    callback(g, state);
                }
            }, null);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Gets the raw Similarity Graph for the Knowledge Base
        /// </summary>
        /// <param name="number">Number of Similar Individuals</param>
        /// <param name="individual">QName of a Individual to find Similar Individuals to</param>
        /// <param name="callback">Callback to invoke when the operation completes</param>
        /// <param name="state">State to pass to the callback</param>
        /// <remarks>
        /// If the operation succeeds the callback will be invoked normally, if there is an error the callback will be invoked with a instance of <see cref="AsyncError"/> passed as the state which provides access to the error message and the original state passed in.
        /// </remarks>
        public void SimilarityRaw(int number, String individual, GraphCallback callback, Object state)
        {
            if (number < 1)
            {
                throw new RdfReasoningException("Pellet Server requires the number of Similar Individuals to be at least 1");
            }

            String requestUri = _similarityUri + number + "/" + individual;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);

            request.Method = Endpoint.HttpMethods.First();
            request.Accept = MimeTypesHelper.CustomHttpAcceptHeader(MimeTypes.Where(t => !t.Equals("text/json")), MimeTypesHelper.SupportedRdfMimeTypes);

            Tools.HttpDebugRequest(request);

            try
            {
                request.BeginGetResponse(result =>
                {
                    try
                    {
                        using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result))
                        {
                            Tools.HttpDebugResponse(response);
                            IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType);
                            Graph g           = new Graph();
                            parser.Load(g, new StreamReader(response.GetResponseStream()));

                            response.Close();
                            callback(g, state);
                        }
                    }
                    catch (WebException webEx)
                    {
                        if (webEx.Response != null)
                        {
                            Tools.HttpDebugResponse((HttpWebResponse)webEx.Response);
                        }
                        callback(null, new AsyncError(new RdfReasoningException("A HTTP error occurred while communicating with the Pellet Server, see inner exception for details", webEx), state));
                    }
                    catch (Exception ex)
                    {
                        callback(null, new AsyncError(new RdfReasoningException("An unexpected error occurred while communicating with the Pellet Server, see inner exception for details", ex), state));
                    }
                }, null);
            }
            catch (WebException webEx)
            {
                if (webEx.Response != null)
                {
                    Tools.HttpDebugResponse((HttpWebResponse)webEx.Response);
                }
                callback(null, new AsyncError(new RdfReasoningException("A HTTP error occurred while communicating with the Pellet Server, see inner exception for details", webEx), state));
            }
            catch (Exception ex)
            {
                callback(null, new AsyncError(new RdfReasoningException("An unexpected error occurred while communicating with the Pellet Server, see inner exception for details", ex), state));
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Gets a Graph explaining why a Class is unsatisfiable
        /// </summary>
        /// <param name="cls">Class</param>
        /// <param name="callback">Callback to invoke when the operation completes</param>
        /// <param name="state">State to pass to the callback</param>
        /// <remarks>
        /// If the operation succeeds the callback will be invoked normally, if there is an error the callback will be invoked with a instance of <see cref="AsyncError"/> passed as the state which provides access to the error message and the original state passed in.
        /// </remarks>
        public void ExplainUnsatisfiable(INode cls, GraphCallback callback, Object state)
        {
            this._baseQuery.SetParameter("s", cls);
            this._baseQuery.SetUri("p", UriFactory.Create(NamespaceMapper.RDFS + "subClassOf"));
            this._baseQuery.SetUri("o", UriFactory.Create(OwlHelper.OwlNothing));

            base.Explain(this._baseQuery.ToString(), callback, state);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Gets a Graph explaining why an Instance is of the given Class
        /// </summary>
        /// <param name="instance">Instance</param>
        /// <param name="cls">Class</param>
        /// <param name="callback">Callback to invoke when the operation completes</param>
        /// <param name="state">State to pass to the callback</param>
        /// <remarks>
        /// If the operation succeeds the callback will be invoked normally, if there is an error the callback will be invoked with a instance of <see cref="AsyncError"/> passed as the state which provides access to the error message and the original state passed in.
        /// </remarks>
        public void ExplainInstance(INode instance, INode cls, GraphCallback callback, Object state)
        {
            this._baseQuery.SetParameter("s", instance);
            this._baseQuery.SetUri("p", UriFactory.Create(RdfSpecsHelper.RdfType));
            this._baseQuery.SetParameter("o", cls);

            base.Explain(this._baseQuery.ToString(), callback, state);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Gets a Graph explaining why the given Class is a subclass of the given Super Class
        /// </summary>
        /// <param name="subclass">Class</param>
        /// <param name="superclass">Super Class</param>
        /// <param name="callback">Callback to invoke when the operation completes</param>
        /// <param name="state">State to pass to the callback</param>
        /// <remarks>
        /// If the operation succeeds the callback will be invoked normally, if there is an error the callback will be invoked with a instance of <see cref="AsyncError"/> passed as the state which provides access to the error message and the original state passed in.
        /// </remarks>
        public void ExplainSubclass(INode subclass, INode superclass, GraphCallback callback, Object state)
        {
            this._baseQuery.SetParameter("s", subclass);
            this._baseQuery.SetUri("p", UriFactory.Create(NamespaceMapper.RDFS + "subClassOf"));
            this._baseQuery.SetParameter("o", superclass);

            base.Explain(this._baseQuery.ToString(), callback, state);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Gets a Graph explaining why the given Triple was derived
        /// </summary>
        /// <param name="subj">Subject</param>
        /// <param name="pred">Predicate</param>
        /// <param name="obj">Object</param>
        /// <param name="callback">Callback to invoke when the operation completes</param>
        /// <param name="state">State to pass to the callback</param>
        /// <remarks>
        /// If the operation succeeds the callback will be invoked normally, if there is an error the callback will be invoked with a instance of <see cref="AsyncError"/> passed as the state which provides access to the error message and the original state passed in.
        /// </remarks>
        public void ExplainProperty(INode subj, INode pred, INode obj, GraphCallback callback, Object state)
        {
            this._baseQuery.SetParameter("s", subj);
            this._baseQuery.SetParameter("p", pred);
            this._baseQuery.SetParameter("o", obj);

            base.Explain(this._baseQuery.ToString(), callback, state);
        }
Ejemplo n.º 13
0
        public async void GetUserInfo()
        {
            GraphCallback graphCallBack = new GraphCallback();

            graphCallBack.RequestCompleted -= GraphCallBack_RequestCompleted;
            graphCallBack.RequestCompleted += GraphCallBack_RequestCompleted;

            var request = new GraphRequest(AccessToken.CurrentAccessToken, "/me", null, HttpMethod.Get, graphCallBack);
            await Task.Run(() => { request.ExecuteAsync(); });
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Extracts the Graph which comprises the class hierarchy.
        /// </summary>
        /// <param name="callback">Callback for when the operation completes.</param>
        /// <param name="state">State to be passed to the callback.</param>
        /// <remarks>
        /// If the operation succeeds the callback will be invoked normally, if there is an error the callback will be invoked with a instance of <see cref="AsyncError"/> passed as the state which provides access to the error message and the original state passed in.
        /// </remarks>
        public void Classify(GraphCallback callback, Object state)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Endpoint.Uri);

            request.Method = Endpoint.HttpMethods.First();
            request.Accept = MimeTypesHelper.CustomHttpAcceptHeader(MimeTypes, MimeTypesHelper.SupportedRdfMimeTypes);

            Tools.HttpDebugRequest(request);

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

                            IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType);
                            Graph g           = new Graph();
                            parser.Load(g, new StreamReader(response.GetResponseStream()));

                            response.Close();
                            callback(g, state);
                        }
                    }
                    catch (WebException webEx)
                    {
                        if (webEx.Response != null)
                        {
                            Tools.HttpDebugResponse((HttpWebResponse)webEx.Response);
                        }
                        callback(null, new AsyncError(new RdfReasoningException("A HTTP error occurred while communicating with the Pellet Server, see inner exception for details", webEx), state));
                    }
                    catch (Exception ex)
                    {
                        callback(null, new AsyncError(new RdfReasoningException("An unexpected error occurred while communicating with the Pellet Server, see inner exception for details", ex), state));
                    }
                }, null);
            }
            catch (WebException webEx)
            {
                if (webEx.Response != null)
                {
                    Tools.HttpDebugResponse((HttpWebResponse)webEx.Response);
                }
                callback(null, new AsyncError(new RdfReasoningException("A HTTP error occurred while communicating with the Pellet Server, see inner exception for details", webEx), state));
            }
            catch (Exception ex)
            {
                callback(null, new AsyncError(new RdfReasoningException("An unexpected error occurred while communicating with the Pellet Server, see inner exception for details", ex), state));
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Makes a Query asynchronously where the expected Result is an RDF Graph ie. CONSTRUCT and DESCRIBE Queries
        /// </summary>
        /// <param name="query">SPARQL Query String</param>
        /// <param name="callback">Callback to invoke when the query completes</param>
        /// <param name="state">State to pass to the callback</param>
        public void QueryWithResultGraph(String query, GraphCallback callback, Object state)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(this.Uri);

            request.Method      = "POST";
            request.ContentType = MimeTypesHelper.WWWFormURLEncoded;
            request.Accept      = MimeTypesHelper.HttpAcceptHeader;

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

            request.BeginGetRequestStream(result =>
            {
                Stream stream = request.EndGetRequestStream(result);
                using (StreamWriter writer = new StreamWriter(stream))
                {
                    writer.Write("query=");
                    writer.Write(HttpUtility.UrlEncode(query));

                    foreach (String u in this.DefaultGraphs)
                    {
                        writer.Write("&default-graph-uri=");
                        writer.Write(Uri.EscapeDataString(u));
                    }
                    foreach (String u in this.NamedGraphs)
                    {
                        writer.Write("&named-graph-uri=");
                        writer.Write(Uri.EscapeDataString(u));
                    }

                    writer.Close();
                }

                request.BeginGetResponse(innerResult =>
                {
                    HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(innerResult);
#if DEBUG
                    if (Options.HttpDebugging)
                    {
                        Tools.HttpDebugResponse(response);
                    }
#endif
                    IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType);
                    Graph g           = new Graph();
                    parser.Load(g, new StreamReader(response.GetResponseStream()));

                    callback(g, state);
                }, null);
            }, null);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Attempts to load a RDF Graph from a URI asynchronously
        /// </summary>
        /// <param name="g">Graph to assert triple in</param>
        /// <param name="u">URI to load from</param>
        /// <param name="parser">Parser to use</param>
        /// <param name="callback">Callback to invoke when the operation completes</param>
        /// <param name="state">State to pass to the callback</param>
        /// <remarks>
        /// <para>
        /// Uses the supplied parser to attempt parsing regardless of the actual Content Type returned
        /// </para>
        /// <para>
        /// In the event that the URI is a File URI the <see cref="FileLoader">FileLoader</see> will be used instead. If the URI is a Data URI then the <see cref="DataUriLoader">DataUriLoader</see> will be used instead.
        /// </para>
        /// <para>
        /// <strong>Note:</strong> UriLoader will assign the Graph the source URI as it's Base URI unless the Graph already has a Base URI or is non-empty prior to attempting parsing.  Note that any Base URI specified in the RDF contained in the file will override this initial Base URI.  In some cases this may lead to invalid RDF being accepted and generating strange relative URIs, if you encounter this either set a Base URI prior to calling this method or create an instance of the relevant parser and invoke it directly.
        /// </para>
        /// <para>
        /// If the loading completes normally the callback will be invoked normally, if an error occurs it will be invoked and passed an instance of <see cref="AsyncError"/> as the state which contains details of the error and the original state.
        /// </para>
        /// </remarks>
        public static void Load(IGraph g, Uri u, IRdfReader parser, GraphCallback callback, Object state)
        {
            if (g == null)
            {
                throw new RdfParseException("Cannot read RDF into a null Graph");
            }
            if (u == null)
            {
                throw new RdfParseException("Cannot read RDF from a null URI");
            }

#if SILVERLIGHT
            if (u.IsFile())
#else
            if (u.IsFile)
#endif
            {
#if PORTABLE
                throw new PlatformNotSupportedException("FileLoader is not supported by the Portable Class Library build");
#else
                //Invoke FileLoader instead
                UriLoader.RaiseWarning("This is a file: URI so invoking the FileLoader instead");
                if (Path.DirectorySeparatorChar == '/')
                {
                    FileLoader.Load(g, u.AbsoluteUri.Substring(7), parser);
                }
                else
                {
                    FileLoader.Load(g, u.AbsoluteUri.Substring(8), parser);
                }
                //FileLoader.Load() will run synchronously so once this completes we can invoke the callback
                callback(g, state);
                return;
#endif
            }
            if (u.Scheme.Equals("data"))
            {
                //Invoke DataUriLoader instead
                RaiseWarning("This is a data: URI so invoking the DataUriLoader instead");
                DataUriLoader.Load(g, u);
                //After DataUriLoader.Load() has run (which happens synchronously) can invoke the callback
                callback(g, state);
                return;
            }

            //Set Base URI if necessary
            if (g.BaseUri == null && g.IsEmpty)
            {
                g.BaseUri = u;
            }

            UriLoader.Load(new GraphHandler(g), u, parser, (_, s) => callback(g, s), state);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Processes a SPARQL Query asynchronously invoking the relevant callback when the query completes
        /// </summary>
        /// <param name="query">SPARQL QUery</param>
        /// <param name="rdfCallback">Callback for queries that return a Graph</param>
        /// <param name="resultsCallback">Callback for queries that return a Result Set</param>
        /// <param name="state">State to pass to the callback</param>
        public void ProcessQuery(SparqlQuery query, GraphCallback rdfCallback, SparqlResultsCallback resultsCallback, Object state)
        {
            query.QueryExecutionTime = null;
            DateTime start = DateTime.Now;

            try
            {
                this._svc.Query(query.ToString(), rdfCallback, resultsCallback, state);
            }
            finally
            {
                TimeSpan elapsed = (DateTime.Now - start);
                query.QueryExecutionTime = (DateTime.Now - start);
            }
        }
Ejemplo n.º 18
0
        public void OnSuccess(Java.Lang.Object result)
        {
            LoginResult loginResult = result as LoginResult;


            GraphCallback graphCallBack = new GraphCallback();

            graphCallBack.RequestCompleted += OnGetFriendsResponseAsync;

            Bundle bundle = new Bundle();

            bundle.PutString("fields", "id,name,email");



            var request = new GraphRequest(loginResult.AccessToken, "/" + AccessToken.CurrentAccessToken.UserId, bundle, HttpMethod.Get, graphCallBack).ExecuteAsync();
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Processes a SPARQL Query asynchronously invoking the relevant callback when the query completes
        /// </summary>
        /// <param name="query">SPARQL QUery</param>
        /// <param name="rdfCallback">Callback for queries that return a Graph</param>
        /// <param name="resultsCallback">Callback for queries that return a Result Set</param>
        /// <param name="state">State to pass to the callback</param>
        /// <remarks>
        /// In the event of a success the appropriate callback will be invoked, if there is an error both callbacks will be invoked and passed an instance of <see cref="AsyncError"/> which contains details of the error and the original state information passed in.
        /// </remarks>
        public void ProcessQuery(SparqlQuery query, GraphCallback rdfCallback, SparqlResultsCallback resultsCallback, Object state)
        {
            Graph             g    = new Graph();
            SparqlResultSet   rset = new SparqlResultSet();
            ProcessQueryAsync d    = new ProcessQueryAsync(this.ProcessQuery);

            d.BeginInvoke(new GraphHandler(g), new ResultSetHandler(rset), query, r =>
            {
                try
                {
                    d.EndInvoke(r);
                    if (rset.ResultsType != SparqlResultsType.Unknown)
                    {
                        resultsCallback(rset, state);
                    }
                    else
                    {
                        rdfCallback(g, state);
                    }
                }
                catch (RdfQueryException queryEx)
                {
                    if (rdfCallback != null)
                    {
                        rdfCallback(null, new AsyncError(queryEx, state));
                    }
                    if (resultsCallback != null)
                    {
                        resultsCallback(null, new AsyncError(queryEx, state));
                    }
                }
                catch (Exception ex)
                {
                    RdfQueryException queryEx = new RdfQueryException("Unexpected error while making an asynchronous query, see inner exception for details", ex);
                    if (rdfCallback != null)
                    {
                        rdfCallback(null, new AsyncError(queryEx, state));
                    }
                    if (resultsCallback != null)
                    {
                        resultsCallback(null, new AsyncError(queryEx, state));
                    }
                }
            }, state);
        }
Ejemplo n.º 20
0
        public async Task <FeedResponse> GetFeed()
        {
            taskCompletion = new TaskCompletionSource <GraphResponse>();
            FeedResponse  feedResponse  = null;
            GraphCallback graphCallback = new GraphCallback();

            graphCallback.RequestCompleted += GraphCallback_RequestCompleted;
            var graphRequest = new GraphRequest(AccessToken.CurrentAccessToken, $"/me/feed", null, HttpMethod.Get, graphCallback);

            graphRequest.ExecuteAsync();
            var graphResponse = await taskCompletion.Task;

            graphCallback.RequestCompleted -= GraphCallback_RequestCompleted;
            feedResponse = Newtonsoft.Json.JsonConvert.DeserializeObject <FeedResponse>(graphResponse.RawResponse);


            return(feedResponse);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Processes a SPARQL Query asynchronously invoking the relevant callback when the query completes
        /// </summary>
        /// <param name="query">SPARQL QUery</param>
        /// <param name="rdfCallback">Callback for queries that return a Graph</param>
        /// <param name="resultsCallback">Callback for queries that return a Result Set</param>
        /// <param name="state">State to pass to the callback</param>
        public void ProcessQuery(SparqlQuery query, GraphCallback rdfCallback, SparqlResultsCallback resultsCallback, Object state)
        {
            Graph             g    = new Graph();
            SparqlResultSet   rset = new SparqlResultSet();
            ProcessQueryAsync d    = new ProcessQueryAsync(this.ProcessQuery);

            d.BeginInvoke(new GraphHandler(g), new ResultSetHandler(rset), query, r =>
            {
                d.EndInvoke(r);
                if (rset.ResultsType != SparqlResultsType.Unknown)
                {
                    resultsCallback(rset, state);
                }
                else
                {
                    rdfCallback(g, state);
                }
            }, state);
        }
Ejemplo n.º 22
0
        public async Task <Uri> GetPicture(string id)
        {
            taskCompletion = new TaskCompletionSource <GraphResponse>();
            Uri           uri           = null;
            GraphCallback graphCallback = new GraphCallback();

            graphCallback.RequestCompleted += GraphCallback_RequestCompleted;
            var graphRequest = new GraphRequest(AccessToken.CurrentAccessToken, $"/{id}?fields=picture.type(large)", null, HttpMethod.Get, graphCallback);

            graphRequest.ExecuteAsync();
            var graphResponse = await taskCompletion.Task;

            graphCallback.RequestCompleted -= GraphCallback_RequestCompleted;

            uri = new Uri(Newtonsoft.Json.JsonConvert.DeserializeObject <PictureResponse>(graphResponse.RawResponse).picture.data.url);


            return(uri);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Gets the raw Cluster Graph for the Knowledge Base
        /// </summary>
        /// <param name="number">Number of Clusters</param>
        /// <param name="callback">Callback to be invoked when the operation completes</param>
        /// <param name="state">State to be passed to the callback</param>
        public void ClusterRaw(int number, GraphCallback callback, Object state)
        {
            if (number < 2)
            {
                throw new RdfReasoningException("Pellet Server requires the number of Clusters to be at least 2");
            }

            String requestUri = this._clusterUri + number + "/";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);

            request.Method = this.Endpoint.HttpMethods.First();
            request.Accept = MimeTypesHelper.CustomHttpAcceptHeader(this.MimeTypes.Where(type => !type.Equals("text/json")), MimeTypesHelper.SupportedRdfMimeTypes);

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

            request.BeginGetResponse(result =>
            {
                using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result))
                {
#if DEBUG
                    if (Options.HttpDebugging)
                    {
                        Tools.HttpDebugResponse(response);
                    }
#endif
                    IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType);
                    Graph g           = new Graph();
                    parser.Load(g, new StreamReader(response.GetResponseStream()));

                    response.Close();
                    callback(g, state);
                }
            }, null);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Attempts to load a RDF Graph from a URI asynchronously
        /// </summary>
        /// <param name="g">Graph to assert triple in</param>
        /// <param name="u">URI to load from</param>
        /// <param name="parser">Parser to use</param>
        /// <param name="callback">Callback to invoke when the operation completes</param>
        /// <param name="state">State to pass to the callback</param>
        /// <remarks>
        /// <para>
        /// Uses the supplied parser to attempt parsing regardless of the actual Content Type returned
        /// </para>
        /// <para>
        /// In the event that the URI is a File URI the <see cref="FileLoader">FileLoader</see> will be used instead
        /// </para>
        /// <para>
        /// If the URI is a Data URI then the <see cref="DataUriLoader">DataUriLoader</see> will be used instead.
        /// </para>
        /// </remarks>
        public static void Load(IGraph g, Uri u, IRdfReader parser, GraphCallback callback, Object state)
        {
            if (g == null) throw new RdfParseException("Cannot read RDF into a null Graph");
            if (u == null) throw new RdfParseException("Cannot read RDF from a null URI");

            #if SILVERLIGHT
            if (u.IsFile())
            #else
            if (u.IsFile)
            #endif
            {
                //Invoke FileLoader instead
                UriLoader.RaiseWarning("This is a file: URI so invoking the FileLoader instead");
                if (Path.DirectorySeparatorChar == '/')
                {
                    FileLoader.Load(g, u.ToString().Substring(7), parser);
                }
                else
                {
                    FileLoader.Load(g, u.ToString().Substring(8), parser);
                }
                //FileLoader.Load() will run synchronously so once this completes we can invoke the callback
                callback(g, state);
                return;
            }
            if (u.Scheme.Equals("data"))
            {
                //Invoke DataUriLoader instead
                RaiseWarning("This is a data: URI so invoking the DataUriLoader instead");
                DataUriLoader.Load(g, u);
                //After DataUriLoader.Load() has run (which happens synchronously) can invoke the callback
                callback(g, state);
                return;
            }

            //Set Base URI if necessary
            if (g.BaseUri == null && g.IsEmpty) g.BaseUri = u;

            UriLoader.Load(new GraphHandler(g), u, parser, (_,s) => callback(g, s), state);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Gets a Graph explaining the result of the SPARQL Query
        /// </summary>
        /// <param name="sparqlQuery">SPARQL Query</param>
        /// <param name="callback">Callback to invoke when the operation completes</param>
        /// <param name="state">State to pass to the callback</param>
        /// <returns></returns>
        public void Explain(String sparqlQuery, GraphCallback callback, Object state)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(this._explainUri + "?query=" + HttpUtility.UrlEncode(sparqlQuery));

            request.Method = this.Endpoint.HttpMethods.First();
            request.Accept = MimeTypesHelper.CustomHttpAcceptHeader(this.MimeTypes, MimeTypesHelper.SupportedRdfMimeTypes);

            Tools.HttpDebugRequest(request);

            request.BeginGetResponse(result =>
            {
                using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result))
                {
                    Tools.HttpDebugResponse(response);
                    IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType);
                    Graph g           = new Graph();
                    parser.Load(g, new StreamReader(response.GetResponseStream()));

                    response.Close();
                    callback(g, state);
                }
            }, null);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Gets a Graph explaining why the given Class is a subclass of the given Super Class
        /// </summary>
        /// <param name="subclass">Class</param>
        /// <param name="superclass">Super Class</param>
        /// <param name="callback">Callback to invoke when the operation completes</param>
        /// <param name="state">State to pass to the callback</param>
        /// <returns></returns>
        public void ExplainSubclass(INode subclass, INode superclass, GraphCallback callback, Object state)
        {
            this._baseQuery.SetParameter("s", subclass);
            this._baseQuery.SetUri("p", new Uri(NamespaceMapper.RDFS + "subClassOf"));
            this._baseQuery.SetParameter("o", superclass);

            base.Explain(this._baseQuery.ToString(), callback, state);
        }
Ejemplo n.º 27
0
 /// <summary>
 /// Gets a Graph explaining why the given Triple was derived
 /// </summary>
 /// <param name="t">Triple</param>
 /// <param name="callback">Callback to invoke when the operation completes</param>
 /// <param name="state">State to pass to the callback</param>
 /// <remarks>
 /// If the operation succeeds the callback will be invoked normally, if there is an error the callback will be invoked with a instance of <see cref="AsyncError"/> passed as the state which provides access to the error message and the original state passed in.
 /// </remarks>
 public void ExplainProprety(Triple t, GraphCallback callback, Object state)
 {
     this.ExplainProperty(t.Subject, t.Predicate, t.Object, callback, state);
 }
Ejemplo n.º 28
0
        /// <summary>
        /// Gets a Graph explaining why the given Triple was derived
        /// </summary>
        /// <param name="subj">Subject</param>
        /// <param name="pred">Predicate</param>
        /// <param name="obj">Object</param>
        /// <param name="callback">Callback to invoke when the operation completes</param>
        /// <param name="state">State to pass to the callback</param>
        /// <returns></returns>
        public void ExplainProperty(INode subj, INode pred, INode obj, GraphCallback callback, Object state)
        {
            this._baseQuery.SetParameter("s", subj);
            this._baseQuery.SetParameter("p", pred);
            this._baseQuery.SetParameter("o", obj);

            base.Explain(this._baseQuery.ToString(), callback, state);
        }
Ejemplo n.º 29
0
 /// <summary>
 /// Gets a Graph explaining why the Knowledge Base is inconsistent
 /// </summary>
 /// <param name="callback">Callback to invoke when the operation completes</param>
 /// <param name="state">State to pass to the callback</param>
 /// <returns></returns>
 public void ExplainInconsistent(GraphCallback callback, Object state)
 {
     base.Explain(String.Empty, callback, state);
 }
Ejemplo n.º 30
0
        /// <summary>
        /// Makes a SPARQL Query against the Knowledge Base
        /// </summary>
        /// <param name="sparqlQuery">SPARQL Query</param>
        /// <param name="graphCallback">Callback to invoke for queries that return a Graph</param>
        /// <param name="resultsCallback">Callback to invoke for queries that return a Result Set</param>
        /// <param name="state">State to pass to whichever callback function is invoked</param>
        /// <returns></returns>
        public void Query(String sparqlQuery, GraphCallback graphCallback, SparqlResultsCallback resultsCallback, Object state)
        {
            Graph g = new Graph();
            SparqlResultSet results = new SparqlResultSet();

            this.Query(new GraphHandler(g), new ResultSetHandler(results), sparqlQuery, (gh, rh, _) =>
                {
                    if (results.ResultsType != SparqlResultsType.Unknown)
                    {
                        resultsCallback(results, state);
                    }
                    else
                    {
                        graphCallback(g, state);
                    }
                }, state);
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Makes a Query asynchronously where the expected Result is an RDF Graph ie. CONSTRUCT and DESCRIBE Queries.
        /// </summary>
        /// <param name="query">SPARQL Query String.</param>
        /// <param name="callback">Callback to invoke when the query completes.</param>
        /// <param name="state">State to pass to the callback.</param>
        public void QueryWithResultGraph(String query, GraphCallback callback, Object state)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Uri);

            request.Method      = "POST";
            request.ContentType = MimeTypesHelper.Utf8WWWFormURLEncoded;
            request.Accept      = RdfAcceptHeader;
            ApplyRequestOptions(request);
            Tools.HttpDebugRequest(request);

            try
            {
                request.BeginGetRequestStream(result =>
                {
                    try
                    {
                        Stream stream = request.EndGetRequestStream(result);
                        using (StreamWriter writer = new StreamWriter(stream, new UTF8Encoding(Options.UseBomForUtf8)))
                        {
                            writer.Write("query=");
                            writer.Write(HttpUtility.UrlEncode(query));

                            foreach (String u in DefaultGraphs)
                            {
                                writer.Write("&default-graph-uri=");
                                writer.Write(HttpUtility.UrlEncode(u));
                            }
                            foreach (String u in NamedGraphs)
                            {
                                writer.Write("&named-graph-uri=");
                                writer.Write(HttpUtility.UrlEncode(u));
                            }

                            writer.Close();
                        }

                        request.BeginGetResponse(innerResult =>
                        {
                            try
                            {
                                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(innerResult);
                                Tools.HttpDebugResponse(response);
                                IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType);
                                Graph g           = new Graph();
                                parser.Load(g, new StreamReader(response.GetResponseStream()));

                                callback(g, state);
                            }
                            catch (SecurityException secEx)
                            {
                                callback(null, new AsyncError(new RdfQueryException("Calling code does not have permission to access the specified remote endpoint, see inner exception for details", secEx), state));
                            }
                            catch (WebException webEx)
                            {
                                if (webEx.Response != null)
                                {
                                    Tools.HttpDebugResponse((HttpWebResponse)webEx.Response);
                                }
                                callback(null, new AsyncError(new RdfQueryException("A HTTP error occurred while making an asynchronous query, see inner exception for details", webEx), state));
                            }
                            catch (Exception ex)
                            {
                                callback(null, new AsyncError(new RdfQueryException("Unexpected error while making an asynchronous query, see inner exception for details", ex), state));
                            }
                        }, null);
                    }
                    catch (SecurityException secEx)
                    {
                        callback(null, new AsyncError(new RdfQueryException("Calling code does not have permission to access the specified remote endpoint, see inner exception for details", secEx), state));
                    }
                    catch (WebException webEx)
                    {
                        if (webEx.Response != null)
                        {
                            Tools.HttpDebugResponse((HttpWebResponse)webEx.Response);
                        }
                        callback(null, new AsyncError(new RdfQueryException("A HTTP error occurred while making an asynchronous query, see inner exception for details", webEx), state));
                    }
                    catch (Exception ex)
                    {
                        callback(null, new AsyncError(new RdfQueryException("Unexpected error while making an asynchronous query, see inner exception for details", ex), state));
                    }
                }, null);
            }
            catch (Exception ex)
            {
                callback(null, new AsyncError(new RdfQueryException("Unexpected error while making an asynchronous query, see inner exception for details", ex), state));
            }
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Gets a Graph explaining the result of the SPARQL Query
        /// </summary>
        /// <param name="sparqlQuery">SPARQL Query</param>
        /// <param name="callback">Callback to invoke when the operation completes</param>
        /// <param name="state">State to pass to the callback</param>
        /// <returns></returns>
        public void Explain(String sparqlQuery, GraphCallback callback, Object state)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(this._explainUri + "?query=" + HttpUtility.UrlEncode(sparqlQuery));
            request.Method = this.Endpoint.HttpMethods.First();
            request.Accept = MimeTypesHelper.CustomHttpAcceptHeader(this.MimeTypes, MimeTypesHelper.SupportedRdfMimeTypes);

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

            request.BeginGetResponse(result =>
                {
                    using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result))
                    {
#if DEBUG
                        if (Options.HttpDebugging)
                        {
                            Tools.HttpDebugResponse(response);
                        }
#endif
                        IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType);
                        Graph g = new Graph();
                        parser.Load(g, new StreamReader(response.GetResponseStream()));

                        response.Close();
                        callback(g, state);
                    }
                }, null);
        }
Ejemplo n.º 33
0
        /// <summary>
        /// Gets the raw Cluster Graph for the Knowledge Base
        /// </summary>
        /// <param name="number">Number of Clusters</param>
        /// <param name="type">QName of a Type to Cluster around</param>
        /// <param name="callback">Callback to be invoked when the operation completes</param>
        /// <param name="state">State to be passed to the callback</param>
        public void ClusterRaw(int number, String type, GraphCallback callback, Object state)
        {
            if (number < 2) throw new RdfReasoningException("Pellet Server requires the number of Clusters to be at least 2");

            String requestUri = this._clusterUri + number + "/" + type;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);
            request.Method = this.Endpoint.HttpMethods.First();
            request.Accept = MimeTypesHelper.CustomHttpAcceptHeader(this.MimeTypes.Where(t => !t.Equals("text/json")), MimeTypesHelper.SupportedRdfMimeTypes);

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

            request.BeginGetResponse(result =>
                {
                    using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result))
                    {
#if DEBUG
                        if (Options.HttpDebugging)
                        {
                            Tools.HttpDebugResponse(response);
                        }
#endif
                        IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType);
                        Graph g = new Graph();
                        parser.Load(g, new StreamReader(response.GetResponseStream()));

                        response.Close();
                        callback(g, state);
                    }
                }, null);
        }
Ejemplo n.º 34
0
 /// <summary>
 /// Processes a SPARQL Query asynchronously invoking the relevant callback when the query completes
 /// </summary>
 /// <param name="query">SPARQL QUery</param>
 /// <param name="rdfCallback">Callback for queries that return a Graph</param>
 /// <param name="resultsCallback">Callback for queries that return a Result Set</param>
 /// <param name="state">State to pass to the callback</param>
 public void ProcessQuery(SparqlQuery query, GraphCallback rdfCallback, SparqlResultsCallback resultsCallback, Object state)
 {
     query.QueryExecutionTime = null;
     DateTime start = DateTime.Now;
     try
     {
         switch (query.QueryType)
         {
             case SparqlQueryType.Ask:
             case SparqlQueryType.Select:
             case SparqlQueryType.SelectAll:
             case SparqlQueryType.SelectAllDistinct:
             case SparqlQueryType.SelectAllReduced:
             case SparqlQueryType.SelectDistinct:
             case SparqlQueryType.SelectReduced:
                 this._endpoint.QueryWithResultSet(this._formatter.Format(query), resultsCallback, state);
                 break;
             case SparqlQueryType.Construct:
             case SparqlQueryType.Describe:
             case SparqlQueryType.DescribeAll:
                 this._endpoint.QueryWithResultGraph(this._formatter.Format(query), rdfCallback, state);
                 break;
             default:
                 throw new RdfQueryException("Unable to execute an unknown query type against a Remote Endpoint");
         }
     }
     finally
     {
         TimeSpan elapsed = (DateTime.Now - start);
         query.QueryExecutionTime = elapsed;
     }
 }
Ejemplo n.º 35
0
 /// <summary>
 /// Processes a SPARQL Query asynchronously invoking the relevant callback when the query completes
 /// </summary>
 /// <param name="query">SPARQL QUery</param>
 /// <param name="rdfCallback">Callback for queries that return a Graph</param>
 /// <param name="resultsCallback">Callback for queries that return a Result Set</param>
 /// <param name="state">State to pass to the callback</param>
 public void ProcessQuery(SparqlQuery query, GraphCallback rdfCallback, SparqlResultsCallback resultsCallback, Object state)
 {
     Graph g = new Graph();
     SparqlResultSet rset = new SparqlResultSet();
     ProcessQueryAsync d = new ProcessQueryAsync(this.ProcessQuery);
     d.BeginInvoke(new GraphHandler(g), new ResultSetHandler(rset), query, r =>
         {
             d.EndInvoke(r);
             if (rset.ResultsType != SparqlResultsType.Unknown)
             {
                 resultsCallback(rset, state);
             }
             else
             {
                 rdfCallback(g, state);
             }
         }, state);
 }
Ejemplo n.º 36
0
        /// <summary>
        /// Gets a Graph explaining why an Instance is of the given Class
        /// </summary>
        /// <param name="instance">Instance</param>
        /// <param name="cls">Class</param>
        /// <param name="callback">Callback to invoke when the operation completes</param>
        /// <param name="state">State to pass to the callback</param>
        /// <returns></returns>
        public void ExplainInstance(INode instance, INode cls, GraphCallback callback, Object state)
        {
            this._baseQuery.SetParameter("s", instance);
            this._baseQuery.SetUri("p", new Uri(RdfSpecsHelper.RdfType));
            this._baseQuery.SetParameter("o", cls);

            base.Explain(this._baseQuery.ToString(), callback, state);
        }
Ejemplo n.º 37
0
 /// <summary>
 /// Processes a SPARQL Query asynchronously invoking the relevant callback when the query completes
 /// </summary>
 /// <param name="query">SPARQL QUery</param>
 /// <param name="rdfCallback">Callback for queries that return a Graph</param>
 /// <param name="resultsCallback">Callback for queries that return a Result Set</param>
 /// <param name="state">State to pass to the callback</param>
 public void ProcessQuery(SparqlQuery query, GraphCallback rdfCallback, SparqlResultsCallback resultsCallback, Object state)
 {
     query.QueryExecutionTime = null;
     DateTime start = DateTime.Now;
     try
     {
         this._svc.Query(query.ToString(), rdfCallback, resultsCallback, state);
     }
     finally
     {
         TimeSpan elapsed = (DateTime.Now - start);
         query.QueryExecutionTime = (DateTime.Now - start);
     }
 }
Ejemplo n.º 38
0
        /// <summary>
        /// Gets the Raw Predictions Graph from the Knowledge Base
        /// </summary>
        /// <param name="individual">QName of an Individual</param>
        /// <param name="property">QName of a Property</param>
        /// <param name="callback">Callback to invoke when the operation completes</param>
        /// <param name="state">State to pass to the callback</param>
        public void PredictRaw(String individual, String property, GraphCallback callback, Object state)
        {
            String requestUri = this._predictUri + individual + "/" + property;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);
            request.Method = this.Endpoint.HttpMethods.First();
            request.Accept = MimeTypesHelper.CustomHttpAcceptHeader(this.MimeTypes.Where(t => !t.Equals("text/json")), MimeTypesHelper.SupportedRdfMimeTypes);

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

            request.BeginGetResponse(result =>
                {
                    using (HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result))
                    {
            #if DEBUG
                        if (Options.HttpDebugging)
                        {
                            Tools.HttpDebugResponse(response);
                        }
            #endif
                        IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType);
                        Graph g = new Graph();
                        parser.Load(g, new StreamReader(response.GetResponseStream()));

                        response.Close();
                        callback(g, state);
                    }
                }, null);
        }
Ejemplo n.º 39
0
 /// <summary>
 /// Gets a Graph explaining why the Knowledge Base is inconsistent
 /// </summary>
 /// <param name="callback">Callback to invoke when the operation completes</param>
 /// <param name="state">State to pass to the callback</param>
 /// <remarks>
 /// If the operation succeeds the callback will be invoked normally, if there is an error the callback will be invoked with a instance of <see cref="AsyncError"/> passed as the state which provides access to the error message and the original state passed in.
 /// </remarks>
 public void ExplainInconsistent(GraphCallback callback, Object state)
 {
     base.Explain(String.Empty, callback, state);
 }
Ejemplo n.º 40
0
 /// <summary>
 /// Attempts to load a RDF Graph from a URI asynchronously
 /// </summary>
 /// <param name="g">Graph to assert triple in</param>
 /// <param name="u">URI to load from</param>
 /// <param name="callback">Callback to invoke when the operation completes</param>
 /// <param name="state">State to pass to the callback</param>
 /// <remarks>
 /// <para>
 /// Will attempt to autodetect the format of the RDF based on the Content-Type header of the HTTP response
 /// </para>
 /// </remarks>
 public static void Load(IGraph g, Uri u, GraphCallback callback, Object state)
 {
     UriLoader.Load(g, u, null, callback, state);
 }
Ejemplo n.º 41
0
 /// <summary>
 /// Gets a Graph explaining why the given Triple was derived
 /// </summary>
 /// <param name="t">Triple</param>
 /// <param name="callback">Callback to invoke when the operation completes</param>
 /// <param name="state">State to pass to the callback</param>
 public void ExplainProprety(Triple t, GraphCallback callback, Object state)
 {
     this.ExplainProperty(t.Subject, t.Predicate, t.Object, callback, state);
 }
Ejemplo n.º 42
0
        /// <summary>
        /// Gets a Graph explaining why a Class is unsatisfiable
        /// </summary>
        /// <param name="cls">Class</param>
        /// <param name="callback">Callback to invoke when the operation completes</param>
        /// <param name="state">State to pass to the callback</param>
        /// <returns></returns>
        public void ExplainUnsatisfiable(INode cls, GraphCallback callback, Object state)
        {
            this._baseQuery.SetParameter("s", cls);
            this._baseQuery.SetUri("p", new Uri(NamespaceMapper.RDFS + "subClassOf"));
            this._baseQuery.SetUri("o", new Uri(OwlHelper.OwlNothing));

            base.Explain(this._baseQuery.ToString(), callback, state);
        }
Ejemplo n.º 43
0
 /// <summary>
 /// Attempts to load a RDF Graph from a URI asynchronously.
 /// </summary>
 /// <param name="g">Graph to assert triple in.</param>
 /// <param name="u">URI to load from.</param>
 /// <param name="callback">Callback to invoke when the operation completes.</param>
 /// <param name="state">State to pass to the callback.</param>
 /// <remarks>
 /// <para>
 /// Will attempt to autodetect the format of the RDF based on the Content-Type header of the HTTP response.
 /// </para>
 /// <para>
 /// In the event that the URI is a File URI the <see cref="FileLoader">FileLoader</see> will be used instead. If the URI is a Data URI then the <see cref="DataUriLoader">DataUriLoader</see> will be used instead.
 /// </para>
 /// <para>
 /// <strong>Note:</strong> UriLoader will assign the Graph the source URI as it's Base URI unless the Graph already has a Base URI or is non-empty prior to attempting parsing.  Note that any Base URI specified in the RDF contained in the file will override this initial Base URI.  In some cases this may lead to invalid RDF being accepted and generating strange relative URIs, if you encounter this either set a Base URI prior to calling this method or create an instance of the relevant parser and invoke it directly.
 /// </para>
 /// <para>
 /// If the loading completes normally the callback will be invoked normally, if an error occurs it will be invoked and passed an instance of <see cref="AsyncError"/> as the state which contains details of the error and the original state.
 /// </para>
 /// </remarks>
 public static void Load(IGraph g, Uri u, GraphCallback callback, Object state)
 {
     Load(g, u, null, callback, state);
 }
Ejemplo n.º 44
0
        /// <summary>
        /// Makes a Query asynchronously where the expected Result is an RDF Graph ie. CONSTRUCT and DESCRIBE Queries
        /// </summary>
        /// <param name="query">SPARQL Query String</param>
        /// <param name="callback">Callback to invoke when the query completes</param>
        /// <param name="state">State to pass to the callback</param>
        public void QueryWithResultGraph(String query, GraphCallback callback, Object state)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(this.Uri);
            request.Method = "POST";
            request.ContentType = MimeTypesHelper.WWWFormURLEncoded;
            request.Accept = MimeTypesHelper.HttpAcceptHeader;

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

            request.BeginGetRequestStream(result =>
            {
                Stream stream = request.EndGetRequestStream(result);
                using (StreamWriter writer = new StreamWriter(stream))
                {
                    writer.Write("query=");
                    writer.Write(HttpUtility.UrlEncode(query));

                    foreach (String u in this.DefaultGraphs)
                    {
                        writer.Write("&default-graph-uri=");
                        writer.Write(Uri.EscapeDataString(u));
                    }
                    foreach (String u in this.NamedGraphs)
                    {
                        writer.Write("&named-graph-uri=");
                        writer.Write(Uri.EscapeDataString(u));
                    }

                    writer.Close();
                }

                request.BeginGetResponse(innerResult =>
                {
                    HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(innerResult);
            #if DEBUG
                    if (Options.HttpDebugging)
                    {
                        Tools.HttpDebugResponse(response);
                    }
            #endif
                    IRdfReader parser = MimeTypesHelper.GetParser(response.ContentType);
                    Graph g = new Graph();
                    parser.Load(g, new StreamReader(response.GetResponseStream()));

                    callback(g, state);
                }, null);
            }, null);
        }