public void ShouldCreateBaseUriForRegisteredClass() { var uriFactory = new UriFactory(); uriFactory.Register<Monster>(); Assert.AreEqual(new Uri("http://localhost:8080/virtual-directory/"), uriFactory.CreateBaseUri<Monster>(new Uri("http://localhost:8080/virtual-directory/monsters/1"))); }
public void ShouldReturnRoutePrefixForRegisteredClass() { var uriFactory = new UriFactory(); uriFactory.Register<Monster>(); Assert.AreEqual("monsters", uriFactory.GetRoutePrefix<Monster>()); }
public void ShouldCreateRelativeUriForRegisteredClass() { var uriFactory = new UriFactory(); uriFactory.Register<Monster>(); Assert.AreEqual(new Uri("monsters/1", UriKind.Relative), uriFactory.CreateRelativeUri<Monster>("1")); }
public void ShouldReturnUriTemplateValueForRegisteredClass() { var uriFactory = new UriFactory(); uriFactory.Register<Monster>(); Assert.AreEqual("{id}", uriFactory.GetUriTemplateValue<Monster>()); }
public void ShouldCreateAbsoluteUriForRegisteredClass() { var uriFactory = new UriFactory(); uriFactory.Register<OrderForm>(); Assert.AreEqual(new Uri("http://localhost:8080/virtual-directory/order-form/1"), uriFactory.CreateAbsoluteUri<OrderForm>(new Uri("http://localhost:8080/virtual-directory/"), "1")); }
public void ShouldCreateRelativeUriForRegisteredClass() { var uriFactory = new UriFactory(); uriFactory.Register<OrderForm>(); Assert.AreEqual(new Uri("order-form/1", UriKind.Relative), uriFactory.CreateRelativeUri<OrderForm>("1")); }
public void ShouldReturnRoutePrefixForRegisteredClass() { var uriFactory = new UriFactory(); uriFactory.Register<OrderForm>(); Assert.AreEqual("order-form", uriFactory.GetRoutePrefix<OrderForm>()); }
public void ShouldAllowRegistrationByPassingTypeToRegisterMethod() { var uriFactory = new UriFactory(); uriFactory.Register(typeof(Quote)); uriFactory.Register(typeof(OrderForm)); Assert.AreEqual(new Uri("http://restbucks.com/quote/1234"), uriFactory.CreateAbsoluteUri<Quote>(new Uri("http://restbucks.com"), 1234)); Assert.AreEqual(new Uri("order-form/1234", UriKind.Relative), uriFactory.CreateRelativeUri<OrderForm>(1234)); Assert.AreEqual(new Uri("http://restbucks.com/"), uriFactory.CreateBaseUri<Quote>(new Uri("http://restbucks.com/quote/1234"))); }
public void ShouldAllowRegistrationByPassingTypeToRegisterMethod() { var uriFactory = new UriFactory(); uriFactory.Register(typeof(Treasure)); uriFactory.Register(typeof(Monster)); Assert.AreEqual(new Uri("http://restinpractice.com/treasures/1234"), uriFactory.CreateAbsoluteUri<Treasure>(new Uri("http://restinpractice.com"), 1234)); Assert.AreEqual(new Uri("monsters/1234", UriKind.Relative), uriFactory.CreateRelativeUri<Monster>(1234)); Assert.AreEqual(new Uri("http://restinpractice.com/"), uriFactory.CreateBaseUri<Treasure>(new Uri("http://restinpractice.com/treasures/1234"))); }
protected void Application_Start(object sender, EventArgs e) { XmlConfigurator.Configure(); Log.Debug("Starting Restbucks.Quoting.Service..."); var formsIntegrityUtility = new FormsIntegrityUtility(Signature.Instance, OrderForm.SignedFormPlaceholder); Action<Collection<HttpOperationHandler>> handlers = c => c.Add(new FormsIntegrityResponseHandler(formsIntegrityUtility)); var configuration = HttpHostConfiguration.Create() .SetResourceFactory( (type, ctx, message) => { Log.DebugFormat("Getting instance of type [{0}].", type.FullName); return container.GetService(type); }, (ctx, service) => { if (service is IDisposable) { Log.DebugFormat("Calling Dispose() on instance of type [{0}].", service.GetType().FullName); ((IDisposable) service).Dispose(); } }) .AddFormatters(RestbucksMediaType.Formatter) .AddResponseHandlers(handlers, (endpoint, operation) => operation.DeclaringContract.ContractType.Equals(typeof (OrderForm))); var uriFactory = new UriFactory(); var resources = new ResourceCollection(Assembly.GetExecutingAssembly()); resources.ForEach(r => { container.Register(Component.For(r.Type).LifeStyle.Transient); uriFactory.Register(r.Type); RouteTable.Routes.MapServiceRoute(r.Type, r.UriTemplate.RoutePrefix, configuration); Log.DebugFormat("Registered resource. Type: [{0}]. Prefix: [{1}]. UriTemplate: [{2}].", r.Type.Name, r.UriTemplate.RoutePrefix, r.UriTemplate.UriTemplateValue); }); container.Register(Component.For(typeof (IQuotationEngine)).ImplementedBy(typeof (QuotationEngine)).LifeStyle.Singleton); container.Register(Component.For(typeof (IDateTimeProvider)).ImplementedBy(typeof (DateTimeProvider)).LifeStyle.Singleton); container.Register(Component.For(typeof (IGuidProvider)).ImplementedBy(typeof (GuidProvider)).LifeStyle.Singleton); container.Register(Component.For(typeof (UriFactory)).Instance(uriFactory).LifeStyle.Singleton); }
/// <summary> /// Replace the Family document in the collection. /// </summary> /// <param name="databaseName">The name/ID of the database.</param> /// <param name="collectionName">The name/ID of the collection.</param> /// <param name="updatedFamily">The family document to be replaced.</param> /// <returns>The Task for asynchronous execution.</returns> private async Task ReplaceFamilyDocument(string databaseName, string collectionName, Family updatedFamily) { await this.client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(databaseName, collectionName, updatedFamily.Id), updatedFamily); this.WriteToConsoleAndPromptToContinue("Replaced Family [{0},{1}]", updatedFamily.LastName, updatedFamily.Id); }
public void ShouldReturnUriTemplateValueForRegisteredType() { var uriFactory = new UriFactory(); uriFactory.Register<OrderForm>(); Assert.AreEqual("{id}", uriFactory.GetUriTemplateValueFor(typeof (OrderForm))); }
public RequestForQuote(UriFactory uriFactory) { this.uriFactory = uriFactory; }
public async Task UpdateDocumentAsync <T>(T document) { await client.UpsertDocumentAsync(UriFactory.CreateDocumentCollectionUri(databaseId, typeof(T).Name), document); }
public async Task RunStoredProcedure(string databaseName, string collectionName, User user) { await client.ExecuteStoredProcedureAsync <string>(UriFactory.CreateStoredProcedureUri(databaseName, collectionName, "UpdateOrderTotal"), new RequestOptions { PartitionKey = new PartitionKey(user.UserId) }); Console.WriteLine("Stored procedure complete"); }
public static Uri CreateCustomerDocumentUri(Guid customerId) { return(UriFactory.CreateDocumentUri(CustomerDatabaseId, CustomerCollectionId, customerId.ToString())); }
public DocumentDbRepository() { _client = new DocumentClient(new Uri(EndpointUri), PrimaryKey); _collectionLink = UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId); }
public async Task <Document> UpdateItemAsync(string id, T item) { return(await _client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(_databaseId, _collectionId, id), item)); }
public async Task DeleteItemAsync(string id) { await _client.DeleteDocumentAsync(UriFactory.CreateDocumentUri(_databaseId, _collectionId, id)); }
public static async Task <Document> CreateItemAsync(T item) { return(await client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(dbId, CollectionId), item)); }
public async Task <Document> CreateItemAsync(T item) { return(await _client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(_databaseId, _collectionId), item)); }
/// <summary> /// Gets the value of the function in the given Evaluation Context for the given Binding ID /// </summary> /// <param name="context">Evaluation Context</param> /// <param name="bindingID">Binding ID</param> /// <returns></returns> public IValuedNode Evaluate(SparqlEvaluationContext context, int bindingID) { ILiteralNode input = (ILiteralNode)this.CheckArgument(this._expr, context, bindingID); IValuedNode start = this.CheckArgument(this._start, context, bindingID, XPathFunctionFactory.AcceptNumericArguments); if (this._end != null) { IValuedNode end = this.CheckArgument(this._end, context, bindingID, XPathFunctionFactory.AcceptNumericArguments); if (input.Value.Equals(String.Empty)) { return(new StringNode(null, String.Empty, UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeString))); } try { int s = Convert.ToInt32(start.AsInteger()); int e = Convert.ToInt32(end.AsInteger()); if (s < 0) { s = 0; } if (e < s) { // If no/negative characters are being selected the empty string is returned return(new StringNode(null, String.Empty, UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeString))); } else if (s > input.Value.Length) { // If the start is after the end of the string the empty string is returned return(new StringNode(null, String.Empty, UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeString))); } else { if (e > input.Value.Length) { // If the end is greater than the length of the string the string from the starts onwards is returned return(new StringNode(null, input.Value.Substring(s), UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeString))); } else { // Otherwise do normal substring return(new StringNode(null, input.Value.Substring(s, e - s), UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeString))); } } } catch { throw new RdfQueryException("Unable to convert the Start/End argument to an Integer"); } } else { if (input.Value.Equals(String.Empty)) { return(new StringNode(null, String.Empty, UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeString))); } try { int s = Convert.ToInt32(start.AsInteger()); if (s < 0) { s = 0; } return(new StringNode(null, input.Value.Substring(s), UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeString))); } catch { throw new RdfQueryException("Unable to convert the Start argument to an Integer"); } } }
/// <summary> /// Run the get started demo for Azure Cosmos DB. This creates a database, collection, two documents, executes a simple query /// and cleans up. /// </summary> /// <returns>The Task for asynchronous completion.</returns> private async Task GetStartedDemo() { // Create a new instance of the DocumentClient this.client = new DocumentClient(new Uri(EndpointUri), PrimaryKey); Database databaseInfo = new Database { Id = "FamilyDB_og" }; await this.client.CreateDatabaseIfNotExistsAsync(databaseInfo); DocumentCollection collectionInfo = new DocumentCollection(); collectionInfo.Id = "FamilyCollection_og"; // We choose LastName as the partition key since we're storing family information. Data is seamlessly scaled out based on the last name of // the inserted entity. collectionInfo.PartitionKey.Paths.Add("/LastName"); // Optionally, you can configure the indexing policy of a collection. Here we configure collections for maximum query flexibility // including string range queries. collectionInfo.IndexingPolicy = new IndexingPolicy(new RangeIndex(DataType.String) { Precision = -1 }); // Collections can be reserved with throughput specified in request units/second. 1 RU is a normalized request equivalent to the read // of a 1KB document. Here we create a collection with 400 RU/s. await this.client.CreateDocumentCollectionIfNotExistsAsync( UriFactory.CreateDatabaseUri(databaseInfo.Id), collectionInfo, new RequestOptions { OfferThroughput = 400 }); // Insert a document, here we create a Family object Family andersenFamily = new Family { Id = "Andersen.1", LastName = "Andersen", Parents = new Parent[] { new Parent { FirstName = "Thomas" }, new Parent { FirstName = "Mary Kay" } }, Children = new Child[] { new Child { FirstName = "Henriette Thaulow", Gender = "female", Grade = 5, Pets = new Pet[] { new Pet { GivenName = "Fluffy" } } } }, Address = new Address { State = "WA", County = "King", City = "Seattle" }, IsRegistered = true }; await this.CreateFamilyDocumentIfNotExists("FamilyDB_og", "FamilyCollection_og", andersenFamily); Family wakefieldFamily = new Family { Id = "Wakefield.7", LastName = "Wakefield", Parents = new Parent[] { new Parent { FamilyName = "Wakefield", FirstName = "Robin" }, new Parent { FamilyName = "Miller", FirstName = "Ben" } }, Children = new Child[] { new Child { FamilyName = "Merriam", FirstName = "Jesse", Gender = "female", Grade = 8, Pets = new Pet[] { new Pet { GivenName = "Goofy" }, new Pet { GivenName = "Shadow" } } }, new Child { FamilyName = "Miller", FirstName = "Lisa", Gender = "female", Grade = 1 } }, Address = new Address { State = "NY", County = "Manhattan", City = "NY" }, IsRegistered = false }; await this.CreateFamilyDocumentIfNotExists("FamilyDB_og", "FamilyCollection_og", wakefieldFamily); this.ExecuteSimpleQuery("FamilyDB_og", "FamilyCollection_og"); // Update the Grade of the Andersen Family child andersenFamily.Children[0].Grade = 6; await this.ReplaceFamilyDocument("FamilyDB_og", "FamilyCollection_og", andersenFamily); this.ExecuteSimpleQuery("FamilyDB_og", "FamilyCollection_og"); // Delete the document await this.DeleteFamilyDocument("FamilyDB_og", "FamilyCollection_og", "Andersen", "Andersen.1"); // Clean up/delete the database and client await this.client.DeleteDatabaseAsync(UriFactory.CreateDatabaseUri("FamilyDB_og")); }
/// <summary> /// Delete the Family document in the collection. /// </summary> /// <param name="databaseName">The name/ID of the database.</param> /// <param name="collectionName">The name/ID of the collection.</param> /// <param name="partitionKey">The partition key of the document.</param> /// <param name="documentKey">The document key of the document.</param> /// <returns>The Task for asynchronous execution.</returns> private async Task DeleteFamilyDocument(string databaseName, string collectionName, string partitionKey, string documentKey) { await this.client.DeleteDocumentAsync(UriFactory.CreateDocumentUri(databaseName, collectionName, documentKey), new RequestOptions { PartitionKey = new PartitionKey(partitionKey) }); Console.WriteLine("Deleted Family [{0},{1}]", partitionKey, documentKey); }
public async Task <Document> CreateAsync(TDocument document) { return(await client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId), document)); }
public async Task CreateCollection() { await DocumentDbClient.CreateDocumentCollectionIfNotExistsAsync( UriFactory.CreateDatabaseUri(_configurationService.DocumentDb.Database), new DocumentCollection { Id = _configurationService.DocumentDb.Collection }); }
/// <summary> /// Creates a new RDFa Evaluation Context /// </summary> /// <param name="baseUri">Base URI</param> public RdfAEvaluationContext(Uri baseUri) { this._baseUri = baseUri; this._nsmapper.AddNamespace(String.Empty, UriFactory.Create(RdfAParser.XHtmlVocabNamespace)); }
/// <summary> /// Creates a new Time span node /// </summary> /// <param name="g">Graph</param> /// <param name="value">Time Span</param> public TimeSpanNode(IGraph g, TimeSpan value) : this(g, value, XmlConvert.ToString(value), UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeDuration)) { }
/// <summary> /// Serializes the Optimisers Configuration /// </summary> /// <param name="context">Serialization Context</param> public void SerializeConfiguration(ConfigurationSerializationContext context) { context.EnsureObjectFactory(typeof(FullTextObjectFactory)); INode optObj = context.NextSubject; context.Graph.Assert(optObj, context.Graph.CreateUriNode(UriFactory.Create(RdfSpecsHelper.RdfType)), context.Graph.CreateUriNode(UriFactory.Create(ConfigurationLoader.ClassAlgebraOptimiser))); context.Graph.Assert(optObj, context.Graph.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyType)), context.Graph.CreateLiteralNode(this.GetType().FullName + ", dotNetRDF.Query.FullText")); if (this._provider is IConfigurationSerializable) { INode searcherObj = context.Graph.CreateBlankNode(); context.NextSubject = searcherObj; ((IConfigurationSerializable)this._provider).SerializeConfiguration(context); context.Graph.Assert(optObj, context.Graph.CreateUriNode(UriFactory.Create(FullTextHelper.PropertySearcher)), searcherObj); } else { throw new DotNetRdfConfigurationException("Unable to serialize configuration for this Full Text Optimiser as the Search Provider used does not implement the required IConfigurationSerializable interface"); } }
/// <summary> /// Creates a new Time span node /// </summary> /// <param name="g">Graph</param> /// <param name="value">Time Span</param> /// <param name="lexicalValue">Lexical value</param> public TimeSpanNode(IGraph g, TimeSpan value, String lexicalValue) : this(g, value, lexicalValue, UriFactory.Create(XmlSpecsHelper.XmlSchemaDataTypeDuration)) { }
public void ThrowsExceptionIfTryingToCreateAbsoluteUriForEntryWithoutRegisteredType() { var uriFactory = new UriFactory(); uriFactory.CreateAbsoluteUri<OrderForm>(new Uri("http://localhost:8080/virtual-directory/"), "1"); }
public Quotes(UriFactory uriFactory, IQuotationEngine quotationEngine) { this.uriFactory = uriFactory; this.quotationEngine = quotationEngine; }
private async Task BasicOperations() { this.client = new DocumentClient(new Uri(ConfigurationManager.AppSettings["accountEndpoint"]), ConfigurationManager.AppSettings["accountKey"]); await this.client.CreateDatabaseIfNotExistsAsync(new Database { Id = "Users" }); await this.client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri("Users"), new DocumentCollection { Id = "WebCustomers" }); Console.WriteLine("Database and collection validation complete"); User yanhe = new User { Id = "1", UserId = "yanhe", LastName = "He", FirstName = "Yan", Email = "*****@*****.**", OrderHistory = new OrderHistory[] { new OrderHistory { OrderId = "1000", DateShipped = "08/17/2018", Total = "52.49" } }, ShippingPreference = new ShippingPreference[] { new ShippingPreference { Priority = 1, AddressLine1 = "90 W 8th St", City = "New York", State = "NY", ZipCode = "10001", Country = "USA" } }, }; await this.CreateUserDocumentIfNotExists("Users", "WebCustomers", yanhe); User nelapin = new User { Id = "2", UserId = "nelapin", LastName = "Pindakova", FirstName = "Nela", Email = "*****@*****.**", Dividend = "8.50", OrderHistory = new OrderHistory[] { new OrderHistory { OrderId = "1001", DateShipped = "08/17/2018", Total = "105.89" } }, ShippingPreference = new ShippingPreference[] { new ShippingPreference { Priority = 1, AddressLine1 = "505 NW 5th St", City = "New York", State = "NY", ZipCode = "10001", Country = "USA" }, new ShippingPreference { Priority = 2, AddressLine1 = "505 NW 5th St", City = "New York", State = "NY", ZipCode = "10001", Country = "USA" } }, Coupons = new CouponsUsed[] { new CouponsUsed { CouponCode = "Fall2018" } } }; // await this.CreateUserDocumentIfNotExists("Users", "WebCustomers", nelapin); // yanhe.LastName = "Suh"; // await this.ReplaceUserDocument("Users", "WebCustomers", yanhe); // await this.ReadUserDocument("Users", "WebCustomers", yanhe); // this.ExecuteSimpleQuery("Users", "WebCustomers"); // await this.DeleteUserDocument("Users", "WebCustomers", yanhe); await this.RunStoredProcedure("Users", "WebCustomers", yanhe); }
public void ThrowsExceptionIfTryingToCreateRelativeUriForEntryWithoutRegisteredType() { var uriFactory = new UriFactory(); uriFactory.CreateRelativeUri<Monster>("1"); }
public async Task DeleteAsync(string id) { await client.DeleteDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id)); }
public void ThrowsExceptionIfTryingToGetUriTemplateValueForEntryWithoutRegisteredType() { var uriFactory = new UriFactory(); uriFactory.GetUriTemplateValue<Monster>(); }
public EntryPoint(UriFactory uriFactory) { this.uriFactory = uriFactory; }
public void ThrowsExceptionWhenTryingToGetUriTemplateValueForTypeThatHasNotBeenRegistered() { var uriFactory = new UriFactory(); uriFactory.GetUriTemplateValueFor(typeof (Monster)); }
/// <summary> /// Internal method which generates the RDF/Json Output for a Graph /// </summary> /// <param name="g">Graph to save</param> /// <param name="output">Stream to save to</param> private void GenerateOutput(IGraph g, TextWriter output) { //Always force RDF Namespace to be correctly defined g.NamespaceMap.Import(this._defaultNamespaces); g.NamespaceMap.AddNamespace("rdf", UriFactory.Create(NamespaceMapper.RDF)); //Create our Writer Context and start the XML Document RdfXmlWriterContext context = new RdfXmlWriterContext(g, output); context.CompressionLevel = this._compressionLevel; context.UseDtd = this._useDTD; context.UseAttributes = this._useAttributes; context.Writer.WriteStartDocument(); if (context.UseDtd) { //Create the DOCTYPE declaration StringBuilder entities = new StringBuilder(); String uri; entities.Append('\n'); foreach (String prefix in context.NamespaceMap.Prefixes) { uri = context.NamespaceMap.GetNamespaceUri(prefix).AbsoluteUri; if (!uri.Equals(context.NamespaceMap.GetNamespaceUri(prefix).ToString())) { context.UseDtd = false; break; } if (!prefix.Equals(String.Empty)) { entities.AppendLine("\t<!ENTITY " + prefix + " '" + uri + "'>"); } } if (context.UseDtd) { context.Writer.WriteDocType("rdf:RDF", null, null, entities.ToString()); } } //Create the rdf:RDF element context.Writer.WriteStartElement("rdf", "RDF", NamespaceMapper.RDF); if (context.Graph.BaseUri != null) { context.Writer.WriteAttributeString("xml", "base", null, context.Graph.BaseUri.AbsoluteUri); } //Add all the existing Namespace Definitions here context.NamespaceMap.IncrementNesting(); foreach (String prefix in context.NamespaceMap.Prefixes) { if (prefix.Equals("rdf")) { continue; } if (!prefix.Equals(String.Empty)) { context.Writer.WriteStartAttribute("xmlns", prefix, null); context.Writer.WriteString(context.NamespaceMap.GetNamespaceUri(prefix).AbsoluteUri);//Uri.EscapeUriString(context.NamespaceMap.GetNamespaceUri(prefix).AbsoluteUri)); context.Writer.WriteEndAttribute(); } else { context.Writer.WriteStartAttribute("xmlns"); context.Writer.WriteString(context.NamespaceMap.GetNamespaceUri(prefix).AbsoluteUri);//Uri.EscapeUriString(context.NamespaceMap.GetNamespaceUri(prefix).AbsoluteUri)); context.Writer.WriteEndAttribute(); } } //Find the Collections and Type References if (context.CompressionLevel >= WriterCompressionLevel.More) { WriterHelper.FindCollections(context, CollectionSearchMode.All); } //Get the Triples as a Sorted List List <Triple> ts = context.Graph.Triples.Where(t => !context.TriplesDone.Contains(t)).ToList(); ts.Sort(new RdfXmlTripleComparer()); INode lastSubj = null; List <Triple> sameSubject = new List <Triple>(); for (int i = 0; i < ts.Count; i++) { //Find the first group of Triples with the same subject if (lastSubj == null) { //Start of new set of Triples with the same subject lastSubj = ts[i].Subject; sameSubject.Add(ts[i]); if (lastSubj.NodeType == NodeType.GraphLiteral) { throw new RdfOutputException(WriterErrorMessages.GraphLiteralsUnserializable("RDF/XML")); } else if (lastSubj.NodeType == NodeType.Variable) { throw new RdfOutputException(WriterErrorMessages.VariableNodesUnserializable("RDF/XML")); } } else { if (ts[i].Subject.Equals(lastSubj)) { //Still finding Triples with same subject sameSubject.Add(ts[i]); } else { //Found the end of current set of Triples with same subject this.GenerateSubjectOutput(context, sameSubject, true); //Reset so we'll start from a new subject on next iteration sameSubject.Clear(); lastSubj = null; i--; } } } //Ensure last set of Triples with same subject gets written if (sameSubject.Count > 0) { this.GenerateSubjectOutput(context, sameSubject, true); } //Take care of any collections that weren't yet written foreach (KeyValuePair <INode, OutputRdfCollection> kvp in context.Collections) { if (!kvp.Value.HasBeenWritten) { //Generate a rdf:Description node and then write the collection context.Writer.WriteStartElement("rdf", "Description", NamespaceMapper.RDF); if (kvp.Value.Triples.Count > 0 || !kvp.Value.IsExplicit) { context.Writer.WriteAttributeString("rdf", "nodeID", NamespaceMapper.RDF, context.BlankNodeMapper.GetOutputID(((IBlankNode)kvp.Key).InternalID)); } this.GenerateCollectionOutput(context, kvp.Key); context.Writer.WriteEndElement(); } } context.NamespaceMap.DecrementNesting(); context.Writer.WriteEndDocument(); //Save to the Output Stream context.Writer.Flush(); context.Writer.Close(); }
public ActionResult <IEnumerable <Payment> > Get() { var query = _client.CreateDocumentQuery <Payment>(UriFactory.CreateDocumentCollectionUri("popops", "paymentdetails")); return(Ok(query)); }
public void ThrowsExceptionIfTryingToCreateBaseUriForEntryWithoutRegisteredType() { var uriFactory = new UriFactory(); uriFactory.CreateBaseUri<Monster>(new Uri("http://localhost:8080/virtual-directory/monsters/1")); }
private void GenerateSubjectOutput(RdfXmlWriterContext context, List <Triple> ts, bool allowRdfDescription) { //If nothing to do return if (ts.Count == 0) { return; } context.NamespaceMap.IncrementNesting(); //First off determine what the XML Element should be //If there is a rdf:type triple then create a typed node //Otherwise create a rdf:Description node INode rdfType = context.Graph.CreateUriNode(UriFactory.Create(RdfSpecsHelper.RdfType)); Triple typeTriple = ts.FirstOrDefault(t => t.Predicate.Equals(rdfType) && t.Object.NodeType == NodeType.Uri); INode subj; if (typeTriple != null) { //Create Typed Node subj = typeTriple.Subject; //Generate the Type Reference creating a temporary namespace if necessary UriRefType outType; IUriNode typeNode = (IUriNode)typeTriple.Object; String uriref = this.GenerateUriRef(context, typeNode.Uri, UriRefType.QName, out outType); if (outType != UriRefType.QName) { //Need to generate a temporary namespace and try generating a QName again String tempPrefix, tempUri; this.GenerateTemporaryNamespace(context, typeNode, out tempPrefix, out tempUri); uriref = this.GenerateUriRef(context, typeNode.Uri, UriRefType.QName, out outType); if (outType != UriRefType.QName) { if (allowRdfDescription) { //Still couldn't generate a QName so fall back to rdf:Description //Note that in this case we don't remove the typeTriple from those to be written as we still need to //write it later context.Writer.WriteStartElement("rdf", "Description", NamespaceMapper.RDF); } else { throw new RdfOutputException(WriterErrorMessages.UnreducablePropertyURIUnserializable); } } else { if (uriref.Contains(':')) { //Type Node in relevant namespace context.Writer.WriteStartElement(uriref.Substring(0, uriref.IndexOf(':')), uriref.Substring(uriref.IndexOf(':') + 1), tempUri); } else { //Type Node in default namespace context.Writer.WriteStartElement(uriref); } ts.Remove(typeTriple); context.TriplesDone.Add(typeTriple); } //Remember to define the temporary namespace on the current element context.Writer.WriteAttributeString("xmlns", tempPrefix, null, Uri.EscapeUriString(tempUri)); } else { //Generated a valid QName if (uriref.Contains(':')) { //Create an element with appropriate namespace String ns = context.NamespaceMap.GetNamespaceUri(uriref.Substring(0, uriref.IndexOf(':'))).AbsoluteUri; context.Writer.WriteStartElement(uriref.Substring(0, uriref.IndexOf(':')), uriref.Substring(uriref.IndexOf(':') + 1), ns); } else { //Create an element in default namespace context.Writer.WriteStartElement(uriref); } context.TriplesDone.Add(typeTriple); ts.Remove(typeTriple); } } else { subj = ts.First().Subject; if (allowRdfDescription) { //Create rdf:Description Node context.Writer.WriteStartElement("rdf", "Description", NamespaceMapper.RDF); } else { throw new RdfOutputException(WriterErrorMessages.UnreducablePropertyURIUnserializable); } } //Always remember to add rdf:about or rdf:nodeID as appropriate if (subj.NodeType == NodeType.Uri) { context.Writer.WriteAttributeString("rdf", "about", NamespaceMapper.RDF, subj.ToString());//Uri.EscapeUriString(subj.ToString())); } else { //Can omit the rdf:nodeID if nesting level is > 2 i.e. not a top level subject node if (context.NamespaceMap.NestingLevel <= 2) { context.Writer.WriteAttributeString("rdf", "nodeID", NamespaceMapper.RDF, context.BlankNodeMapper.GetOutputID(((IBlankNode)subj).InternalID)); } } //If use of attributes is enabled we'll encode triples with simple literal objects //as attributes on the subject node directly if (context.UseAttributes) { //Next find any simple literals we can attach directly to the Subject Node List <Triple> simpleLiterals = new List <Triple>(); HashSet <INode> simpleLiteralPredicates = new HashSet <INode>(); foreach (Triple t in ts) { if (t.Object.NodeType == NodeType.Literal) { ILiteralNode lit = (ILiteralNode)t.Object; if (lit.DataType == null && lit.Language.Equals(String.Empty)) { if (!simpleLiteralPredicates.Contains(t.Predicate)) { simpleLiteralPredicates.Add(t.Predicate); simpleLiterals.Add(t); } } } } //Now go ahead and attach these to the Subject Node as attributes this.GenerateSimpleLiteralAttributes(context, simpleLiterals); simpleLiterals.ForEach(t => context.TriplesDone.Add(t)); simpleLiterals.ForEach(t => ts.Remove(t)); } //Then generate Predicate Output for each remaining Triple foreach (Triple t in ts) { this.GeneratePredicateOutput(context, t); context.TriplesDone.Add(t); } //Also check for the rare case where the subject is the key to a collection if (context.Collections.ContainsKey(subj)) { OutputRdfCollection collection = context.Collections[subj]; if (!collection.IsExplicit) { this.GenerateCollectionItemOutput(context, collection); collection.HasBeenWritten = true; } } context.Writer.WriteEndElement(); context.NamespaceMap.DecrementNesting(); }
public void ThrowsExceptionIfTryingToGetRoutePrefixForEntryWithoutRegisteredType() { var uriFactory = new UriFactory(); uriFactory.GetRoutePrefix<Monster>(); }
public async Task <CueStack> GetCueStack(string cueStackId) => await _documentClient.ReadDocumentAsync <CueStack>( UriFactory.CreateDocumentUri( _cueDatabaseOptions.Value.DatabaseName, CueDatabaseCollections.CueStacks, cueStackId));
public void ThrowsExceptionIfTypeIsNotAttributedWithUriTemplateAttribute() { var uriFactory = new UriFactory(); uriFactory.Register<string>(); }
/// <summary> /// Caches the user permission. /// </summary> /// <returns>The user permission.</returns> /// <param name="permissionToken">Permission token.</param> private async Task CacheUserPermission(PermissionToken permissionToken) { permissionToken.Id = permissionToken.UserId + "permission"; await Client.UpsertDocumentAsync(UriFactory.CreateDocumentCollectionUri(databaseId, collectionId), permissionToken); }
public void WhenPassingGuidAsUriTemplateParameterShouldRemoveAllDashes() { var uriFactory = new UriFactory(); uriFactory.Register<Monster>(); Assert.AreEqual(new Uri("monsters/00000000000000000000000000000000", UriKind.Relative), uriFactory.CreateRelativeUri<Monster>(Guid.Empty)); }
/// <summary> /// Gets the new permission. /// </summary> /// <returns>The new permission.</returns> /// <param name="userId">User identifier.</param> private async Task <PermissionToken> GetNewPermission(string userId) { Permission permission = null; try { Uri url = UriFactory.CreatePermissionUri(databaseId, userId, permissionId); permission = await Client.ReadPermissionAsync(UriFactory.CreatePermissionUri(databaseId, userId, permissionId)); } catch (DocumentClientException e) { if (e.StatusCode == System.Net.HttpStatusCode.NotFound) { DocumentCollection collection = await Client.ReadDocumentCollectionAsync(UriFactory.CreateDocumentCollectionUri(databaseId, collectionId)); Permission p = new Permission { PermissionMode = PermissionMode.All, ResourceLink = collection.SelfLink, ResourcePartitionKey = new PartitionKey(userId), Id = permissionId // Needs to be unique for a given user }; await CreateUserIfNotExistsAsync(userId); permission = await Client.CreatePermissionAsync(UriFactory.CreateUserUri(databaseId, userId), p); } else { throw e; } } var expires = Convert.ToInt32(DateTime.UtcNow.Subtract(BeginningOfTime).TotalSeconds) + 3600; // expires in 1h return(new PermissionToken() { Token = permission.Token, Expires = expires, UserId = userId }); }
public async Task <HttpStatusCode> CreateDatabaseAsync() { var response = HttpStatusCode.OK; var databaseResponse = await _client.CreateDatabaseIfNotExistsAsync(new Database { Id = _config.DatabaseName }); if (databaseResponse.StatusCode == HttpStatusCode.Created) { response = HttpStatusCode.Created; } var documentCollection = new DocumentCollection { Id = _config.CollectionName }; var collectionResponse = await _client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri(_config.DatabaseName), documentCollection); if (collectionResponse.StatusCode == HttpStatusCode.Created) { response = HttpStatusCode.Created; } return(response); }
/// <summary> /// Launch the RDF export wizard and save resulting RDF file to disk. /// </summary> public void ExportRDF() { // Generate candidate list of namespaces to map, for the export dialog to consume candidateNamespacesToMap = new HashSet <Uri>(); foreach (Worksheet worksheet in Globals.ThisAddIn.Application.Worksheets) { int lastUsedColumnIndex = worksheet.UsedRange.Columns.Count; string lastUsedColumnName = Helper.GetExcelColumnName(lastUsedColumnIndex); Range headerRange = worksheet.get_Range(String.Format("A1:{0}1", lastUsedColumnName)); candidateNamespacesToMap.UnionWith(Helper.getNamespaceUrisFromComments(headerRange)); } ExportOptionsForm exportOptionsForm = new ExportOptionsForm(); if (exportOptionsForm.ShowDialog() == DialogResult.OK) { // Set up save file UI SaveFileDialog saveRdfFileDialog = new SaveFileDialog(); saveRdfFileDialog.Filter = "RDF/XML (*.rdf)|*.rdf|Turtle (*.ttl)|*.ttl|NTriples (*.nt)|*.nt"; saveRdfFileDialog.Title = "Save RDF file"; if (saveRdfFileDialog.ShowDialog() == DialogResult.OK) { // Initiate DotNetRdf Graph and shared IRI:s IGraph g = new Graph(); IUriNode rdfType = g.CreateUriNode(UriFactory.Create(RdfSpecsHelper.RdfType)); // Assign namespace mappings from export dialog foreach (KeyValuePair <string, Uri> entry in exportPrefixMappings) { g.NamespaceMap.AddNamespace(entry.Key, entry.Value); } // Used to trim URI:s Char[] trimUrisChars = new Char[] { '<', '>' }; // Iterate over all worksheets foreach (Worksheet worksheet in Globals.ThisAddIn.Application.Worksheets) { // Which bits of the sheet are being used Range usedRange = worksheet.UsedRange; int lastUsedRow = usedRange.Row + usedRange.Rows.Count - 1; int lastUsedColumn = usedRange.Column + usedRange.Columns.Count - 1; // Identifier column metadata int identifierColumn = 0; // Class name is tentatively in the data namespace until the identifier column is found Uri className = new Uri(exportNamespace.ToString() + worksheet.Name); // Set up lookup table. Note that we use 1-indexing to simplify mapping to/from Excel // ranges. The 0:th column will thus be empty and should not be adressed, as will the // identifier column. HeaderFields[] headerLookupTable = new HeaderFields[lastUsedColumn + 1]; // Parse the header row. string lastUsedColumnName = Helper.GetExcelColumnName(lastUsedColumn); Range headerRange = worksheet.get_Range(String.Format("A1:{0}1", lastUsedColumnName)); foreach (Range headerCell in headerRange.Cells) { int column = headerCell.Column; // If there is an embedded note, proceed if (headerCell.Comment != null) { string noteText = headerCell.Comment.Text(Type.Missing, Type.Missing, Type.Missing); string[] noteTextComponents = noteText.Split('\n'); string iriComponent = noteTextComponents[0]; if (iriComponent.Equals("<IRI>") && noteTextComponents.Count() == 2) { // This is the identifier column; update worksheet metadata accordingly identifierColumn = headerCell.Column; string classComponent = noteTextComponents[1]; string classComponentTrimmed = classComponent.Trim(trimUrisChars); className = new Uri(classComponentTrimmed); } else if (noteTextComponents.Count() == 3) { HeaderFields hf = new HeaderFields(); hf.propertyIri = g.CreateUriNode(UriFactory.Create(iriComponent.Trim(trimUrisChars))); string propertyTypeComponent = noteTextComponents[1]; hf.propertyType = new Uri(propertyTypeComponent.Trim(trimUrisChars)); string propertyRangeComponent = noteTextComponents[2]; hf.propertyRange = new Uri(propertyRangeComponent.Trim(trimUrisChars)); headerLookupTable[column] = hf; } else if (noteTextComponents.Count() == 6) { HeaderFields hf = new HeaderFields(); hf.propertyIri = g.CreateUriNode(UriFactory.Create(iriComponent.Trim(trimUrisChars))); string propertyTypeComponent = noteTextComponents[1]; hf.propertyType = new Uri(propertyTypeComponent.Trim(trimUrisChars)); string propertyRangeComponent = noteTextComponents[2]; hf.propertyRange = new Uri(propertyRangeComponent.Trim(trimUrisChars)); string nestedIriComponent = noteTextComponents[3]; hf.nestedIri = g.CreateUriNode(UriFactory.Create(nestedIriComponent.Trim(trimUrisChars))); string nestedTypeComponent = noteTextComponents[4]; hf.nestedType = new Uri(nestedTypeComponent.Trim(trimUrisChars)); string nestedRangeComponent = noteTextComponents[5].Trim(trimUrisChars); if (nestedRangeComponent.Length > 0) { hf.nestedRange = new Uri(nestedRangeComponent); } headerLookupTable[column] = hf; } } } // Now, assuming an identifier column has been found, we can finally start parsing the rows if (identifierColumn != 0) { // All entities will have the same class IUriNode worksheetClass = g.CreateUriNode(className); // For every row in the spreadsheet.. for (int rowIndex = 2; rowIndex <= lastUsedRow; rowIndex++) { string rowRangeIdentifier = String.Format("{0}{1}:{2}{3}", Helper.GetExcelColumnName(1), rowIndex, Helper.GetExcelColumnName(lastUsedColumn), rowIndex); Range row = worksheet.get_Range(rowRangeIdentifier); // Set subject node ID. string identifierCellIdentifier = String.Format("{0}{1}", Helper.GetExcelColumnName(identifierColumn), rowIndex); Range identifierCell = worksheet.get_Range(identifierCellIdentifier); // Used to store the references to any intermediate (nested) blank nodes for the row Dictionary <IUriNode, IBlankNode> intermediateNodes = new Dictionary <IUriNode, IBlankNode>(); // Only parse rows that have an identifier if (identifierCell.Text != "") { Uri subjectUri = new Uri(exportNamespace.ToString() + identifierCell.Text); IUriNode subjectNode = g.CreateUriNode(subjectUri); g.Assert(new Triple(subjectNode, rdfType, worksheetClass)); // Iterate over remaining columns, i.e., property instances, skipping the identifier column if it reappears foreach (Range dataCell in row.Cells) { if (dataCell.Column == identifierColumn) { continue; } // Get header fields HeaderFields hf = headerLookupTable[dataCell.Column]; // Check that there actually are header fields for the cell under consideration; otherwise, ignore cell // This is not a simple null check since HeaderFields is a struct, e.g., value type, which cannot be null if (hf.Equals(default(HeaderFields))) { continue; } if (hf.nestedIri != null) { // This is a nested anonymous individual // Assert the intermediate (nested) individual IUriNode predicateNode = hf.propertyIri; IBlankNode intermediateBlank; if (intermediateNodes.ContainsKey(predicateNode)) { intermediateBlank = intermediateNodes[predicateNode]; } else { intermediateBlank = g.CreateBlankNode(); intermediateNodes.Add(predicateNode, intermediateBlank); } IUriNode intermediateType = g.CreateUriNode(hf.propertyRange); g.Assert(new Triple(subjectNode, predicateNode, intermediateBlank)); g.Assert(new Triple(intermediateBlank, rdfType, intermediateType)); IUriNode nestedPredicateNode = hf.nestedIri; // Get out and parse object. // "Raw" cell value, will need treatment (TODO!) INode objectNode; string cellValue = dataCell.Text; // Check so cell isn't empty if (!cellValue.Equals("")) { switch (hf.nestedType.ToString()) { case OntologyHelper.OwlDatatypeProperty: objectNode = g.CreateLiteralNode(cellValue, hf.nestedRange); break; case OntologyHelper.OwlObjectProperty: // If there is a valid URI in the cell, use that as-is, otherwise generate one frame the export namespace if (Uri.TryCreate(cellValue, UriKind.Absolute, out Uri tempObjectPropertyValue) == true) { objectNode = g.CreateUriNode(tempObjectPropertyValue); } else { objectNode = g.CreateUriNode(new Uri(exportNamespace.ToString() + cellValue)); } break; case OntologyHelper.OwlAnnotationProperty: // For annotation properties we use literal object nodes if property range is in XSD namespace // and uri nodes otherwise. if (hf.nestedRange.ToString().Contains(XmlSpecsHelper.NamespaceXmlSchema)) { objectNode = g.CreateLiteralNode(cellValue, hf.nestedRange); } else { // If there is a valid URI in the cell, use that as-is, otherwise generate one frame the export namespace if (Uri.TryCreate(cellValue, UriKind.Absolute, out Uri tempAnnotationPropertyValue) == true) { objectNode = g.CreateUriNode(tempAnnotationPropertyValue); } else { objectNode = g.CreateUriNode(new Uri(exportNamespace.ToString() + cellValue)); } } break; default: continue; } g.Assert(new Triple(intermediateBlank, nestedPredicateNode, objectNode)); } } else { IUriNode predicateNode = hf.propertyIri; // Get out and parse object. // "Raw" cell value, will need treatment (TODO!) INode objectNode; string cellValue = dataCell.Text; // Check so cell isn't empty if (!cellValue.Equals("")) { switch (hf.propertyType.ToString()) { case OntologyHelper.OwlDatatypeProperty: objectNode = g.CreateLiteralNode(cellValue, hf.propertyRange); break; case OntologyHelper.OwlObjectProperty: // If there is a valid URI in the cell, use that as-is, otherwise generate one frame the export namespace if (Uri.TryCreate(cellValue, UriKind.Absolute, out Uri tempObjectPropertyValue) == true) { objectNode = g.CreateUriNode(tempObjectPropertyValue); } else { objectNode = g.CreateUriNode(new Uri(exportNamespace.ToString() + cellValue)); } break; case OntologyHelper.OwlAnnotationProperty: // For annotation properties we use literal object nodes if property range is in XSD namespace // and uri nodes otherwise. if (hf.propertyRange.ToString().Contains(XmlSpecsHelper.NamespaceXmlSchema)) { objectNode = g.CreateLiteralNode(cellValue, hf.propertyRange); } else { // If there is a valid URI in the cell, use that as-is, otherwise generate one frame the export namespace if (Uri.TryCreate(cellValue, UriKind.Absolute, out Uri tempAnnotationPropertyValue) == true) { objectNode = g.CreateUriNode(tempAnnotationPropertyValue); } else { objectNode = g.CreateUriNode(new Uri(exportNamespace.ToString() + cellValue)); } } break; default: continue; } g.Assert(new Triple(subjectNode, predicateNode, objectNode)); } } } } } String saveFileExtension = Path.GetExtension(saveRdfFileDialog.FileName); IRdfWriter writer = MimeTypesHelper.GetWriterByFileExtension(saveFileExtension); writer.Save(g, saveRdfFileDialog.FileName); } } } } }
async Task IDatabase.DeleteAsync <T>(string id) { // build the document's self link for the fastest query var selflink = UriFactory.CreateDocumentUri(_databaseId, _collectionId, id); await _documentClient.DeleteDocumentAsync(selflink).ConfigureAwait(false); }
public static Uri CreateDocumentUri(Guid addressId) { return(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, addressId.ToString())); }
public void ThrowsExceptionIfEntryAlreadyExistsForType() { var uriFactory = new UriFactory(); uriFactory.Register<Monster>(); uriFactory.Register<Monster>(); }
public OrderForm(UriFactory uriFactory, IQuotationEngine quotationEngine) { this.uriFactory = uriFactory; this.quotationEngine = quotationEngine; }