public override KeyedResourceInstance GetSingleResourceByKey(KeyExpression keyExpression) { if (keyExpression.Properties.OfType <ResourceProperty>().Where(rp => rp.Type.ClrType.Equals(typeof(DateTime))).Count() > 0) { UriQueryBuilder uriQueryBuilder = new UriQueryBuilder(this, this.ServiceUri); _workaroundDateTimeQuery = uriQueryBuilder.Build(Query.From( Exp.Variable(keyExpression.ResourceContainer)) .Where(keyExpression) .Select()); } KeyedResourceInstance o = null; try { o = SocketExceptionHandler.Execute <KeyedResourceInstance>( () => GetSingleResourceByKeyBase(keyExpression)); } catch (Microsoft.OData.Client.DataServiceQueryException exc) { if (exc.Response.StatusCode != 404) { throw exc; } // if DSV is not present, its not an Astoria-level error if (!exc.Response.Headers.ContainsKey("OData-Version")) { throw exc; } } return(o); }
private static void VerifyLinksPayload(Workspace w, CommonPayload payload, LinqQueryBuilder linqBuilder) { ArrayList expectedEntities = CommonPayload.CreateList(linqBuilder.QueryResult); if (payload == null) { AstoriaTestLog.AreEqual(expectedEntities.Count, 0, "Unexpected null $ref payload"); } else { KeyExpressions expectedKeys = new KeyExpressions(); foreach (object o in expectedEntities) { KeyExpression keyExp = w.CreateKeyExpressionFromProviderObject(o); expectedKeys.Add(keyExp); } List <string> linksFound = new List <string>(); if (payload.Resources == null) { linksFound.Add(payload.Value); } else { foreach (PayloadObject o in (payload.Resources as List <PayloadObject>)) { if (o.PayloadProperties.Any(p => p.Name == "uri")) { linksFound.Add((o["uri"] as PayloadSimpleProperty).Value); } } } AstoriaTestLog.AreEqual(expectedKeys.Count, linksFound.Count, "Number of expected entities does not match number of links found"); foreach (string link in linksFound) { KeyExpression match = null; foreach (KeyExpression expectedKey in expectedKeys) { if (compareKeyURI(link, expectedKey)) { match = expectedKey; break; } } if (match != null) { expectedKeys.Remove(match); } else { AstoriaTestLog.WriteLineIgnore("Unexpected URI: '" + link + "'"); AstoriaTestLog.FailAndThrow("Unexpected URI found in $ref payload"); } } } }
public static KeyedResourceInstance CreateKeyedResourceInstance(KeyExpression exp, ResourceContainer container, params ResourceInstanceProperty[] properties) { ResourceType resType = exp.Properties.OfType <ResourceProperty>().First().ResourceType; ResourceInstanceKey instanceKey = ResourceInstanceKey.ConstructResourceInstanceKey(exp); return(new KeyedResourceInstance(instanceKey, properties)); }
public static ResourceInstanceProperty CreateRefInstanceProperty(KeyExpression keyExp, ResourceContainer container, ResourceProperty navProperty) { ResourceType navResourceType = navProperty.Type as ResourceType; ResourceInstanceKey resourceInstanceKey = ResourceInstanceKey.ConstructResourceInstanceKey(keyExp); return(new ResourceInstanceNavRefProperty(navProperty.Name, new AssociationResourceInstance(resourceInstanceKey, AssociationOperation.Add))); }
/// <summary> /// Implements IDataInserter.AddEntity by creating a POST-based insert request and adding it to the batch queue /// </summary> /// <param name="key">Key expression for new entity</param> /// <param name="entity">Update tree for new entity</param> public void AddEntity(KeyExpression key, KeyedResourceInstance entity) { // build the request // ExpNode containerQuery = ContainmentUtil.BuildCanonicalQuery(key, true); AstoriaRequest request = workspace.CreateRequest(containerQuery, entity, RequestVerb.Post); // set ETagHeaderExpected appropriately if (key.ResourceType.Properties.Any(p => p.Facets.ConcurrencyModeFixed)) { request.ETagHeaderExpected = true; } // add it to the queue // queue.Add(request); // store the content-id // contentIDMap[entity] = request.Headers["Content-ID"]; // fire the event // if (this.OnAddingEntity != null) { OnAddingEntity(key, entity); } }
/// <summary> /// Implements IDataInserter.AddEntity by generating a IUpdatable.CreateResource call and multiple IUpdatable.SetValue calls /// </summary> /// <param name="key">Key expression for new entity</param> /// <param name="entity">Update tree for new entity</param> public void AddEntity(KeyExpression key, KeyedResourceInstance entity) { // generate a variable name for this entity and save it // int entityID = entityIDs.Count; entityIDs[entity] = entityID; string entityObjectName = "entity" + entityID; // code-gen the CreateResource and SetValue calls // code.AppendLine("//Adding entity"); foreach (string line in WriteObject(entityObjectName, entity)) { code.AppendLine(line); } code.AppendLine(entityListName + ".Add(" + entityObjectName + ");"); code.AppendLine(string.Empty); // Fire the event // if (this.OnAddingEntity != null) { OnAddingEntity(key, entity); } // ensure that a later Flush/Close will write the SaveChanges call changesSaved = false; }
//--------------------------------------------------------------------- // Constructs AstoriaRequest and sets. //--------------------------------------------------------------------- private BlobsRequest(Workspace w, SerializationFormatKind format, RequestVerb verb, string uri, HttpStatusCode expectedStatusCode) : base(w) { // Common settings for MLEs and MRs. base.IsBlobRequest = true; base.Verb = verb; base.ExpectedStatusCode = expectedStatusCode; // Construct request URI. if (uri.Contains("(*)")) { // Replace (*) with random key. string relativeURI = uri.Remove(0, w.ServiceUri.Length + 1); ResourceContainer container = w.ServiceContainer.ResourceContainers[relativeURI.Substring(0, relativeURI.IndexOf("(*)"))]; KeyExpression key = null; try { key = w.GetRandomExistingKey(container, container.BaseType); } catch (Exception e) { AstoriaTestLog.Skip("Unable to get random key"); } base.Query = ContainmentUtil.BuildCanonicalQuery(key); base.URI += relativeURI.Substring(relativeURI.IndexOf("(*)") + 3); } else { // Deterministic URI. base.URI = uri; } LastURI = base.URI; }
//Constructor public PredicateModel(Workspace w, ResourceContainer container, ResourceProperty p, KeyExpression parentKey, ResourceType resType) { _resourceContainer = container; _workspace = w; _resType = resType; _key = parentKey; _prop = p; }
public AstoriaRequest PrimitiveProperty(out ResourceContainer container, out KeyExpression keyExp, out ResourceProperty property) { container = _workspace.ServiceContainer.ResourceContainers.Choose(); keyExp = _workspace.GetRandomExistingKey(container); property = container.BaseType.Properties.OfType <ResourceProperty>().Where(p => !p.IsNavigation && !p.IsComplexType).Choose(); return(PrimitiveProperty(container, keyExp, property)); }
public AstoriaRequest EntitySetNavProp(ResourceContainer container, KeyExpression keyExp, ResourceProperty property) { ExpNode q = Query.From( Exp.Variable(container)) .Where(keyExp) .Nav(property.Property()); return(_workspace.CreateRequest(q)); }
public AstoriaRequest SingleEntityKeyedTopLevel(ResourceContainer container, KeyExpression keyExp) { ExpNode q = Query.From( Exp.Variable(container)) .Where(keyExp) .Select(); return(_workspace.CreateRequest(q)); }
public AstoriaRequest SingleEntityKeyedNavProp(ResourceContainer container, KeyExpression keyExp, ResourceProperty property) { ExpNode q = Query.From( Exp.Variable(container)) .Where(keyExp) .Select(new PropertyExpression(property, false)); return(_workspace.CreateRequest(q)); }
public AstoriaRequest PrimitivePropertyValue(ResourceContainer container, KeyExpression keyExp, ResourceProperty property) { ExpNode q = Query.From( Exp.Variable(container)) .Where(keyExp) .Select(new PropertyExpression(property, true)); return(_workspace.CreateRequest(q)); }
// gets the path down to the set containing the given keyexpression public static List <AccessPathSegment> BuildAccessPath(KeyExpression keyExp, bool requireCanonical) { // grab all the canonical path attributes IEnumerable <ContainmentAttribute> attributes; if (requireCanonical) { attributes = GetContainmentAttributes(keyExp, ca => ca.Canonical); } else { attributes = GetContainmentAttributes(keyExp); } // now we need to link them together, first by getting the SINGLE canonical path attribute with the current // resource container as the child, and moving up List <AccessPathSegment> path = new List <AccessPathSegment>(); ResourceContainer current = keyExp.ResourceContainer; bool done = !attributes.Any(); while (!done) { IEnumerable <ContainmentAttribute> applicable = attributes.Where(ca => ca.ChildContainer == current); if (!applicable.Any()) { done = true; } else { ContainmentAttribute att = applicable.Where(ca => ca.Canonical).FirstOrDefault(); if (att == null) { att = applicable.FirstOrDefault(); } if (att == null || (att.TopLevelAccess && !requireCanonical)) { done = true; } else { AccessPathSegment segment = new AccessPathSegment(); segment.Attribute = att; keyExp = att.GetContainingKey(keyExp); segment.ParentKey = keyExp; path.Add(segment); current = att.ParentContainer; } } } path.Reverse(); return(path); }
public static string CreateKeyString(KeyExpression keyExp, bool binaryFormat) { Workspace w = keyExp.ResourceContainer.Workspace; UriQueryBuilder builder = new UriQueryBuilder(w, w.ServiceUri); builder.UseBinaryFormatForDates = binaryFormat; builder.CleanUpSpecialCharacters = true; return(builder.CreateKeyString(keyExp)); }
public AstoriaRequest Links(out ResourceContainer container, out KeyExpression keyExp, out ResourceProperty property) { container = _workspace.ServiceContainer.ResourceContainers .Where(c => c.ResourceTypes.Any(rt => rt.Properties.OfType <ResourceProperty>().Any(p => p.IsNavigation && p.Type is CollectionType))).Choose(); keyExp = _workspace.GetRandomExistingKey(container); property = container.BaseType.Properties.OfType <ResourceProperty>().Where(p => p.IsNavigation && p.Type is CollectionType).Choose(); return(Links(container, keyExp, property)); }
protected void QueryNavProperty(Func <IEdmEntityType, List <string> > getNavPropsLambda) { ForEachResourceType( (resourceType, resourceContainer, workspace) => { CreateContext(resourceType, workspace); AstoriaTestLog.WriteLine("Querying entityset {0}", resourceContainer.Name); IEdmEntityType entityType = DataServiceMetadata.EntityTypes.FirstOrDefault(eType => eType.Name == resourceType.Name); KeyExpression keyExp = workspace.GetRandomExistingKey(resourceContainer); if (keyExp != null && (!(resourceContainer is ServiceOperation))) { List <KVP> keyExpValues = WebDataCtxWrapper.ConvertKeyExpression(keyExp); foreach (string collNavProperty in getNavPropsLambda(entityType)) { AstoriaTestLog.WriteLine("Querying Properties {0}", collNavProperty); try { DataServiceQuery queryWithExpand = ((DataServiceQuery)CurrentContext.CreateQueryOfT(resourceContainer.Name, resourceType.ClientClrType)).Where(keyExpValues); //.SelectNavigationProperty(collNavProperty) as DataServiceQuery; IEnumerator enumerateQueryResults = ((IQueryable)queryWithExpand).GetEnumerator(); object entity = null; if (enumerateQueryResults.MoveNext()) { entity = enumerateQueryResults.Current; } while (enumerateQueryResults.MoveNext()) { ; } Uri entityUri = null; CurrentContext.UnderlyingContext.TryGetUri(entity, out entityUri); CurrentContext.Detach(entity); entityUri = new Uri(entityUri.OriginalString + "/" + collNavProperty); var qoREsponse = CurrentContext.ExecuteOfT(GetResourceType(collNavProperty, resourceType).ClientClrType, entityUri); IEnumerator enumerator = qoREsponse.GetEnumerator(); while (enumerator.MoveNext()) { ; } if (ChainedFunction != null) { ChainedFunction(); } } catch (System.Reflection.TargetInvocationException tiException) { if (!tiException.ToString().Contains("Sequence Contains")) { throw tiException; } } } } }, false); }
public string CreateKeyString(KeyExpression keyExp) { System.Collections.Generic.List <string> names = new System.Collections.Generic.List <string>(); System.Collections.Generic.List <object> values = new System.Collections.Generic.List <object>(); foreach (KeyValuePair <PropertyExpression, ConstantExpression> pair in keyExp.EnumerateIncludedPairs()) { names.Add(pair.Key.Name); values.Add(pair.Value.Value.ClrValue); } return(CreateKeyString(names.ToArray(), values.ToArray())); }
private string BuildKeyExpressionXml(KeyExpression keyExpression) { StringBuilder sbKeyExpression = new StringBuilder(); for (int propertyIndex = 0; propertyIndex < keyExpression.Properties.Length; propertyIndex++) { sbKeyExpression.AppendFormat("<ArithmeticExpression><Equal><Left><PropertyExpression>{0}</PropertyExpression></Left><Right><ConstantExpression><Type>{1}</Type><Value>{2}</Value></ConstantExpression></Right></Equal></ArithmeticExpression>", keyExpression.Properties[propertyIndex].Name, keyExpression.Values[propertyIndex].ClrValue.GetType().FullName, keyExpression.Values[propertyIndex].ClrValue.ToString() ); } return(sbKeyExpression.ToString()); }
public static AstoriaRequest BuildGet(Workspace workspace, KeyExpression key, HttpStatusCode expectedStatusCode, SerializationFormatKind format) { QueryNode query = ContainmentUtil.BuildCanonicalQuery(key); string keyString = UriQueryBuilder.CreateKeyString(key, false); if ((expectedStatusCode == System.Net.HttpStatusCode.OK) && (keyString.Contains("/") || keyString.Contains(Uri.EscapeDataString("/")))) { expectedStatusCode = System.Net.HttpStatusCode.BadRequest; } return(BuildGet(workspace, query, expectedStatusCode, format)); }
public static KeyedResourceInstance CreateKeyedResourceInstanceByClone(ResourceContainer container, ResourceType resourceType, bool excludeRelationships) { Workspace workspace = container.Workspace; //Clone for an existing resource, and update its key KeyExpression keyExpression = workspace.GetRandomExistingKey(container, resourceType); if (keyExpression == null) { return(null); } KeyedResourceInstance dataObject = workspace.GetSingleResourceByKey(keyExpression); if (dataObject == null) { return(null); } ResourceInstanceKey key = null; // if there are any non-server-generated key properties, then we need to build the key if (keyExpression.ResourceType.Properties.Any(p => p.PrimaryKey != null && !p.Facets.ServerGenerated)) { ResourceType newResourceType = container.ResourceTypes.Where(rt => rt.Name == dataObject.TypeName).FirstOrDefault(); key = CreateUniqueKey(container, newResourceType); } //Foreach property in dataObject create a ResourceProperty List <ResourceInstanceProperty> properties = new List <ResourceInstanceProperty>(); properties.AddRange(dataObject.Properties.OfType <ResourceInstanceSimpleProperty>().ToArray()); properties.AddRange(dataObject.Properties.OfType <ResourceInstanceComplexProperty>().ToArray()); if (!excludeRelationships) { properties.AddRange(CloneRequiredRelationships(container, keyExpression.ResourceType, keyExpression)); } KeyedResourceInstance keyResourceInstance = null; if (key != null) { keyResourceInstance = new KeyedResourceInstance(key, properties.ToArray()); } else { keyResourceInstance = new KeyedResourceInstance(dataObject.ResourceSetName, dataObject.TypeName, properties.ToArray()); } return(keyResourceInstance); }
public static ResourceInstanceKey ConstructResourceInstanceKey(KeyExpression keyExpression) { List <ResourceInstanceSimpleProperty> keyProperties = new List <ResourceInstanceSimpleProperty>(); for (int i = 0; i < keyExpression.Properties.Count(); i++) { NodeProperty p = keyExpression.Properties.ElementAt(i); NodeValue nodeVal = keyExpression.Values.ElementAt(i); keyProperties.Add(new ResourceInstanceSimpleProperty(p.Name, nodeVal.ClrValue)); } ResourceInstanceKey instanceKey = new ResourceInstanceKey(keyExpression.ResourceContainer, keyExpression.ResourceType, keyProperties.ToArray()); return(instanceKey); }
protected void QueryExpandProperty(Func <IEdmEntityType, List <string> > getNavPropsLambda) { ForEachResourceType( (resourceType, resourceContainer, workspace) => { CreateContext(resourceType, workspace); AstoriaTestLog.WriteLine("Querying entityset {0}", resourceContainer.Name); IEdmEntityType entityType = DataServiceMetadata.EntityTypes.FirstOrDefault(eType => eType.Name == resourceType.Name); KeyExpression keyExp = workspace.GetRandomExistingKey(resourceContainer); if (keyExp != null) { List <KVP> keyExpValues = WebDataCtxWrapper.ConvertKeyExpression(keyExp); foreach (string collNavProperty in getNavPropsLambda(entityType)) { AstoriaTestLog.WriteLine("Expanding Properties {0}", collNavProperty); try { DataServiceQuery queryWithExpand = ((DataServiceQuery)CurrentContext.CreateQueryOfT(resourceContainer.Name, resourceType.ClientClrType)).Where(keyExpValues).Expand(collNavProperty); IEnumerator enumerateQueryResults = ((IQueryable)queryWithExpand).GetEnumerator(); try { while (enumerateQueryResults.MoveNext()) { ; } } catch (OptimisticConcurrencyException oException) { AstoriaTestLog.WriteLineIgnore("Failed as per Expand causes etags not to be included." + oException.Message); } if (ChainedFunction != null) { ChainedFunction(); } } catch (System.Reflection.TargetInvocationException tiException) { if (!tiException.ToString().Contains("Sequence Contains")) { throw tiException; } } } } }, false); }
public virtual void Where() { AstoriaTestLog.WriteLineIgnore("Calling Where"); //Sub model - projections PredicateModel model = new PredicateModel(this.Workspace, this.ResContainer, this.property, this.ParentRelKey, this.ResType); ModelEngine engine = new ModelEngine(this.Engine, model); engine.Run(); ExpNode e = model.Result; this.ParentRelKey = e as KeyExpression; if (null == _parentKey) { /* no keys for resource type*/ this.Reload(); return; } int i = this.Engine.Options.Random.Next(0, 10); if (i % 7 == 0) { e = ((KeyExpression)e).Predicate; bFilter = true; } if (e != null) { if (_query is ScanExpression) { _query = ((ScanExpression)_query).Where(e) as PredicateExpression; } else if (_query is NavigationExpression) { _query = ((NavigationExpression)_query).Where(e) as PredicateExpression; } bWhere = true; IsKey = true; _action = LastAction.Where; AstoriaTestLog.WriteLineIgnore(".Where()"); } }
public static AstoriaRequest BuildDelete(Workspace workspace, KeyExpression toDelete, HttpStatusCode expectedStatusCode, SerializationFormatKind format) { QueryNode query = ContainmentUtil.BuildCanonicalQuery(toDelete); AstoriaRequest request = workspace.CreateRequest(); request.Verb = RequestVerb.Delete; request.Query = query; request.Format = format; request.ExpectedStatusCode = expectedStatusCode; if (toDelete.ResourceType.Properties.Any(p => p.Facets.ConcurrencyModeFixed)) { request.Headers[ConcurrencyUtil.IfMatchHeader] = toDelete.ETag; } return(request); }
private List <KeyExpression> GetContainingKeys(KeyExpression keyExpression) { List <KeyExpression> keys = new List <KeyExpression>(); // reverse the segments, and generate keys for each parent type KeyExpression currentKey = keyExpression; keys.Add(currentKey); segments.Reverse(); foreach (ContainmentQuerySegment segment in segments) { currentKey = segment.attribute.GetContainingKey(currentKey, segment.abbreviateChild); keys.Add(currentKey); } segments.Reverse(); keys.Reverse(); return(keys); }
public static KeyExpression GetContainingKey(this ContainmentAttribute att, KeyExpression childKey, ResourceType parentType, bool abbreviate) { AstoriaTestLog.Compare(childKey.ResourceContainer == att.ChildContainer, String.Format("ChildKey does not belong to expected set (Expected '{0}', got '{1}'", att.ChildContainer.Name, childKey.ResourceContainer.Name)); List <PropertyExpression> parentProperties = new List <PropertyExpression>(); List <ConstantExpression> parentValues = new List <ConstantExpression>(); foreach (NodeProperty p_prop in att.ParentContainer.BaseType.Key.Properties) { string c_name; if (!att.KeyMapping.TryGetValue(p_prop.Name, out c_name)) { AstoriaTestLog.FailAndThrow(String.Format("Parent key property {0} does not appear in derived key mapping", p_prop.Name)); } // need to get the offset now int c_offset = 0; for (; c_offset < childKey.Properties.Length; c_offset++) { if (childKey.Properties[c_offset].Name == c_name) { break; } } if (c_offset >= childKey.Properties.Length) { AstoriaTestLog.FailAndThrow(String.Format("Could not find property '{0}' in child key", c_name)); } NodeProperty c_prop = childKey.Properties[c_offset]; parentProperties.Add(p_prop.Property()); parentValues.Add(new ConstantExpression(childKey.Values[c_offset])); if (abbreviate) { childKey.IncludeInUri[c_offset] = false; } } return(new KeyExpression(att.ParentContainer, parentType, parentProperties.ToArray(), parentValues.ToArray())); }
internal static ResourceInstanceKey CreateUniqueKey(ResourceContainer container, ResourceType resType, KeyExpressions relatedForeignKeys, KeyExpressions existingKeys) { KeyExpressions possibleRelatedForeignKeys = new KeyExpressions(); Workspace workspace = container.Workspace; int keysGenerated = 0; bool keyTrying = true; ResourceInstanceKey resourceInstanceKey = null; do { possibleRelatedForeignKeys = new KeyExpressions(); resourceInstanceKey = TryCreateUniqueResourceInstanceKey(container, resType, possibleRelatedForeignKeys); KeyExpression keyExpression = resourceInstanceKey.CreateKeyExpression(container, resType); // need to make sure its not a duplicate // if (existingKeys == null) { KeyedResourceInstance o = workspace.GetSingleResourceByKey(keyExpression); if (o == null) { keyTrying = false; } } else { keyTrying = existingKeys.Contains(keyExpression); } keysGenerated++; if (keysGenerated > 25) { throw new Microsoft.Test.ModuleCore.TestFailedException("Unable to create a unique key"); } }while (keyTrying); relatedForeignKeys.Add(possibleRelatedForeignKeys); return(resourceInstanceKey); }
protected string CreateCanonicalUri(ResourceInstanceKey key) { UriQueryBuilder builder = new UriQueryBuilder(Workspace, Workspace.ServiceUri); builder.UseBinaryFormatForDates = false; builder.CleanUpSpecialCharacters = false; KeyExpression keyExpression = ResourceInstanceUtil.ConvertToKeyExpression(key, Workspace); if (keyExpression != null) { QueryNode query = ContainmentUtil.BuildCanonicalQuery(keyExpression); return(builder.Build(query)); } IEnumerable <ResourceInstanceSimpleProperty> properties = key.KeyProperties.OfType <ResourceInstanceSimpleProperty>(); string keyString = builder.CreateKeyString(properties.Select(p => p.Name).ToArray(), properties.Select(p => p.PropertyValue).ToArray()); string uri = Workspace.ServiceUri + "/" + key.ResourceSetName + "(" + keyString + ")"; return(uri); }
public override bool Equals(object obj) { KeyExpression keyExp = obj as KeyExpression; if (keyExp == null) { return(false); } ResourceProperty[] resProperties = keyExp.Properties.OfType <ResourceProperty>().ToArray(); ResourceProperty[] thisResProperties = keyExp.Properties.OfType <ResourceProperty>().ToArray(); if (resProperties.Length != thisResProperties.Length) { return(false); } if (this.Values.Length != keyExp.Values.Length) { return(false); } if (this.IncludeInUri.Length != keyExp.IncludeInUri.Length) { return(false); } for (int i = 0; i < keyExp.Values.Length; i++) { if (!this.Values[i].ClrValue.Equals(keyExp.Values[i].ClrValue)) { return(false); } if (!resProperties[i].Name.Equals(thisResProperties[i].Name)) { return(false); } if (this.IncludeInUri[i] != keyExp.IncludeInUri[i]) { return(false); } } return(true); }