Beispiel #1
0
        /// <summary>
        /// Updates the properties of a resource in the backing RDF store.
        /// </summary>
        /// <param name="resource">Resource that is to be updated in the backing store.</param>
        /// <param name="transaction">Transaction associated with this action.</param>
        public virtual void UpdateResource(Resource resource, ITransaction transaction = null)
        {
            string updateString;

            if (resource.IsNew)
            {
                updateString = string.Format(@"WITH {0} INSERT {{ {1} }} WHERE {{}}",
                                             SparqlSerializer.SerializeUri(Uri),
                                             SparqlSerializer.SerializeResource(resource, IgnoreUnmappedProperties));
            }
            else
            {
                updateString = string.Format(@"WITH {0} DELETE {{ {1} ?p ?o. }} INSERT {{ {2} }} WHERE {{ OPTIONAL {{ {1} ?p ?o. }} }}",
                                             SparqlSerializer.SerializeUri(Uri),
                                             SparqlSerializer.SerializeUri(resource.Uri),
                                             SparqlSerializer.SerializeResource(resource, IgnoreUnmappedProperties));
            }

            SparqlUpdate update = new SparqlUpdate(updateString)
            {
                Resource = resource
            };

            ExecuteUpdate(update, transaction);

            resource.IsNew          = false;
            resource.IsSynchronized = true;
        }
Beispiel #2
0
        /// <summary>
        /// Updates the properties of a resource in the backing RDF store.
        /// </summary>
        /// <param name="resource">Resource that is to be updated in the backing store.</param>
        /// <param name="transaction">ransaction associated with this action.</param>
        public void UpdateResource(Resource resource, ITransaction transaction = null)
        {
            string updateString;

            if (resource.IsNew)
            {
                updateString = string.Format(@"WITH {0} INSERT {{ {1} }} WHERE {{}}",
                                             SparqlSerializer.SerializeUri(Uri),
                                             SparqlSerializer.SerializeResource(resource));
            }
            else
            {
                updateString = string.Format(@"WITH {0} DELETE {{ {1} ?p ?o. }} INSERT {{ {2} }} WHERE {{ {1} ?p ?o. }} ",
                                             SparqlSerializer.SerializeUri(Uri),
                                             SparqlSerializer.SerializeUri(resource.Uri),
                                             SparqlSerializer.SerializeResource(resource));
            }

            SparqlUpdate update = new SparqlUpdate(updateString);

            update.Resource = resource;

            ExecuteUpdate(update, transaction);

            resource.IsNew = false;
        }
        public override string ToString()
        {
            SparqlQuery query = new SparqlQuery(SparqlSerializer.Serialize(_model, _query));

            query.Model = _model;

            return(query.ToString());
        }
        /// <summary>
        /// Generate the Dataset for a single model
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static string GenerateDatasetClause(IModel model)
        {
            if (model == null)
            {
                return("");
            }

            if (model is IModelGroup)
            {
                return(GenerateDatasetClause(model as IModelGroup));
            }

            return("FROM " + SparqlSerializer.SerializeUri(model.Uri) + " ");
        }
        /// <summary>
        /// Generate a dataset clause for an enumeration of models.
        /// </summary>
        /// <param name="models">An enumeration of models.</param>
        /// <returns></returns>
        public static string GenerateDatasetClause(IEnumerable <IModel> models)
        {
            if (!models.Any())
            {
                return("");
            }

            StringBuilder resultBuilder = new StringBuilder();

            foreach (var model in models)
            {
                resultBuilder.Append("FROM ");
                resultBuilder.Append(SparqlSerializer.SerializeUri(model.Uri));
                resultBuilder.Append(" ");
            }

            return(resultBuilder.ToString());
        }
        public IEnumerable <T> GetResources <T>(int offset = -1, int limit = -1) where T : Resource
        {
            _query.Offset = offset;
            _query.Limit  = limit;

            if (_inferenceEnabled)
            {
                SparqlQuery uriQuery = new SparqlQuery(SparqlSerializer.Serialize(_model, _query, true));

                StringBuilder uris    = new StringBuilder();
                var           uriList = FetchUris(uriQuery).ToList();

                foreach (Uri u in uriList)
                {
                    if (u != null)
                    {
                        uris.Append(SparqlSerializer.SerializeUri(u));
                    }
                }

                if (!uriList.Any())
                {
                    return(new List <T>());
                }

                SparqlQuery        query = new SparqlQuery(string.Format("DESCRIBE {0} {1}", uris, SparqlSerializer.GenerateDatasetClause(_model)));
                ISparqlQueryResult res   = _model.ExecuteQuery(query);

                if (IsSorted)
                {
                    return(res.GetResources <T>().OrderBy(o => { return (o != null) ? uriList.IndexOf(o.Uri) : -1; }));
                }
                else
                {
                    return(res.GetResources <T>());
                }
            }
            else
            {
                SparqlQuery query = new SparqlQuery(SparqlSerializer.Serialize(_model, _query));

                return(_model.ExecuteQuery(query, _inferenceEnabled).GetResources <T>());
            }
        }
        public int Count()
        {
            SparqlQuery query = new SparqlQuery(SparqlSerializer.SerializeCount(_model, _query));

            ISparqlQueryResult result = _model.ExecuteQuery(query, _inferenceEnabled);

            IEnumerable <BindingSet> bindings = result.GetBindings();

            if (bindings != null)
            {
                foreach (BindingSet b in bindings)
                {
                    if (b.ContainsKey("count"))
                    {
                        return((int)b["count"]);
                    }
                }
            }

            return(-1);
        }
Beispiel #8
0
        /// <summary>
        /// Set the value for a query parameter which is preceeded by '@'.
        /// </summary>
        /// <param name="parameter">The parameter name including the '@'.</param>
        /// <param name="value">The paramter value.</param>
        public void Bind(string parameter, object value)
        {
            if (string.IsNullOrEmpty(parameter))
            {
                throw new ArgumentException("Empty or null value for SPARQL query parameter.");
            }
            else if (parameter[0] != '@')
            {
                throw new ArgumentException("SPARQL query parameters must start with '@'.");
            }
            else if (value == null)
            {
                throw new ArgumentNullException("SPARQL query parameter values may not be null.");
            }
            else if (ParameterTypes[parameter] == CustomToken.GRAPHPARAMETER)
            {
                if (ParameterValues.ContainsKey(parameter))
                {
                    string g = ParameterValues[parameter];

                    DefaultGraphs.Remove(g);
                }

                string uri = SparqlSerializer.SerializeValue(value);
                string url = uri.TrimStart('<').TrimEnd('>');

                if (DefaultGraphs.Contains(url))
                {
                    throw new ArgumentException("FROM parameter value {0} is already set. Have you previously set the model property of the query?", uri);
                }

                DefaultGraphs.Add(url);

                ParameterValues[parameter] = uri;
            }
            else
            {
                ParameterValues[parameter] = SparqlSerializer.SerializeValue(value);
            }
        }
Beispiel #9
0
        /// <summary>
        /// Return the query with all bound variables.
        /// </summary>
        /// <param name="outputLevel">Level of the sub graph to be returned (0 := entire query).</param>
        /// <returns></returns>
        protected string Serialize(int outputLevel = 0)
        {
            StringBuilder outputBuilder = new StringBuilder();

            // The current iteration depth.
            int level = 0;

            for (int i = 0; i < Tokens.Count; i++)
            {
                IToken token = Tokens[i];

                if (token.TokenType == Token.LEFTCURLYBRACKET)
                {
                    level += 1;

                    // Do not output the brackets at the output level.
                    if (level == outputLevel)
                    {
                        continue;
                    }
                }
                else if (token.TokenType == Token.RIGHTCURLYBRACKET)
                {
                    level -= 1;
                }

                if (level < outputLevel)
                {
                    continue;
                }

                switch (token.TokenType)
                {
                default:
                {
                    outputBuilder.Append(token.Value);
                    outputBuilder.Append(' ');

                    break;
                }

                case Token.URI:
                {
                    outputBuilder.AppendFormat("<{0}> ", token.Value);

                    break;
                }

                case Token.LITERAL:
                case Token.LONGLITERAL:
                {
                    IToken next = i < Tokens.Count ? Tokens[i + 1] : null;

                    outputBuilder.Append(SparqlSerializer.SerializeString(token.Value));

                    if (next.TokenType != Token.LANGSPEC)
                    {
                        outputBuilder.Append(' ');
                    }

                    break;
                }

                case Token.LANGSPEC:
                {
                    outputBuilder.AppendFormat("@{0} ", token.Value);

                    break;
                }

                case Token.HATHAT:
                {
                    outputBuilder.Append(token.Value);

                    break;
                }

                case CustomToken.PARAMETER:
                case CustomToken.GRAPHPARAMETER:
                {
                    string key = token.Value;

                    if (!ParameterValues.ContainsKey(key))
                    {
                        string msg = string.Format("No value set for query parameter {0}.", key);

                        throw new KeyNotFoundException(msg);
                    }

                    outputBuilder.Append(ParameterValues[key]);
                    outputBuilder.Append(' ');

                    break;
                }
                }
            }

            return(outputBuilder.ToString().Trim());
        }
Beispiel #10
0
        public T GetResource <T>(Uri uri, ITransaction transaction = null) where T : Resource
        {
            SparqlQuery        query  = new SparqlQuery(String.Format("DESCRIBE {0} {1}", SparqlSerializer.SerializeUri(uri), DatasetClause));
            ISparqlQueryResult result = ExecuteQuery(query, transaction: transaction);

            IList resources = result.GetResources <T>().ToList();

            if (resources.Count > 0)
            {
                T res = resources[0] as T;
                res.IsNew          = false;
                res.IsSynchronized = true;
                res.IsReadOnly     = true;
                res.SetModel(this);
                return(res);
            }
            else
            {
                string msg = "Error: Could not find resource <{0}>.";
                throw new ArgumentException(string.Format(msg, uri));
            }
        }
Beispiel #11
0
 public bool ContainsResource(Uri uri, ITransaction transaction = null)
 {
     return(ExecuteQuery(new SparqlQuery(string.Format(@"ASK {0} {{ {1} ?p ?o . }}",
                                                       DatasetClause,
                                                       SparqlSerializer.SerializeUri(uri))), transaction: transaction).GetAnwser());
 }
Beispiel #12
0
 void UpdateDatasetClause()
 {
     _datasetClause = SparqlSerializer.GenerateDatasetClause(_set);
 }
Beispiel #13
0
 public override string ToString()
 {
     return(SparqlSerializer.Serialize(null, this));
 }