Ejemplo n.º 1
0
        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());
        }
Ejemplo n.º 2
0
 //Constructor
 public PredicateModel(Workspace w,ResourceContainer container, ResourceProperty p, KeyExpression parentKey, ResourceType resType)
 {
     _resourceContainer = container;
     _workspace = w;
     _resType = resType;
     _key = parentKey;
     _prop = p;
 }
        private IMappedExpression BuildField(Type type, ref int index, ref IEnumerable <Type> types)
        {
//      if (type.IsOfGenericType(typeof (Ref<>))) {
//        var entityType = type.GetGenericType(typeof (Ref<>)).GetGenericArguments()[0];
//        TypeInfo typeInfo = model.Types[entityType];
//        KeyInfo keyProviderInfo = typeInfo.KeyInfo;
//        TupleDescriptor keyTupleDescriptor = keyProviderInfo.TupleDescriptor;
//        KeyExpression entityExpression = KeyExpression.Create(typeInfo, index);
//        index += keyTupleDescriptor.Count;
//        types = types.Concat(keyTupleDescriptor);
//        return Expression.Convert(entityExpression, type);
//      }

            if (type.IsSubclassOf(typeof(Entity)))
            {
                TypeInfo          typeInfo           = model.Types[type];
                KeyInfo           keyInfo            = typeInfo.Key;
                TupleDescriptor   keyTupleDescriptor = keyInfo.TupleDescriptor;
                IMappedExpression expression;
                if (isKeyConverter)
                {
                    expression = KeyExpression.Create(typeInfo, index);
                }
                else
                {
                    var entityExpression = EntityExpression.Create(typeInfo, index, true);
                    entityExpression.IsNullable = true;
                    expression = entityExpression;
                }
                index += keyTupleDescriptor.Count;
                types  = types.Concat(keyTupleDescriptor);
                return(expression);
            }

            if (type.IsSubclassOf(typeof(Structure)))
            {
                TypeInfo            typeInfo            = model.Types[type];
                TupleDescriptor     tupleDescriptor     = typeInfo.TupleDescriptor;
                var                 tupleSegment        = new Segment <int>(index, tupleDescriptor.Count);
                StructureExpression structureExpression = StructureExpression.CreateLocalCollectionStructure(typeInfo, tupleSegment);
                index += tupleDescriptor.Count;
                types  = types.Concat(tupleDescriptor);
                return(structureExpression);
            }

            if (TypeIsStorageMappable(type))
            {
                ColumnExpression columnExpression = ColumnExpression.Create(type, index);
                types = types.AddOne(type);
                index++;
                return(columnExpression);
            }

            throw new NotSupportedException();
        }
Ejemplo n.º 4
0
        public override string ToAql()
        {
            string aql = "REMOVE " + KeyExpression.ToAql();

            aql += " IN " + CollectionName;

            if (Options.Count > 0)
            {
                aql += " OPTIONS " + Options.ToString();
            }

            return(aql);
        }
Ejemplo n.º 5
0
        protected override Expression VisitKeyExpression(KeyExpression expression)
        {
            // TODO: http://code.google.com/p/dataobjectsdotnet/issues/detail?id=336
            Expression tupleExpression = Expression.Call(
                GetTupleSegmentMethod,
                GetTupleExpression(expression),
                Expression.Constant(expression.Mapping));

            return(Expression.Call(
                       WellKnownMembers.Key.Create,
                       Expression.Constant(context.Domain),
                       Expression.Property(
                           Expression.Field(itemMaterializationContextParameter, ItemMaterializationContext.SessionFieldInfo),
                           WellKnownMembers.SessionNodeId),
                       Expression.Constant(expression.EntityType),
                       Expression.Constant(TypeReferenceAccuracy.BaseType),
                       tupleExpression));
        }
        public override string ToAql()
        {
            string aql = "REPLACE " + KeyExpression.ToAql();

            if (WithExpression != null)
            {
                aql += " WITH " + WithExpression.ToAql();
            }

            aql += " IN " + CollectionName;

            if (Options.Count > 0)
            {
                aql += " OPTIONS " + Options.ToString();
            }

            return(aql);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Performs the REMOVE operation on a frame stream
        /// </summary>
        public IEnumerable <ExecutionFrame> ApplyToFrameStream(
            QueryExecutor executor,
            IEnumerable <ExecutionFrame> frameStream
            )
        {
            foreach (ExecutionFrame frame in frameStream)
            {
                JsonValue keyResult = KeyExpression.Evaluate(executor, frame);

                // get key & ref
                string key;
                string rev;
                if (keyResult.IsJsonObject)
                {
                    key = keyResult["_key"].AsString;
                    rev = keyResult["_rev"].AsString;
                }
                else
                {
                    key = keyResult.AsString;
                    rev = null;
                }

                // OLD
                JsonObject oldDocument = executor.DataSource.GetDocument(
                    CollectionName,
                    key
                    );

                // remove
                executor.DataSource.RemoveDocument(
                    CollectionName,
                    key,
                    rev,
                    Options
                    );

                // update frame
                yield return(frame
                             .AddVariable("OLD", oldDocument));
            }
        }
        /// <summary>
        /// Performs the REPLACE operation on a frame stream
        /// </summary>
        public IEnumerable <ExecutionFrame> ApplyToFrameStream(
            QueryExecutor executor,
            IEnumerable <ExecutionFrame> frameStream
            )
        {
            foreach (ExecutionFrame frame in frameStream)
            {
                // get key
                JsonValue keyResult = KeyExpression.Evaluate(executor, frame);
                string    key       = keyResult.AsString;
                if (keyResult.IsJsonObject)
                {
                    key = keyResult["_key"].AsString;
                }

                // get document
                JsonObject document = keyResult;
                if (WithExpression != null)
                {
                    document = WithExpression.Evaluate(executor, frame);
                }

                // OLD
                JsonObject oldDocument = executor.DataSource.GetDocument(
                    CollectionName,
                    key
                    );

                // replace & NEW
                JsonObject newDocument = executor.DataSource.ReplaceDocument(
                    CollectionName,
                    key,
                    document,
                    Options
                    );

                // update frame
                yield return(frame
                             .AddVariable("OLD", oldDocument)
                             .AddVariable("NEW", newDocument));
            }
        }
        public static void EnsureKeyExpressionCompatible(this KeyExpression left, KeyExpression right, Expression expressionPart)
        {
            if (left == null || right == null)
            {
                return;
            }

            if (left.EntityType.IsInterface || right.EntityType.IsInterface)
            {
                if (left.EntityType.Key.EqualityIdentifier != right.EntityType.Key.EqualityIdentifier)
                {
                    throw new InvalidOperationException(string.Format(
                                                            Strings.ExKeysOfXAndXNotCompatible, expressionPart.ToString(true), left.EntityType, right.EntityType));
                }
            }
            else
            {
                if (left.EntityType.Hierarchy != right.EntityType.Hierarchy)
                {
                    throw new InvalidOperationException(string.Format(
                                                            Strings.ExEntitiesXAndXBelongToDifferentHierarchies, expressionPart.ToString(true), left.EntityType, right.EntityType));
                }
            }
        }
Ejemplo n.º 10
0
 protected virtual Expression VisitKeyExpression(KeyExpression expression)
 {
     return(expression);
 }
Ejemplo n.º 11
0
        public static AstoriaRequest BuildUpdate(Workspace workspace, KeyExpression modifiedKey, bool replace, HttpStatusCode expectedStatusCode, SerializationFormatKind format)
        {
            if (modifiedKey == null)
                return null;

            ResourceContainer container = modifiedKey.ResourceContainer;
            ResourceType resourceType = modifiedKey.ResourceType;

            if (replace && resourceType.Properties.Any(p => p.Facets.IsIdentity))
                return null;

            string keyString = UriQueryBuilder.CreateKeyString(modifiedKey, false);
            if (expectedStatusCode == HttpStatusCode.NoContent && (keyString.Contains("/") || keyString.Contains(Uri.EscapeDataString("/"))))
                expectedStatusCode = HttpStatusCode.BadRequest;

            QueryNode query = ContainmentUtil.BuildCanonicalQuery(modifiedKey);

            List<ResourceInstanceProperty> properties = new List<ResourceInstanceProperty>();

            string[] propertiesToSkip;
            //Skip because setting the birthdate to a random Datetime won't work due to contraints
            //if (resourceType.Name == "Employees")
            //    propertiesToSkip = new string[] { "BirthDate" };
            ////Skipping because it has some weird constraint on it
            //else if (resourceType.Name == "Order_Details")
            //    propertiesToSkip = new string[] { "Discount" };
            //else
            //    propertiesToSkip = new string[] { };

            foreach (ResourceProperty resourceProperty in resourceType.Properties.OfType<ResourceProperty>()
                .Where(p => !p.IsNavigation
                    && p.PrimaryKey == null
                    && !p.Facets.IsIdentity))
                    //&& !p.IsComplexType
                    //&& !propertiesToSkip.Contains(p.Name)))
            {
                properties.Add(resourceProperty.CreateRandomResourceInstanceProperty());
            }

            if (!properties.Any())
                return null;

            KeyedResourceInstance resourceInstance = new KeyedResourceInstance(
                ResourceInstanceKey.ConstructResourceInstanceKey(modifiedKey),
                properties.ToArray());

            AstoriaRequest request = workspace.CreateRequest();

            request.Verb = replace ? RequestVerb.Put : RequestVerb.Patch;
            request.Query = query;
            request.UpdateTree = resourceInstance;
            request.ExpectedStatusCode = expectedStatusCode;
            request.Format = format;

            if (modifiedKey.ResourceType.Properties.Any(p => p.Facets.ConcurrencyModeFixed))
            {
                request.Headers[ConcurrencyUtil.IfMatchHeader] = modifiedKey.ETag;
                request.ETagHeaderExpected = true;
            }

            return request;
        }
Ejemplo n.º 12
0
 public static AstoriaRequest BuildUpdate(Workspace workspace, ResourceContainer container, ResourceType resourceType,
     bool replace, HttpStatusCode expectedStatusCode, SerializationFormatKind format, out KeyExpression modifiedKey)
 {
     modifiedKey = workspace.GetRandomExistingKey(container, resourceType);
     return BuildUpdate(workspace, modifiedKey, replace, expectedStatusCode, format);
 }
Ejemplo n.º 13
0
 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());
 }
Ejemplo n.º 14
0
        public override KeyedResourceInstance GetSingleResourceByKey(KeyExpression keyExpression)
        {
            ExpNode query = ContainmentUtil.BuildCanonicalQuery(keyExpression);
            AstoriaRequest request = this.CreateRequest(query);

            if (request.URI.Length > 260) // Can't make this request.
                return null;

            AstoriaResponse response = request.GetResponse();

            if (response.ActualStatusCode == HttpStatusCode.NotFound)
                return null;
            else if (response.ActualStatusCode == HttpStatusCode.OK)
            {
                CommonPayload payload = response.CommonPayload;
                if (payload.Resources is List<PayloadObject>)
                {
                    List<PayloadObject> payloadObjects = (List<PayloadObject>)payload.Resources;
                    if (payloadObjects.Count == 1)
                        return ResourceInstanceUtil.CreateKeyedResourceInstanceFromPayloadObject(keyExpression.ResourceContainer, keyExpression.ResourceType, payloadObjects.First());
                    else if (payloadObjects.Count == 0 && keyExpression.ResourceContainer is ServiceOperation)
                    {
                        // we change serviceoperations into $filter requests, so they come back as empty feeds instead of 404s
                        return null;
                    }
                }
            }

            ResponseVerification.LogFailure(response, new TestFailedException("Could not get resource for the given key"));
            return null;
        }
Ejemplo n.º 15
0
        private static List<ResourceInstanceProperty> CloneRequiredRelationships(ResourceContainer container, ResourceType resourceType, KeyExpression keyExpression)
        {
            List<ResourceInstanceProperty> properties = new List<ResourceInstanceProperty>();
            //Foreach Navigation Property in dataObject create a bind 
            Dictionary<ResourceProperty, KeyExpressions> navigationProperties = GetAllAssociatedKeys(container, resourceType, keyExpression);
            foreach (ResourceProperty navProperty in navigationProperties.Keys)
            {
                //ResourceAssociationEnd otherEnd = navProperty.ResourceAssociation.GetOtherEnd(navProperty);
                ResourceType navPropertyResourceType = (navProperty.Type is CollectionType ? (navProperty.Type as CollectionType).SubType : navProperty.Type) as ResourceType;
                ResourceContainer otherContainer = container.FindDefaultRelatedContainer(navProperty);

                bool foreignKeyViolation = false;
                foreach (ResourceProperty otherProperty in otherContainer.BaseType.Key.Properties)
                {
                    if (otherProperty.ForeignKeys.Count() > 0)
                    {
                        ResourceType otherType = otherProperty.ForeignKeys.First().PrimaryKey.Properties.OfType<ResourceProperty>().First().ResourceType;
                        if (otherType == container.BaseType)
                        {
                            foreignKeyViolation = true;
                            break;
                        }
                    }
                }
                if (foreignKeyViolation)
                    continue;

                KeyExpressions keyExpressions = navigationProperties[navProperty];
                if (navProperty.Type is ResourceType)
                {
                    if (keyExpressions.Count > 0)
                    {
                        properties.Add(CreateRefInstanceProperty(keyExpressions[0], otherContainer, navProperty));
                    }
                }
                else
                {
                    ResourceInstanceProperty property = CreateCollectionInstanceProperty(keyExpressions, otherContainer, navProperty);
                    if (property != null)
                    {
                        properties.Add(property);
                    }
                }

            }
            return properties;
        }
Ejemplo n.º 16
0
 public override string ToString()
 {
     return(KeyExpression.ToString() + " : " + ValueExpression.ToString());
 }
Ejemplo n.º 17
0
        public virtual KeyedResourceInstance GetSingleResourceByKey(KeyExpression keyExpression)
        {
            LinqQueryBuilder linqBuilder = new LinqQueryBuilder(this);

            ExpNode query = null;
            if (this.Settings.HasContainment)
                query = ContainmentUtil.BuildCanonicalQuery(keyExpression).Select();
            else
            {
                query = Query.From(
                                 Exp.Variable(keyExpression.ResourceContainer))
                                .Where(keyExpression)
                                .Select();
            }

            IQueryable queryable = this.GetUnderlyingProviderQueryResults(query);
            IEnumerator enumerator = queryable.GetEnumerator();
            enumerator.MoveNext();
            object dataObject = enumerator.Current;

            if (dataObject == null)
                return null;
            return ResourceInstanceUtil.CreateKeyedResourceInstanceByExactClone(keyExpression.ResourceContainer, keyExpression.ResourceType, dataObject);
        }
Ejemplo n.º 18
0
 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);
 }
Ejemplo n.º 19
0
        /// <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);
        }
Ejemplo n.º 20
0
 public virtual KeyExpression GetRandomExistingKey(ResourceContainer resourceContainer, KeyExpression partialKey)
 {
     return this.GetRandomExistingKey(resourceContainer, null, partialKey);
 }
Ejemplo n.º 21
0
        private RowEntityType FindRowInstance(KeyExpression keyExp)
        {
            RowEntityType type = FindRowInstance(keyExp.ResourceContainer.Name,
                keyExp.Properties.Select(p => p.Name).ToList(),
                keyExp.Values.Select(v => v.ClrValue).ToList());

            if (type != null)
                return type;

            throw new TestException(TestResult.Failed, "Could not find row instance for keyExpression: "
               + keyExp.ResourceContainer.Name + "(" + UriQueryBuilder.CreateKeyString(keyExp, false) + ")");
        }
Ejemplo n.º 22
0
 private void DataInserter_HandleAddingEntity(KeyExpression key, KeyedResourceInstance entity)
 {
     AddNewEntity(entity, key.ResourceType);
 }
Ejemplo n.º 23
0
        private bool CreateKeyedResourceInstance(ResourceContainer container, ResourceType resourceType, out KeyExpression key, out KeyedResourceInstance newResource)
        {
            int retryCount = 5;

            if (!_existingKeyMap.Keys.Contains(container))
                _existingKeyMap.Add(container, new KeyExpressions());

            newResource = resourceType.CreateRandomResource(container, new KeyExpressions(), false); // should not make request
            key = newResource.ResourceInstanceKey.CreateKeyExpression(container, resourceType);

            while (_existingKeyMap[container].Contains(key) && retryCount > 0)
            {
                newResource.ResourceInstanceKey = ResourceInstanceUtil.CreateUniqueKey(container, resourceType, new KeyExpressions(), new KeyExpressions());
                key = newResource.ResourceInstanceKey.CreateKeyExpression(container, resourceType);
                retryCount--;
            }

            if (retryCount == 0)
            {
                newResource = null;
                key = null;
                return false;
            }

            _existingKeyMap[container].Add(key);
            _existingEntityMap[key] = newResource;
            return true;
        }
Ejemplo n.º 24
0
        private static bool compareKeyURI(string uriFound, KeyExpression keyExpected)
        {
            UriQueryBuilder builder = new UriQueryBuilder(keyExpected.ResourceContainer.Workspace, keyExpected.ResourceContainer.Workspace.ServiceUri);
            builder.EscapeUriValues = true;
            builder.CleanUpSpecialCharacters = false;
            builder.UseBinaryFormatForDates = false;

            switch (keyExpected.IncludeInUri.Count(i => i))
            {
                case 0:
                    AstoriaTestLog.FailAndThrow("Cannot compare KeyExpression to URI, key has no included values");
                    return false;

                case 1:
                    // TODO: stop ignoring case
                    QueryNode query = ContainmentUtil.BuildCanonicalQuery(keyExpected);
                    string expected = builder.Build(query);

                    expected = expected.Replace(".0f", "f"); //this is kinda a hack, but TypeData.FormatForKey is going to add the .0, so we need to remove it
                    expected = expected.Replace(".0D", "D"); //this is kinda a hack, but TypeData.FormatForKey is going to add the .0, so we need to remove it
                    bool match = uriFound.Equals(expected, StringComparison.InvariantCultureIgnoreCase);
                    if (!match)
                        AstoriaTestLog.WriteLineIgnore("Link did not match key, expected '" + expected + "'");
                    return match;

                default:
                    QueryNode setQuery = ContainmentUtil.BuildCanonicalQuery(keyExpected, true);

                    Workspace w = keyExpected.ResourceContainer.Workspace;
                    string setUri = builder.Build(setQuery);

                    string keySegment = uriFound.Substring(setUri.Length);

                    string expectedKeySegment = "(" + UriQueryBuilder.CreateKeyString(keyExpected, false) + ")";

                    if (keySegment.Equals(expectedKeySegment, StringComparison.InvariantCultureIgnoreCase))
                        return true;

                    // if not explicitely equal, need to make sure its not due to a re-ordering of the properties
                    //
                    List<KeyValuePair<string, int>> predicateLocations = new List<KeyValuePair<string, int>>();
                    for (int i = 0; i < keyExpected.Values.Length; i++)
                    {
                        string predicate = builder.CreateKeyStringPair(keyExpected.Properties[i].Name, keyExpected.Values[i].ClrValue);
                        int offset = keySegment.IndexOf(predicate);
                        if (offset < 0)
                            return false;

                        predicateLocations.Add(new KeyValuePair<string, int>(predicate, offset));
                    }

                    predicateLocations.Sort(delegate(KeyValuePair<string, int> pair1, KeyValuePair<string, int> pair2)
                    {
                        return pair1.Value.CompareTo(pair2.Value);
                    });

                    expectedKeySegment = "(" + String.Join(",", predicateLocations.Select(pair => pair.Key).ToArray()) + ")";

                    return keySegment.Equals(expectedKeySegment, StringComparison.InvariantCultureIgnoreCase);
            }
        }
Ejemplo n.º 25
0
        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()" );
                }
            }
Ejemplo n.º 26
0
        protected virtual KeyExpression GetRandomExistingKey(ResourceContainer resourceContainer, ResourceType resourceType, KeyExpression partialKey)
        {
            LinqQueryBuilder linqBuilder = new LinqQueryBuilder(this);
            QueryNode query = Query.From(Exp.Variable(resourceContainer));

            //TODO: Figure out how to make OfType work with astoria dataquerycontext
            if (resourceType != null && resourceContainer.Workspace.DataLayerProviderKind != DataLayerProviderKind.InMemoryLinq && resourceType.BaseType != null)
            {
                query = query.OfType(resourceType);
            }
            else if (partialKey != null)
            {
                query = query.Where(partialKey);
            }
            query = query.Select().Top(50);

            linqBuilder.Build(query);

            int count = 0;
            KeyExpressions keys = new KeyExpressions();

            IQueryable objects = linqBuilder.QueryResult;
            IEnumerator enumerator = null;
            try
            {
                enumerator = objects.GetEnumerator();
                while (enumerator.MoveNext() && count < 50)
                {
                    if (enumerator.Current != null)
                    {
                        Type t = enumerator.Current.GetType();
                        if (AstoriaTestProperties.EdmObjectLayer == ServiceEdmObjectLayer.PocoWithProxy)
                            t = t.BaseType;
                        List<ResourceType> types = resourceContainer.ResourceTypes.Where(rt => rt.Name.Equals(t.Name) && rt.Namespace.Equals(t.Namespace)).ToList();
                        if (types.Count > 0)
                        {
                            ResourceType actualResourceType = types.Single();

                            if (resourceType != null && resourceType != actualResourceType)
                                continue;

                            KeyExpression keyExp = GetKeyExpression(resourceContainer, actualResourceType, enumerator.Current);
                            //If key is something that has approx value
                            //Then its really a nonfunctional key, excluding it as 
                            //we only want valid keys here
                            if (!keyExp.IsApproxKeyValue())
                            {
                                keys.Add(keyExp);
                                count++;
                            }
                        }
                    }
                }
            }
            finally
            {
                IDisposable disposable = (enumerator as IDisposable);
                if (null != disposable)
                {
                    disposable.Dispose();
                }
            }
            return keys.Choose();
        }
Ejemplo n.º 27
0
 public static bool SpecialChars(KeyExpression keyExp)
 {
     // Workaround unsupported .:'/ in URI
     bool bSpecial = false;
     if (keyExp != null)
     {
         foreach (NodeValue key in keyExp.Values)
         {
             string x = key.ClrValue.ToString();
             if (0 <= x.IndexOfAny(CharsBadRequest) || (key.ClrValue is DateTime))
             {
                 bSpecial = true;
                 break;
             }
         }
         return bSpecial;
     }
     else
         return true;
 }
Ejemplo n.º 28
0
        public virtual KeyExpressions GetExistingAssociatedKeys(ResourceContainer resourceContainer, ResourceProperty property, KeyExpression keyExpression)
        {
            LinqQueryBuilder linqBuilder = new LinqQueryBuilder(this);
            ExpNode query = Query.From(
                                 Exp.Variable(resourceContainer))
                                .Where(keyExpression)
                                .OfType(property.ResourceType)
                                .Nav(new PropertyExpression(property))
                                .Select();

            linqBuilder.Build(query);

            ResourceType associatedType = property.Type as ResourceType;
            if (property.Type is ResourceCollection)
            {
                associatedType = (property.Type as ResourceCollection).SubType as ResourceType;
            }
            IQueryable queryable = linqBuilder.QueryResult;
            KeyExpressions keys = new KeyExpressions();
            IEnumerator enumerator = queryable.GetEnumerator();
            while (enumerator.MoveNext())
            {
                if (enumerator.Current != null)
                {
                    Type t = enumerator.Current.GetType();
                    if (AstoriaTestProperties.EdmObjectLayer == ServiceEdmObjectLayer.PocoWithProxy)
                        t = t.BaseType;

                    IEnumerable<ResourceType> typesWithName = resourceContainer.Workspace.ServiceContainer.ResourceTypes.Where(rt => (t.Name.Equals(rt.Name)));
                    IEnumerable<ResourceType> typesWithNamespace = typesWithName.Where(rt2 => rt2.Namespace == t.Namespace).ToList();
                    ResourceType instanceType = typesWithNamespace.First();
                    ResourceContainer relatedContainer = resourceContainer.FindDefaultRelatedContainer(property);
                    keys.Add(GetKeyExpression(relatedContainer, instanceType, enumerator.Current));
                }
            }
            return keys;
        }
Ejemplo n.º 29
0
 public static AstoriaRequest BuildGet(Workspace workspace, KeyExpression key)
 {
     return BuildGet(workspace, key, HttpStatusCode.OK, SerializationFormatKind.Default);
 }
Ejemplo n.º 30
0
 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));
 }
Ejemplo n.º 31
0
        public KeyedResourceInstance CreateRandomResource(ResourceContainer container, KeyExpression specifiedKey)
        {
            List<ResourceInstanceProperty> properties = new List<ResourceInstanceProperty>();

            foreach (ResourceProperty p in this.Properties.OfType<ResourceProperty>().Where(rp => rp.IsNavigation == false && rp.PrimaryKey == null))
            {
                ResourceInstanceProperty property = p.CreateRandomResourceInstanceProperty();
                properties.Add(property);
            }

            return ResourceInstanceUtil.CreateKeyedResourceInstance(specifiedKey, container, properties.ToArray());
        }
Ejemplo n.º 32
0
        public static Dictionary<ResourceProperty, KeyExpressions> GetAllAssociatedKeys(ResourceContainer container, ResourceType resourceType, KeyExpression keyExpression)
        {
            Workspace workspace = container.Workspace;
            Dictionary<ResourceProperty, KeyExpressions> listOfKeyExpressions = new Dictionary<ResourceProperty, KeyExpressions>();

            foreach (ResourceProperty resourceProperty in resourceType.Properties)
            {
                if (resourceProperty.IsNavigation)
                {
                    KeyExpressions keys = workspace.GetExistingAssociatedKeys(container, resourceProperty, keyExpression);
                    listOfKeyExpressions.Add(resourceProperty, keys);
                }
            }
            return listOfKeyExpressions;
        }
Ejemplo n.º 33
0
 protected override Expression VisitKeyExpression(KeyExpression k)
 {
     AddColumns(k, k.Mapping.GetItems());
     return(k);
 }
Ejemplo n.º 34
0
        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);
        }
Ejemplo n.º 35
0
        public static AstoriaRequest BuildDelete(Workspace workspace, KeyExpressions existingKeys, HttpStatusCode expectedStatusCode, SerializationFormatKind format, out KeyExpression deletedKey)
        {
            deletedKey = existingKeys.Choose();
            if (deletedKey == null)
            {
                AstoriaTestLog.WriteLine("Cannot build DELETE request, no existing keys");
                return null;
            }
            existingKeys.Remove(deletedKey);

            return BuildDelete(workspace, deletedKey, expectedStatusCode, format);
        }
Ejemplo n.º 36
0
        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);
        }
Ejemplo n.º 37
0
        public override KeyExpressions GetExistingAssociatedKeys(ResourceContainer resourceContainer, ResourceProperty property, KeyExpression keyExpression)
        {
            bool pageSizeChanged = false;
            int originalPageSize = this.DataService.ConfigSettings.GetEntitySetPageSize(resourceContainer.Name);
            if (originalPageSize < 1000)
            {
                pageSizeChanged = true;
                this.DataService.ConfigSettings.SetEntitySetPageSize(resourceContainer.Name, 100000);
            }

            ExpNode query = ContainmentUtil.BuildCanonicalQuery(keyExpression).Nav(property.Property()).Select();

            AstoriaRequest request = this.CreateRequest(query);

            AstoriaResponse response = request.GetResponse();
            // normal verification doesn't work here safely due to ETags and No-Content responses
            if (response.ActualStatusCode != HttpStatusCode.OK && response.ActualStatusCode != HttpStatusCode.NoContent)
            {
                ResponseVerification.LogFailure(response, new TestFailedException("Unexpected status code"));
            }

            ResourceContainer otherResourceContainer = resourceContainer.FindDefaultRelatedContainer(property);
            KeyExpressions keyExpressions = GetKeyExpressionsFromPayload(otherResourceContainer, response);
            if (pageSizeChanged)
            {
                this.DataService.ConfigSettings.SetEntitySetPageSize(resourceContainer.Name, originalPageSize);
            }

            return keyExpressions;
        }
        /// <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;
        }
Ejemplo n.º 39
0
        public static AstoriaRequest BuildInsert(Workspace workspace, ResourceContainer container, ResourceType type,
            HttpStatusCode expectedStatusCode, SerializationFormatKind format, out KeyExpression createdKey)
        {
            KeyedResourceInstance newResource = type.CreateRandomResource(container);
            if (newResource == null)
            {
                newResource = ResourceInstanceUtil.CreateKeyedResourceInstanceByClone(container, type);

                if(newResource == null)
                {
                    createdKey = null;
                    return null;
                }
            }

            QueryNode query;
            if (!type.Key.Properties.Any(p => p.Facets.ServerGenerated) && newResource.ResourceInstanceKey != null)
            {
                createdKey = newResource.ResourceInstanceKey.CreateKeyExpression(container, type);
                query = ContainmentUtil.BuildCanonicalQuery(createdKey, true);
            }
            else
            {
                createdKey = null;
                // the key is unknown, must be server generated
                // in this case, lets hope that containment is a non-issue
                query =
                    Query.From(Exp.Variable(container))
                    .Select();
                if (!container.Facets.TopLevelAccess && expectedStatusCode == HttpStatusCode.Created)
                    expectedStatusCode = HttpStatusCode.BadRequest;
            }

            AstoriaRequest request = workspace.CreateRequest();

            request.Verb = RequestVerb.Post;
            request.Query = query;
            request.UpdateTree = newResource;
            request.ExpectedStatusCode = expectedStatusCode;
            request.Format = format;

            return request;
        }
Ejemplo n.º 40
0
 protected override Expression VisitKeyExpression(KeyExpression expression)
 {
     return(expression);
 }
Ejemplo n.º 41
0
        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;
        }