Exemplo n.º 1
0
        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");
                    }
                }
            }
        }
Exemplo n.º 2
0
        public void GetKeyExpression()
        {
            if (_resType.Name.Contains("Order_Details_Extended") || _resourceContainer.Name.Contains("Order_Details_Extended"))
            {
                this.Result = null;
                return;
            }

            if (_resType.Name != _resourceContainer.BaseType.Name)
            {
                KeyExpressions keyExp2 = _resourceContainer.Workspace.GetExistingAssociatedKeys(_resourceContainer, _prop, _key);
                if (null == keyExp2 || keyExp2.Count == 0) /* no keys for resource type*/ return {
                    ;
                }
                foreach (KeyExpression ke in keyExp2)
                {
                    bool bSpecial = SpecialChars(ke);
                    if (bSpecial)
                    {
                        this.Result = null;
                        break;
                    }
                    else
                    {
                        this.Result = ke;
                        AstoriaTestLog.WriteLineIgnore("Predicate from container :" + _resType.Name);
                        break;
                    }
                }
            }
Exemplo n.º 3
0
        public void VerifyServer(ExpNode q)
        {
            AstoriaTestLog.WriteLineIgnore("Verify server query");
            try
            {
                UriQueryBuilder ub   = new UriQueryBuilder(_workspace, "");
                string          ruri = ub.Build(q);
                AstoriaTestLog.WriteLineIgnore(ruri);


                AstoriaRequest request = _workspace.CreateRequest(q);
                request.Format = _kind;

                if (request.URI.Length > 260)
                {
                    return;
                }

                AstoriaResponse response = request.GetResponse();
                response.Verify();
            }
            catch (Exception e)
            {
                AstoriaTestLog.WriteLineIgnore(e.ToString());
            }
        }
Exemplo n.º 4
0
 // Print out the WCF configuration option values if different from default setting
 public void LogConfigSetting()
 {
     if (!_TransferMode.Equals("Buffered") ||
         _MaxBufferSize != 2147483647 ||
         _MaxReceivedMessageSize != 2147483647 ||
         _MaxRequestLength != 2097151 ||
         !_TransportSecurityMode.Equals("TransportCredentialOnly") ||
         !_CloseTimeout.Equals("00:01:00") ||
         !_OpenTimeout.Equals("00:01:00") ||
         !_ReceiveTimeout.Equals("00:10:00") ||
         !_SendTimeout.Equals("00:01:00") ||
         !_AspNetCompatibilityEnabled)
     {
         AstoriaTestLog.WriteLineIgnore("WCF Configuration Settings:");
         AstoriaTestLog.WriteLineIgnore("_TransferMode: " + _TransferMode);
         AstoriaTestLog.WriteLineIgnore("_MaxBufferSize: " + _MaxBufferSize);
         AstoriaTestLog.WriteLineIgnore("_MaxReceivedMessageSize: " + _MaxReceivedMessageSize);
         AstoriaTestLog.WriteLineIgnore("_MaxRequestLength: " + _MaxRequestLength);
         AstoriaTestLog.WriteLineIgnore("_TransportSecurityMode: " + _TransportSecurityMode);
         AstoriaTestLog.WriteLineIgnore("_CloseTimeout: " + _CloseTimeout);
         AstoriaTestLog.WriteLineIgnore("_OpenTimeout: " + _OpenTimeout);
         AstoriaTestLog.WriteLineIgnore("_ReceiveTimeout: " + _ReceiveTimeout);
         AstoriaTestLog.WriteLineIgnore("_SendTimeout: " + _SendTimeout);
         AstoriaTestLog.WriteLineIgnore("_AspNetCompatibilityEnabled: " + _AspNetCompatibilityEnabled);
     }
 }
Exemplo n.º 5
0
        protected override void Verify()
        {
            if (!Applies(Response))
            {
                return;
            }

            AstoriaRequest request = Response.Request;

            if (!request.SnapshotForUpdate)
            {
                return;
            }

            try
            {
                Verify(request);
            }
            catch (Exception e)
            {
                AstoriaTestLog.WriteLineIgnore("Pre-update snapshot:");
                AstoriaTestLog.WriteLineIgnore(request.BeforeUpdatePayload.RawPayload);
                AstoriaTestLog.WriteLineIgnore("--------------------");
                AstoriaTestLog.WriteLineIgnore("Post-update snapshot:");
                AstoriaTestLog.WriteLineIgnore(request.AfterUpdatePayload.RawPayload);

                throw new TestFailedException("Update verification failed", null, null, e);
            }
        }
Exemplo n.º 6
0
        public void VerifyClient(QueryModel qm)
        {
            WebDataCtxWrapper ctx = new WebDataCtxWrapper(new Uri(qm.Workspace.ServiceUri));

            ctx.Credentials = CredentialCache.DefaultNetworkCredentials;

            try
            {
                UriQueryBuilder ub   = new UriQueryBuilder(qm.Workspace, "");
                string          ruri = ub.Build(qm.QueryResult);

                string uriRel = ruri.Substring(ruri.LastIndexOf(".svc/") + 5);

                if ((ctx.BaseUri + "/" + uriRel).Length > 260)
                {
                    return;
                }
                AstoriaTestLog.WriteLineIgnore(ctx.BaseUri + "/" + uriRel);

                ResolveClientType(qm.Workspace, ctx, qm.ResultType);

                object enumerable = ExecuteQuery(ctx, qm.ResultType, uriRel, "sync");
                Verify(qm.Workspace, qm.QueryResult, (IEnumerable)enumerable, qm.ResType, null, qm.IsCount);
            }
            catch (Exception e)
            {
                AstoriaTestLog.FailAndContinue(e);
            }
        }
Exemplo n.º 7
0
        // Turns a resource type into an MLE.
        private static void MakeMLE(Workspace w, string typeName)
        {
            // Add blob attribute.
            ResourceType type = w.ServiceContainer.ResourceTypes.Where(p => p.Name == typeName).First();

            type.Facets.Add(NodeFacet.Attribute(new BlobsAttribute(type)));
            AstoriaTestLog.WriteLineIgnore("MLE type: " + type.Name);
        }
Exemplo n.º 8
0
        //Overrides
        public override void Init()
        {
            _workspaces = new Workspaces();

            //Redirect modeling output to our (debug) logger
            ModelTrace.Enabled = false;
            ModelTrace.Out     = new TestLogWriter(TestLogFlags.Trace | TestLogFlags.Ignore);

            //Delegate
            base.Init();

            HashSet <string> interestingPropertyNames = new HashSet <string>()
            {
                "AstoriaBuild",
                "Host",
                "Client",
                "DataLayerProviderKinds",
                "HostAuthenicationMethod",
                "ServerVersion",
                "ClientVersion",
                "DesignVersion",
                "UseOpenTypes"
            };

            IEnumerable <PropertyInfo> properties = typeof(AstoriaTestProperties).GetProperties(BindingFlags.Public | BindingFlags.Static).OrderBy(p => p.Name);

            IEnumerable <PropertyInfo>[] subsets = new IEnumerable <PropertyInfo>[]
            {
                properties.Where(p => interestingPropertyNames.Contains(p.Name)),
                properties.Where(p => !interestingPropertyNames.Contains(p.Name))
            };
            foreach (IEnumerable <PropertyInfo> subset in subsets)
            {
                foreach (PropertyInfo property in subset)
                {
                    Type   type  = property.PropertyType;
                    object value = property.GetValue(null, null);
                    if (type.IsValueType || type.IsPrimitive || type == typeof(string))
                    {
                        AstoriaTestLog.WriteLineIgnore(property.Name + ": " + value);
                    }
                    else if (type.IsArray)
                    {
                        AstoriaTestLog.WriteLineIgnore(property.Name + ": {" + string.Join(", ", ((Array)value).OfType <object>().Select(o => o.ToString()).ToArray()) + "}");
                    }
                }
                AstoriaTestLog.WriteLineIgnore("");
            }

            Workspace.CreateNewWorkspaceEvent += this.HandleWorkspaceCreationEvent;
        }
Exemplo n.º 9
0
        public void Skip()
        {
            int i = NextSkipValue();

            if (_query is OrderByExpression)
            {
                _query = ((OrderByExpression)_query).Skip(i) as SkipExpression;
            }

            bSkip     = true;
            _action   = LastAction.Skip;
            bIsOption = true;
            AstoriaTestLog.WriteLineIgnore(".Skip(" + i.ToString() + ")");
        }
Exemplo n.º 10
0
        private static void HandleWebRequestTimeout(bool inWebRequest, WebException exc)
        {
            if (inWebRequest)
            {
                AstoriaTestLog.WriteLineIgnore("A web request timed out in AstoriaRequest.GetResponse(), waiting before re-trying");
            }
            else
            {
                AstoriaTestLog.WriteLineIgnore("A web request timed out, waiting before re-trying");
            }

            AstoriaTestLog.WriteLineIgnore("\tException message was: " + exc.Message);
            AstoriaTestLog.WriteLineIgnore("Time before sleep: " + System.DateTime.Now);
            System.Threading.Thread.Sleep(new TimeSpan(0, 0, TimeoutWaitSeconds));
            AstoriaTestLog.WriteLineIgnore("Time after sleep: " + System.DateTime.Now);
        }
Exemplo n.º 11
0
        public static void Verify(List <APICallLogEntry> expectedCalls, List <APICallLogEntry> observedCalls, Func <APICallLogEntry, APICallLogEntry, bool> compare)
        {
            observedCalls = observedCalls.Where(e => !ClassesToIgnore.Any(c => e.MethodName.StartsWith(c + "."))).ToList();

            List <int> mismatchedLines = new List <int>();

            AstoriaTestLog.WriteLineIgnore("Observed call order: ");
            for (int i = 0; i < observedCalls.Count; i++)
            {
                if (i >= expectedCalls.Count || !compare(expectedCalls[i], observedCalls[i]))
                {
                    AstoriaTestLog.WriteLine("(Observed) " + i + " - " + observedCalls[i].ToString());
                    mismatchedLines.Add(i);
                }
                else if (!AstoriaTestProperties.IsLabRun)
                {
                    AstoriaTestLog.WriteLineIgnore("(Observed) " + i + " - " + observedCalls[i].ToString());
                }
            }

            if (observedCalls.Count < expectedCalls.Count)
            {
                for (int i = observedCalls.Count; i < expectedCalls.Count; i++)
                {
                    mismatchedLines.Add(i);
                }
            }

            if (mismatchedLines.Any())
            {
                AstoriaTestLog.WriteLineIgnore("Expected call order: ");
                for (int i = 0; i < expectedCalls.Count; i++)
                {
                    if (mismatchedLines.Contains(i))
                    {
                        AstoriaTestLog.WriteLine("(Expected) " + i + " - " + expectedCalls[i].ToString());
                    }
                    else
                    {
                        AstoriaTestLog.WriteLineIgnore("(Expected) " + i + " - " + expectedCalls[i].ToString());
                    }
                }

                AstoriaTestLog.FailAndThrow("Observed call log did not match baseline");
            }
        }
Exemplo n.º 12
0
 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);
 }
Exemplo n.º 13
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()");
            }
        }
Exemplo n.º 14
0
 private static void HandleSocketException(bool inWebRequest, SocketException exc)
 {
     //Wait for a couple of minutes to allow sockets to be freed up
     //http://blogs.msdn.com/dgorti/archive/2005/09/18/470766.aspx
     if (inWebRequest)
     {
         AstoriaTestLog.WriteLineIgnore("A socket exception has occurred in WebRequest.GetResponse(), waiting for some to finish");
     }
     else
     {
         AstoriaTestLog.WriteLineIgnore("A socket exception has occurred, waiting for some to finish");
     }
     AstoriaTestLog.WriteLineIgnore("\tException message was: " + exc.Message);
     AstoriaTestLog.WriteLineIgnore("Time before sleep: " + System.DateTime.Now);
     System.Threading.Thread.Sleep(new TimeSpan(0, SocketExceptionWaitMinutes, 0));
     AstoriaTestLog.WriteLineIgnore("Time after sleep: " + System.DateTime.Now);
     GC.Collect();
 }
Exemplo n.º 15
0
        public static void Verify(APICallLogBuilder callLogBuilder, AstoriaResponse response, Func <APICallLogEntry, APICallLogEntry, bool> compare, params ComplexType[] types)
        {
            if (!AstoriaTestProperties.IsLabRun)
            {
                StringBuilder builder = new StringBuilder();
                builder.AppendLine("------------------------------------");
                builder.AppendLine("");
                builder.AppendLine("Verifying call order");
                builder.AppendLine("");

                if (types.Length > 0)
                {
                    builder.AppendLine("Metadata:");
                    WriteTypesToLog(builder, types);
                    builder.AppendLine("");
                }

                builder.AppendLine("Request:");
                response.Request.LogRequest(builder, true, true);
                builder.AppendLine("");
                builder.AppendLine("Response:");
                response.LogResponse(builder, true, true);
                builder.AppendLine("");
                AstoriaTestLog.WriteLineIgnore(builder.ToString());
            }

            try
            {
                Verify(callLogBuilder.Entries, response.Request.APICallLogEntries, compare);
            }
            catch (Exception ex)
            {
                if (types.Length > 0)
                {
                    StringBuilder builder = new StringBuilder();
                    builder.AppendLine("Metadata:");
                    WriteTypesToLog(builder, types);
                    builder.AppendLine("");
                    AstoriaTestLog.WriteLineIgnore(builder.ToString());
                }

                ResponseVerification.LogFailure(response, ex);
            }
        }
Exemplo n.º 16
0
        public void Sort(bool bAsc)
        {
            //Sub model - sort
            SortModel   model  = new SortModel(this._workspace, _fromContainer.BaseType);
            ModelEngine engine = new ModelEngine(this.Engine, model);

            engine.Run();

            PropertyExpression[] ordervalues = model.SortResult;

            if (_query is TopExpression)
            {
                _query = ((TopExpression)_query).Sort(ordervalues, bAsc) as OrderByExpression;
            }
            else if (_query is SkipExpression)
            {
                _query = ((SkipExpression)_query).Sort(ordervalues, bAsc) as OrderByExpression;
            }
            else if (_query is CountExpression)
            {
                _query = ((CountExpression)_query).Sort(ordervalues, bAsc) as OrderByExpression;
            }
            else if (_query is ExpandExpression)
            {
                _query = ((ExpandExpression)_query).Sort(ordervalues, bAsc) as OrderByExpression;
            }
            else if (_query is NavigationExpression)
            {
                _query = ((NavigationExpression)_query).Sort(ordervalues, bAsc) as OrderByExpression;
            }
            else if (_query is PredicateExpression)
            {
                _query = ((PredicateExpression)_query).Sort(ordervalues, bAsc) as OrderByExpression;
            }
            else if (_query is ScanExpression)
            {
                _query = ((ScanExpression)_query).Sort(ordervalues, bAsc) as OrderByExpression;
            }

            bSort     = true;
            _action   = LastAction.OrderBy;
            bIsOption = true;
            AstoriaTestLog.WriteLineIgnore(".OrderBy(" + ordervalues.ToString() + ")");
        }
Exemplo n.º 17
0
        public static void ExecuteLinq(Workspace workspace, ExpNode q, ResourceContainer container, bool bSingle, ExpNode altq)
        {
            System.Uri uri = new Uri(workspace.ServiceUri);

            WebDataCtxWrapper ctx = new WebDataCtxWrapper(uri);

            ctx.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
            ctx.MergeOption = MergeOption.NoTracking;

            Type resType = container.BaseType.ClientClrType;

            ResolveClientType(workspace, ctx, resType);

            Type       cType = typeof(WebDataCtxWrapper);
            MethodInfo mi    = cType.GetMethod("CreateQuery", new Type[] { typeof(string) });

            Type       pType         = container.BaseType.ClientClrType;
            MethodInfo miConstructed = mi.MakeGenericMethod(pType);

            string uri2 = container.Name;

            AstoriaTestLog.WriteLineIgnore(workspace.ServiceUri + "/" + uri2);

            object[] args  = { uri2 };
            object   query = miConstructed.Invoke(ctx, args);

            LinqQueryBuilder lb   = new LinqQueryBuilder(workspace, (IQueryable)query);
            string           uri3 = lb.Build(q);

            AstoriaTestLog.WriteLineIgnore("Linq expression: " + lb.QueryExpression);

            //if (bSingle)
            //{
            //    var single = lb.QueryResultSingle;
            //    VerifyLinqSingle(workspace, altq, single, container);
            //}
            //else
            //{
            var queryable = lb.QueryResult;

            VerifyLinq(workspace, q, (IQueryable)queryable);
            //}
        }
Exemplo n.º 18
0
        public void Navigation()
        {
            bool         bfound   = false;
            int          j        = 0;
            ResourceType _navType = null;

            while (!bfound && j < from.Properties.Count)
            {
                int i = this.Engine.Options.Random.Next(0, from.Properties.Count);

                ResourceProperty _property = (ResourceProperty)from.Properties[i];
                if (_property.IsNavigation && _property.Type is CollectionType && this.ResContainer.BaseType.Properties.Contains(_property))
                {
                    if (_query is PredicateExpression)
                    {
                        _query = ((PredicateExpression)_query).Nav(_property.Property()) as NavigationExpression;
                        if (_property.Type is CollectionType)
                        {
                            _navType = (ResourceType)((ResourceCollection)_property.Type).SubType;
                            _pType   = _navType.ClientClrType;
                        }
                        else if (_property.Type is ResourceType)
                        {
                            _navType = (ResourceType)_property.Type;
                            _pType   = _property.Type.ClrType;
                        }

                        this.ResType = _navType;

                        bNav         = true;
                        bfound       = true;
                        _action      = LastAction.Nav;
                        property     = _property;
                        this.ResType = _navType; //update the resourceType

                        AstoriaTestLog.WriteLineIgnore(".Nav(" + _property.Property().Name + ")");
                        IsKey = false;
                    }
                }

                j++;
            }
        }
Exemplo n.º 19
0
        public static void CreateDefaultDatabase(Workspace workspace)
        {
            if (workspace.Settings.SkipDataPopulation)
            {
                AstoriaTestLog.WriteLineIgnore("Creating empty database for workspace '" + workspace.Name + "'.");
                workspace.Database = new AstoriaDatabase(workspace.DatabasePrefixName, false);
            }
            else
            {
                AstoriaTestLog.WriteLineIgnore("Creating default database for workspace '" + workspace.Name + "'.");

                workspace.Database = new AstoriaDatabase(workspace.DatabasePrefixName, true);
                ResourceType ldr = workspace.LanguageDataResource();
                if (ldr != null)
                {
                    AstoriaTestLog.WriteLineIgnore("Inserting language data for workspace '" + workspace.Name + "'.");
                    workspace.Database.InsertLanguageData(workspace, ldr);
                }
            }
        }
Exemplo n.º 20
0
        public void Run()
        {
            if (_workspace.Settings.SkipDataPopulation)
            {
                AstoriaTestLog.WriteLineIgnore("Skipping GraphBasedDataGenerator.SendData() due to workspace settings");
                return;
            }

            bool oldLoggingValue = _workspace.Settings.SuppressTrivialLogging;

            _workspace.Settings.SuppressTrivialLogging = true;

            List <ResourceContainer> containers = _workspace.ServiceContainer.ResourceContainers.Where(rc => !(rc is ServiceOperation)).ToList();

            foreach (ResourceContainer container in containers)
            {
                if (!this.Skip(container))
                {
                    int addCount;
                    int graphDepth = this.GraphDepth(container.BaseType);

                    if (graphDepth > _maxEntitiesToInsert)
                    {
                        addCount = 1;
                    }
                    else
                    {
                        addCount = _maxEntitiesToInsert - graphDepth + 1;
                    }

                    System.Diagnostics.Debug.WriteLine(container.BaseType.Name + ": " + graphDepth.ToString(), ", " + addCount.ToString());

                    this.InsertData(container, addCount);
                }
            }

            DataInserter.Close();
            Done = true;

            _workspace.Settings.SuppressTrivialLogging = oldLoggingValue;
        }
Exemplo n.º 21
0
        public void Count()
        {
            if (_query is TopExpression)
            {
                _query = ((TopExpression)_query).Count(true) as CountExpression;
            }
            else if (_query is OrderByExpression)
            {
                _query = ((OrderByExpression)_query).Count(true) as CountExpression;
            }
            else if (_query is ScanExpression)
            {
                _query = ((ScanExpression)_query).Count(true) as CountExpression;
            }
            else if (_query is NavigationExpression)
            {
                _query = ((NavigationExpression)_query).Count(true) as CountExpression;
            }
            else if (_query is SkipExpression)
            {
                _query = ((SkipExpression)_query).Count(true) as CountExpression;
            }
            else if (_query is NavigationExpression)
            {
                _query = ((NavigationExpression)_query).Count(true) as CountExpression;
            }
            else if (_query is ExpandExpression)
            {
                _query = ((ExpandExpression)_query).Count(true) as CountExpression;
            }
            else if (_query is PredicateExpression)
            {
                _query = ((PredicateExpression)_query).Count(true) as CountExpression;
            }


            IsCount   = true;
            _action   = LastAction.Count;
            bIsOption = true;
            AstoriaTestLog.WriteLineIgnore(".Count");
        }
Exemplo n.º 22
0
        //---------------------------------------------------------------------
        // Customizes the workspace by enabling features.
        //---------------------------------------------------------------------
        protected override void WorkspaceCallback(Workspace w)
        {
            // Enable features.
            EnableServerGeneratedKeys(w);
            AddBlobsAttributes(w, "Project", "College", "GradStudent", "Vehicle");
            ImplementServiceProvider(w);
            ImplementStreamProvider(w);

            // Fixup and inject additional code.
            w.GlobalAdditionalCode = FixupAdditionalCode(w.GlobalAdditionalCode ?? "")
                                     .Replace("ContextNamespace", w.ContextNamespace)
                                     .Replace("ContextTypeName", w.ContextTypeName)
                                     .Replace("DataServiceClass", w.ServiceClassName);

            // Dump additional code for easier lab run investigations.
            if (AstoriaTestProperties.IsLabRun)
            {
                AstoriaTestLog.WriteLineIgnore(w.GlobalAdditionalCode);
            }
            w.GenerateClientTypes = true;
            w.PopulateClientTypes();
        }
Exemplo n.º 23
0
        public void Top()
        {
            int i = NextTopValue();

            if (_query is OrderByExpression)
            {
                _query = ((OrderByExpression)_query).Top(i) as TopExpression;
            }
            else if (_query is CountExpression)
            {
                _query = ((CountExpression)_query).Top(i) as TopExpression;
            }
            else if (_query is ExpandExpression)
            {
                _query = ((ExpandExpression)_query).Top(i) as TopExpression;
            }
            else if (_query is NavigationExpression)
            {
                _query = ((NavigationExpression)_query).Top(i) as TopExpression;
            }
            else if (_query is SkipExpression)
            {
                _query = ((SkipExpression)_query).Top(i) as TopExpression;
            }
            else if (_query is PredicateExpression)
            {
                _query = ((PredicateExpression)_query).Top(i) as TopExpression;
            }
            else if (_query is ScanExpression)
            {
                _query = ((ScanExpression)_query).Top(i) as TopExpression;
            }

            iTop      = i;
            bTop      = true;
            _action   = LastAction.Top;
            bIsOption = true;
            AstoriaTestLog.WriteLineIgnore(".Top(" + i.ToString() + ")");
        }
Exemplo n.º 24
0
        // Creates MLEs and generates server-side code.
        protected override void WorkspaceCallback(Workspace w)
        {
            // Turn some entities into MLEs.
            MakeMLE(w, "InternalPicture");
            MakeMLE(w, "ExternalPicture");

            // Read additional code from resources.
            string resPath = "Microsoft.Data.Test.Features.Blobs.Client.Resources.PicturesTagsEdm.res.cs";

            using (StreamReader reader = new StreamReader(GetType().Assembly.GetManifestResourceStream(resPath), true))
            {
                w.GlobalAdditionalCode = reader.ReadToEnd();
            }

            w.GlobalAdditionalCode = w.GlobalAdditionalCode.Replace("ContextNamespace", w.ContextNamespace).Replace("ContextTypeName", w.ContextTypeName).Replace("DataServiceClass", w.ServiceClassName);

            // Dump additional code for easier lab run investigations.
            if (AstoriaTestProperties.IsLabRun)
            {
                AstoriaTestLog.WriteLineIgnore("Global additional code for workspace " + w.Name + ":");
                AstoriaTestLog.WriteLineIgnore(w.GlobalAdditionalCode);
            }
        }
Exemplo n.º 25
0
        private static void CheckWindows7CompatMode()
        {
            switch (AstoriaTestProperties.WindowsCompatFlag)
            {
            case WindowsCompatFlag.None:
                return;

            case WindowsCompatFlag.Vista:
                throw new NotImplementedException("Vista Compatible Mode Check Not Implemented");

            case WindowsCompatFlag.Win7:
                // Check that if we are running on Win7 then we are in Win7 compat mode
                if (OsCompatibility.IsWindows7CompatibilitySupported)
                {
                    try
                    {
                        OsCompatibility.EnsureWindows7DynamicContextIsActive();
                    }
                    catch (Exception e)
                    {
                        AstoriaTestLog.Warning(false, e.ToString());
                    }
                    AstoriaTestLog.WriteLineIgnore("Verified that we are running in Win7 compat mode");
                }
                else
                {
                    AstoriaTestLog.WriteLineIgnore("Win7 compat mode not supported");
                }
                break;

            case WindowsCompatFlag.Win8:
                throw new NotImplementedException("Windows 8 Compatible Mode Check Not Implemented");

            default:
                throw new NotImplementedException("Unknown Compatible Mode Check Not Implemented");
            }
        }
Exemplo n.º 26
0
        public virtual void From()
        {
            if (RunningUnderScenarioModel)
            {
                _query = Query.From(Exp.Variable(ResContainer));
                _pType = ResContainer.BaseType.ClientClrType;
                AstoriaTestLog.WriteLineIgnore("Query.From(" + ResContainer.Name + ")");
            }
            else
            {
                ScanModel   model  = new ScanModel(_workspace);
                ModelEngine engine = new ModelEngine(this.Engine, model);
                engine.Run();

                this.ResContainer = model.ResultContainer;
                _query            = Query.From(Exp.Variable(model.ResultContainer));
                _pType            = model.ResultContainer.BaseType.ClientClrType;
                AstoriaTestLog.WriteLineIgnore("Query.From(" + model.ResultContainer.Name + ")");
            }


            _action = LastAction.From;
            IsCount = false;
        }
Exemplo n.º 27
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));
            }
        }
Exemplo n.º 28
0
        protected override bool SendRequest_Internal(AstoriaRequest request, out AstoriaResponse response)
        {
            string uri = request.URI;

            // workaround bug that same url is always cached.
            if (request.Verb == RequestVerb.Get)
            {
                if (uri.Contains('?'))
                {
                    uri = String.Format("{0}&bug={1}", uri, DateTime.Now.Ticks.ToString());
                }
                else
                {
                    uri = String.Format("{0}?bug={1}", uri, DateTime.Now.Ticks.ToString());
                }
            }

            Exception exc        = null;
            int       statusCode = -1;

            XmlHttpClassComWrapper nativeWebRequest;

            try
            {
                nativeWebRequest = XmlHttpClassComWrapper.CreateXmlHttpClassWrapper();
            }
            catch
            {
                AstoriaTestLog.WriteLineIgnore("Could not create a new XmlHttp com wrapper");
                AstoriaTestLog.WriteLineIgnore("Time before sleep: " + DateTime.Now);
                Threading.Thread.Sleep(new TimeSpan(0, 0, 30));
                AstoriaTestLog.WriteLineIgnore("Time after sleep: " + DateTime.Now);
                response = null;
                return(false);
            }

            using (nativeWebRequest)
            {
                string userName = null;
                string password = null;
                if (AstoriaTestProperties.HostAuthenicationMethod.ToLower().Equals("windows"))
                {
                    userName = string.Empty;
                    password = string.Empty;
                }

                nativeWebRequest.open(request.Verb.ToHttpMethod(), uri, false, userName, password);


                // this does Accept and Content-Type for us
                foreach (KeyValuePair <string, string> header in request.Headers)
                {
                    nativeWebRequest.setRequestHeader(header.Key, header.Value);
                }

                byte[] toSend = request.PayloadBytes;

                try
                {
                    nativeWebRequest.send(toSend);
                    statusCode = nativeWebRequest.status;
                }
                catch (System.Reflection.TargetInvocationException targetInvokationException)
                {
                    exc = targetInvokationException;

                    if (targetInvokationException.InnerException != null && targetInvokationException.InnerException is System.Runtime.InteropServices.COMException)
                    {
                        //HACK DUE TO XmlHttpIssue
                        // info at    http://www.enhanceie.com/ie/bugs.asp
                        if (nativeWebRequest.status == 1223)
                        {
                            statusCode = (int)HttpStatusCode.NoContent;
                        }
                        else
                        {
                            throw targetInvokationException;
                        }
                    }
                }

                response = new AstoriaResponse(request);

                // Assign status code.
                if (Enum.IsDefined(typeof(HttpStatusCode), statusCode))
                {
                    response.ActualStatusCode = (HttpStatusCode)statusCode;
                }
                else
                {
                    response.ActualStatusCode = HttpStatusCode.Ambiguous;
                }

                // Assign Content-Type and other headers.
                string headers = nativeWebRequest.AllResponseHeaders;
                response.ContentType = null;
                if (headers != null)
                {
                    // Parse headers.
                    foreach (string headerLine in headers.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        int valueIndex = headerLine.IndexOf(':');
                        if (valueIndex > 0 && valueIndex < headerLine.Length - 1)
                        {
                            response.Headers[headerLine.Substring(0, valueIndex)] = headerLine.Substring(valueIndex + 2);
                        }
                    }
                }
                else
                {
                    // No headers.
                    if (statusCode == (int)HttpStatusCode.NoContent)
                    {
                        AstoriaTestLog.WriteLine("Warning: XmlHttp does not return headers when status code is No Content");
                    }
                    else
                    {
                        AstoriaTestLog.FailAndThrow("Failed to read headers from XmlHttp response");
                    }
                }
                response.ETagHeaderFound = response.Headers.ContainsKey("ETag");

                // Assign payload.
                if (response.ContentType == SerializationFormatKinds.MimeApplicationOctetStream)
                {
                    response.Bytes = nativeWebRequest.responseBody;
                }
                else
                {
                    response.Payload = nativeWebRequest.responseText;
                }

                GC.Collect();
                return(true);
            }
        }
Exemplo n.º 29
0
        private static bool HandleWebException(WebException webException, out WebResponse response)
        {
            // return whether or not it has been handled
            // find out if the exception was caused by a socket exception

            Exception innerException = webException.InnerException;

            System.Net.Sockets.SocketException sockException = null;

            while (innerException != null)
            {
                if (innerException is System.Net.Sockets.SocketException)
                {
                    sockException = innerException as System.Net.Sockets.SocketException;
                    break;
                }
                else
                {
                    innerException = innerException.InnerException;
                }
            }

            if (sockException != null)
            {
                // Ignore exceptions caused by Fiddler.
                if (sockException.SocketErrorCode == System.Net.Sockets.SocketError.ConnectionReset)
                {
                    AstoriaTestLog.WriteLine("Connection was reset. Retrying...");
                    response = null;
                    return(true);
                }
                AstoriaTestLog.WriteLine("A socket exception occurred, waiting 30 seconds before retrying");
                AstoriaTestLog.WriteLine("Message: " + sockException.Message);
                AstoriaTestLog.WriteLine("Error Code: " + sockException.SocketErrorCode);
                AstoriaTestLog.WriteLineIgnore("Time before sleep: " + DateTime.Now);
                Threading.Thread.Sleep(new TimeSpan(0, 0, 30));
                AstoriaTestLog.WriteLineIgnore("Time after sleep: " + DateTime.Now);
                response = null;
                return(true);
            }

            if (webException.Status == WebExceptionStatus.Timeout)
            {
                AstoriaTestLog.WriteLine("The request timeout out, waiting 30 seconds before retrying");
                AstoriaTestLog.WriteLine("Message: " + webException.Message);
                AstoriaTestLog.WriteLineIgnore("Time before sleep: " + DateTime.Now);
                Threading.Thread.Sleep(new TimeSpan(0, 0, 30));
                AstoriaTestLog.WriteLineIgnore("Time after sleep: " + DateTime.Now);
                response = null;
                return(true);
            }

            if (webException.Response != null)
            {
                response = webException.Response;
                return(true);
            }

            response = null;
            return(false);
        }
Exemplo n.º 30
0
        private void VerifyProperties(ResourceType type, PayloadObject inserted, PayloadObject returned, bool missingInsertPropertiesOk, Func <ResourceProperty, bool> strictEquality)
        {
            List <string> propertyNames = inserted.PayloadProperties.Union(returned.PayloadProperties).Select(p => p.Name).ToList();

            propertyNames.AddRange(inserted.CustomEpmMappedProperties.Keys);
            propertyNames.AddRange(returned.CustomEpmMappedProperties.Keys);

            foreach (string propertyName in propertyNames.Distinct())
            {
                PayloadProperty insertedProperty;
                if (inserted.Format == SerializationFormatKind.JSON) //in JSON the first one wins
                {
                    insertedProperty = inserted.PayloadProperties.FirstOrDefault(p => p.Name == propertyName);
                }
                else //in xml the last one wins
                {
                    insertedProperty = inserted.PayloadProperties.LastOrDefault(p => p.Name == propertyName);
                }
                bool insertHadProperty = insertedProperty != null;

                PayloadProperty returnedProperty    = returned.PayloadProperties.LastOrDefault(p => p.Name == propertyName);;
                bool            returnedHadProperty = returnedProperty != null;

                ResourceProperty property = type.Properties.OfType <ResourceProperty>().SingleOrDefault(p => p.Name == propertyName);

                if (property == null || !property.Facets.IsDeclaredProperty)
                {
                    if (!type.Facets.IsOpenType)
                    {
                        string error = "included dynamic property '" + propertyName + "' despite '" + type.Name + "' not being an open type";
                        if (insertHadProperty && returnedHadProperty)
                        {
                            AstoriaTestLog.FailAndThrow("Both the inserted and returned objects " + error);
                        }
                        else if (insertHadProperty)
                        {
                            AstoriaTestLog.FailAndThrow("The inserted object " + error);
                        }
                        else if (returnedHadProperty)
                        {
                            AstoriaTestLog.FailAndThrow("The returned object " + error);
                        }
                    }
                    else
                    {
                        if (insertHadProperty && returnedHadProperty)
                        {
                            CompareDynamicPropertyValues(insertedProperty, returnedProperty);
                        }
                        else if (insertHadProperty)
                        {
                            // only acceptable if inserted value was null
                            if (insertedProperty.IsNull)
                            {
                                AstoriaTestLog.FailAndThrow("Returned object missing non-null dynamic property '" + propertyName + "'");
                            }
                        }
                    }
                }
                else
                {
                    if (property.IsNavigation)
                    {
                        // the insert payload may not specify this property
                        //PayloadObject insertedObject = inserted.PayloadObjects.SingleOrDefault(o => o.Name == property.Name);
                        PayloadObject returnedObject = returned.PayloadObjects.Single(o => o.Name == property.Name);

                        // returned thing should be deferred whether its a reference or not
                        AstoriaTestLog.AreEqual(true, returnedObject.Deferred, "!returnedObject.Deferred", false);

                        // TODO: verify only expected links are present (based on uri and payload values as well)
                    }
                    else
                    {
                        if (insertHadProperty && returnedHadProperty)
                        {
                            try
                            {
                                ComparePropertyValues(property, insertedProperty, returnedProperty, strictEquality(property));
                            }
                            catch (Exception e)
                            {
                                throw new TestFailedException("Value of property '" + property.Name + "' does not match inserted value", null, null, e);
                            }
                        }
                        else if (insertHadProperty)
                        {
                            AstoriaTestLog.FailAndThrow("Returned object unexpectedly missing declared property '" + propertyName + "'");
                        }
                        else if (returnedHadProperty)
                        {
                            if (missingInsertPropertiesOk)
                            {
                                AstoriaTestLog.WriteLineIgnore("Ignoring missing declared property '" + propertyName + "' in insert payload");
                            }
                            else
                            {
                                AstoriaTestLog.FailAndThrow("Inserted object unexpectedly missing declared property '" + propertyName + "'");
                            }
                        }
                    }
                }
            }
        }