/// <summary>
        /// Verify Common.Core.4065
        /// </summary>
        /// <param name="context">Service context</param>
        /// <param name="info">out parameter to return violation information when rule fail</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;

            info = null;

            // Send a Get request with "application/json" in Accept header.
            string   acceptHeader = Constants.AcceptHeaderJson;
            Response response     = WebHelper.Get(context.Destination, acceptHeader, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, context.RequestHeaders);

            // ResponseHeaders is not empty.
            if (response.ResponseHeaders.Length != 0)
            {
                // Whether "application/json" exist in ResponseHeaders, if exist means service support "application/json".
                if (response.ResponseHeaders.Contains(Constants.AcceptHeaderJson))
                {
                    passed = true;
                }
                else
                {
                    passed = false;
                    info   = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload);
                }
            }

            return(passed);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Verifies the service implementation feature.
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out parameter to return violation information when rule does not pass</param>
        /// <returns>true if the service implementation feature passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;

            info = null;
            var    svcStatus     = ServiceStatus.GetInstance();
            var    entitySetUrls = MetadataHelper.GetEntitySetURLs();
            var    entitySetUrl  = entitySetUrls[0];
            string url           = svcStatus.RootURL.TrimEnd('/') + "/" + entitySetUrl + "?$top=1";
            var    resp          = WebHelper.Get(new Uri(url), string.Empty, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, svcStatus.DefaultHeaders);
            var    detail        = new ExtensionRuleResultDetail("ServiceImpl_SystemQueryOptionTop", url, HttpMethod.Get, string.Empty);

            info = new ExtensionRuleViolationInfo(new Uri(url), string.Empty, detail);
            if (null != resp && HttpStatusCode.OK == resp.StatusCode)
            {
                JObject jObj = JObject.Parse(resp.ResponsePayload);
                JArray  jArr = jObj.GetValue("value") as JArray;
                passed = 1 == jArr.Count;
            }
            else
            {
                passed = false;
            }

            return(passed);
        }
        /// <summary>
        /// Verifies the service implementation feature.
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out parameter to return violation information when rule does not pass</param>
        /// <returns>true if the service implementation feature passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;

            info = null;
            var    svcStatus = ServiceStatus.GetInstance();
            string entityTypeShortName;
            var    propTypes = new string[2] {
                "Edm.Date", "Edm.DateTimeOffset"
            };
            var propNames = MetadataHelper.GetPropertyNames(propTypes, out entityTypeShortName);

            if (null == propNames || !propNames.Any())
            {
                return(passed);
            }

            string propName     = propNames[0];
            var    entitySetUrl = entityTypeShortName.GetAccessEntitySetURL();

            if (string.IsNullOrEmpty(entitySetUrl))
            {
                return(passed);
            }

            string url  = svcStatus.RootURL.TrimEnd('/') + "/" + entitySetUrl;
            var    resp = WebHelper.Get(new Uri(url), string.Empty, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, svcStatus.DefaultHeaders);

            if (null != resp && HttpStatusCode.OK == resp.StatusCode)
            {
                JObject jObj    = JObject.Parse(resp.ResponsePayload);
                JArray  jArr    = jObj.GetValue(Constants.Value) as JArray;
                var     entity  = jArr.First as JObject;
                var     propVal = Convert.ToDateTime(entity[propName]).Second;
                url  = string.Format("{0}?$filter=second({1}) eq {2}", url, propName, propVal);
                resp = WebHelper.Get(new Uri(url), string.Empty, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, svcStatus.DefaultHeaders);
                var detail = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Get, string.Empty);
                info = new ExtensionRuleViolationInfo(new Uri(url), string.Empty, detail);
                if (null != resp && HttpStatusCode.OK == resp.StatusCode)
                {
                    jObj = JObject.Parse(resp.ResponsePayload);
                    jArr = jObj.GetValue(Constants.Value) as JArray;
                    foreach (JObject et in jArr)
                    {
                        passed = Convert.ToDateTime(et[propName]).Second == propVal;
                    }
                }
                else
                {
                    passed = false;
                }
            }

            return(passed);
        }
        /// <summary>
        /// Verifies the extension rule.
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out parameter to return violation information when rule does not pass</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;

            string   url      = string.Format("{0}/?$find=*", context.Destination);
            var      req      = WebRequest.Create(url) as HttpWebRequest;
            Response response = WebHelper.Get(req, RuleEngineSetting.Instance().DefaultMaximumPayloadSize);
            ExtensionRuleResultDetail detail1 = new ExtensionRuleResultDetail(this.Name, url, "GET", string.Empty, response);

            if (response != null && response.StatusCode != null)
            {
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    passed = true;
                }
                else
                {
                    passed = false;
                    detail1.ErrorMessage = "Services SHOULD fail the above URI because it contains query options 'find' which services does not understand.";
                }
            }
            else
            {
                passed = false;
                detail1.ErrorMessage = "No response returned from above URI.";
            }

            info = new ExtensionRuleViolationInfo(context.Destination, context.ResponsePayload, detail1);
            return(passed);
        }
        /// <summary>
        /// Builds the uri for purpose of probing the empty feed based on the base uri string.
        /// </summary>
        /// <param name="context">The service context object</param>
        /// <returns>Uri object if a meaningful prober can be constructed; null otherwise </returns>
        private static Uri ConstructProbeUri(ServiceContext context)
        {
            int safetyTopping = 20;
            Uri result = null;

            // find out how many entries in the base feed
            Uri uriFeedCount = new Uri(context.DestinationBasePath + "/$count");
            var resp = WebHelper.Get(uriFeedCount, Constants.AcceptHeaderAtom, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, context.RequestHeaders);
            if (resp.StatusCode.HasValue && resp.StatusCode.Value == System.Net.HttpStatusCode.OK && !string.IsNullOrEmpty(resp.ResponsePayload))
            {
                string payload = resp.ResponsePayload.Trim();
                int count = 0;
                if (Int32.TryParse(payload, out count) && count >= 0)
                {
                    int countToSkip = count + safetyTopping;
                    Uri uriBaseFeed = new Uri(context.DestinationBasePath);
                    ResourcePathHelper pathHelper = new ResourcePathHelper(uriBaseFeed);
                    pathHelper.AddQueryOption("$skip", countToSkip.ToString(CultureInfo.InvariantCulture));

                    result = new Uri(pathHelper.Product);
                }
            }

            return result;
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Gets value of the specified property of the entry
        /// </summary>
        /// <param name="uriEntry">The entry</param>
        /// <param name="property">The name of property</param>
        /// <returns>The property value</returns>
        private static string GetProperty(Uri uriEntry, string property, ServiceContext ctx)
        {
            Uri uri  = new Uri(uriEntry, property + "/$value");
            var resp = WebResponseHelper.GetWithHeaders(uri, false, null, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, ctx);

            return(resp.ResponsePayload);
        }
        /// <summary>
        /// Verifies the semantic rule
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out parameter to return violation information when rule does not pass</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            info = null;
            bool?  passed             = null;
            string odataVersionString = "DataServiceVersion";

            if (context.Version == ODataVersion.V4)
            {
                odataVersionString = "OData-Version";
            }

            //to get the DSV defined in metadata document
            XElement meta  = XElement.Parse(context.MetadataDocument);
            string   xpath = @"//*[local-name()='DataServices' and @m:DataServiceVersion]";
            var      ds    = meta.XPathSelectElement(xpath, ODataNamespaceManager.Instance);

            if (ds != null)
            {
                string dsvInResp = context.ResponseHttpHeaders.GetHeaderValue(odataVersionString);
                string dsvInMeta = ds.GetAttributeValue("m:DataServiceVersion", ODataNamespaceManager.Instance);

                if (!string.IsNullOrEmpty(dsvInResp) && !string.IsNullOrEmpty(dsvInMeta))
                {
                    string dsv     = GetBiggerDSV(ResourcePathHelper.GetMajorHeaderValue(dsvInMeta), ResourcePathHelper.GetMajorHeaderValue(dsvInResp));
                    var    headers = new List <KeyValuePair <string, string> > {
                        new KeyValuePair <string, string>(odataVersionString, dsv + VersionClientUserAgent)
                    };

                    var resp = WebResponseHelper.GetWithHeaders(context.Destination,
                                                                context.PayloadFormat == RuleEngine.PayloadFormat.Json,
                                                                headers,
                                                                RuleEngineSetting.Instance().DefaultMaximumPayloadSize,
                                                                context);

                    //to approximate with checking with status code and responded DSV
                    if (context.HttpStatusCode != resp.StatusCode)
                    {
                        passed = false;
                        info   = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, resp.StatusCode.ToString());
                    }
                    else
                    {
                        var DsvOld = context.ResponseHttpHeaders.GetHeaderValue(odataVersionString);
                        var DsvNew = resp.ResponseHeaders.GetHeaderValue(odataVersionString);
                        passed = DsvOld == DsvNew;
                        if (!passed.Value)
                        {
                            info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, resp.ResponsePayload);
                        }
                    }
                }
            }

            return(passed);
        }
        /// <summary>
        /// Verifies the extension rule.
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out parameter to return violation information when rule does not pass</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool? Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            info = null;
            bool? passed = null;

            Uri uriEmptyFeed = FeedCore2000.ConstructProbeUri(context);
            var resp = WebHelper.Get(uriEmptyFeed, Constants.AcceptHeaderJson, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, context.RequestHeaders);

            JObject response = JsonParserHelper.GetResponseObject(resp.ResponsePayload);
            if (response != null)
            {
                JArray entries = JsonParserHelper.GetEntries(response);
                if (entries.Count == 0)
                {
                    passed = true;
                }
                else
                {
                    passed = false;
                    info = new ExtensionRuleViolationInfo(Resource.NotEmptyFeed, uriEmptyFeed, resp.ResponsePayload);
                }
            }

            return passed;
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Verifies the service implementation feature.
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out parameter to return violation information when rule does not pass</param>
        /// <returns>true if the service implementation feature passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;

            info = null;
            var    svcStatus = ServiceStatus.GetInstance();
            string url       = svcStatus.RootURL + "?$format=application/json";
            var    resp      = WebHelper.Get(new Uri(url), string.Empty, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, context.RequestHeaders);
            var    detail    = new ExtensionRuleResultDetail("ServiceImpl_SystemQueryOptionFormat", url, HttpMethod.Get, string.Empty);

            info = new ExtensionRuleViolationInfo(new Uri(url), string.Empty, detail);
            if (null != resp && HttpStatusCode.OK == resp.StatusCode)
            {
                passed = resp.ResponsePayload.IsJsonLightSvcDoc();
            }
            else
            {
                passed = false;
            }

            return(passed);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Verifies the extension rule.
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out parameter to return violation information when rule does not pass</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;

            info = null;

            string   acceptHeader = Constants.ContentTypeXml;
            Response response     = WebHelper.Get(context.Destination, acceptHeader, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, context.RequestHeaders);

            if (null != response && HttpStatusCode.UnsupportedMediaType != response.StatusCode)
            {
                passed = true;
            }
            else
            {
                passed = false;
                info   = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload);
            }

            return(passed);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Verifies the service implementation feature.
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out parameter to return violation information when rule does not pass</param>
        /// <returns>true if the service implementation feature passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;

            info = null;
            var    svcStatus     = ServiceStatus.GetInstance();
            var    entitySetUrls = MetadataHelper.GetEntitySetURLs();
            var    entitySetUrl  = entitySetUrls[0];
            string url           = svcStatus.RootURL.TrimEnd('/') + "/" + entitySetUrl;
            int    actualNum     = JsonParserHelper.GetEntitiesCountFromFeed(url, svcStatus.DefaultHeaders);

            url = string.Format("{0}/$count", url);
            var resp   = WebHelper.Get(new Uri(url), string.Empty, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, svcStatus.DefaultHeaders);
            var detail = new ExtensionRuleResultDetail("ServiceImpl_SystemQueryOptionCount", url, HttpMethod.Get, string.Empty);

            info = new ExtensionRuleViolationInfo(new Uri(url), string.Empty, detail);
            if (null != resp && HttpStatusCode.OK == resp.StatusCode)
            {
                passed = Convert.ToInt32(resp.ResponsePayload) == actualNum;
            }
            else
            {
                passed = false;
            }

            return(passed);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Verify Metadata.Core.4504
        /// </summary>
        /// <param name="context">Service context</param>
        /// <param name="info">out parameter to return violation information when rule fail</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;

            info = null;


            Uri metadataUri = new Uri(context.ServiceBaseUri + "/$metadata/", UriKind.Absolute);

            Response response = WebHelper.Get(metadataUri, string.Empty, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, context.RequestHeaders);

            if (response != null && response.StatusCode == System.Net.HttpStatusCode.OK && !string.IsNullOrEmpty(response.ResponsePayload))
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(response.ResponsePayload);

                XmlNode serviceModel = xmlDoc.SelectSingleNode("//*[local-name()='Edmx']");
                if (serviceModel != null)
                {
                    passed = true;
                }
                else
                {
                    passed = false;
                    info   = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload);
                }
            }

            return(passed);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Verifies the extension rule.
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out parameter to return violation information when rule does not pass</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;

            Uri      metadataServiceUrl = new Uri(context.Destination.AbsoluteUri.TrimEnd('/') + @"/$metadata" + @"/");
            var      req      = WebRequest.Create(metadataServiceUrl) as HttpWebRequest;
            Response response = WebHelper.Get(req, RuleEngineSetting.Instance().DefaultMaximumPayloadSize);
            ExtensionRuleResultDetail detail = new ExtensionRuleResultDetail(this.Name, metadataServiceUrl.AbsoluteUri, "GET", string.Empty, response);

            if (response != null && response.StatusCode == HttpStatusCode.OK && response.ResponsePayload.IsMetadata())
            {
                passed = true;
            }
            else
            {
                passed = false;
                detail.ErrorMessage = "The response is not the metadata service document. Please refer to section 15 of [OData-CSDL].";
            }

            info = new ExtensionRuleViolationInfo(context.Destination, context.ResponsePayload, detail);
            return(passed);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Verify Common.Core.4015
        /// </summary>
        /// <param name="context">Service context</param>
        /// <param name="info">out parameter to return violation information when rule fail</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;

            info = null;

            if (context.ResponseHttpHeaders.Contains(context.Version == ODataVersion.V4 ? Constants.V4OdataStreaming : Constants.OdataStreaming) &&
                context.Destination.Query.Contains(@"$expand="))
            {
                List <XElement> props          = MetadataHelper.GetAllPropertiesOfEntity(context.MetadataDocument, context.EntityTypeShortName, MatchPropertyType.Navigations);
                List <string>   navigPropNames = new List <string>();

                foreach (var prop in props)
                {
                    navigPropNames.Add(prop.Attribute("Name").Value);
                }

                JObject jObj;
                context.ResponsePayload.TryToJObject(out jObj);

                if (jObj != null && jObj.Type == JTokenType.Object)
                {
                    var jProps = jObj.Children();

                    foreach (JProperty j in jProps)
                    {
                        if (navigPropNames.Contains(j.Name) && j.Value.Type == JTokenType.Array)
                        {
                            var      req  = WebRequest.Create(context.DestinationBasePath + "/" + j.Name + @"/$count") as HttpWebRequest;
                            Response resp = WebHelper.Get(req, RuleEngineSetting.Instance().DefaultMaximumPayloadSize);
                            passed = null;

                            if ((j.Value as JArray).Count < Convert.ToInt32(resp.ResponsePayload))
                            {
                                if ((j.Next as JProperty).Name ==
                                    (ODataVersion.V4 == context.Version ?
                                     Constants.V4OdataNextLink : Constants.OdataNextLink))
                                {
                                    passed = true;
                                }
                                else
                                {
                                    passed = false;
                                    info   = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload);
                                    break;
                                }
                            }
                        }
                    }
                }
            }

            return(passed);
        }
        /// <summary>
        /// Verifies the service implementation feature.
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out parameter to return violation information when rule does not pass</param>
        /// <returns>true if the service implementation feature passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;

            info = null;
            var    svcStatus = ServiceStatus.GetInstance();
            string entityTypeShortName;
            var    keyProp = MetadataHelper.GetKeyProperty(out entityTypeShortName);

            if (null == keyProp)
            {
                return(passed);
            }

            string keyPropName = keyProp.Item1;
            string keyPropType = keyProp.Item2;

            if (string.IsNullOrEmpty(entityTypeShortName) || string.IsNullOrEmpty(keyPropName) || string.IsNullOrEmpty(keyPropType))
            {
                return(passed);
            }

            string entitySetUrl = entityTypeShortName.MapEntityTypeShortNameToEntitySetURL();
            string url          = svcStatus.RootURL.TrimEnd('/') + "/" + entitySetUrl;
            var    resp         = WebHelper.Get(new Uri(url), Constants.V4AcceptHeaderJsonFullMetadata, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, context.RequestHeaders);

            if (null != resp && HttpStatusCode.OK == resp.StatusCode)
            {
                var jObj = JObject.Parse(resp.ResponsePayload);
                var jArr = jObj.GetValue("value") as JArray;
                var temp = ((JObject)(jArr.First))[keyPropName];
                if (null == temp)
                {
                    return(passed);
                }

                var    keyPropVal = temp.ToString();
                string pattern    = "Edm.String" == keyPropType ? "{0}('{1}')/{2}/$value" : "{0}({1})/{2}/$value";
                url  = string.Format(pattern, url, keyPropVal, keyPropName);
                resp = WebHelper.Get(new Uri(url), string.Empty, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, context.RequestHeaders);
                var detail = new ExtensionRuleResultDetail("ServiceImpl_SystemQueryOptionValue", url, HttpMethod.Get, string.Empty);
                info = new ExtensionRuleViolationInfo(new Uri(url), string.Empty, detail);
                if (null != resp && HttpStatusCode.OK == resp.StatusCode)
                {
                    passed = resp.ResponsePayload == keyPropVal;
                }
                else
                {
                    passed = false;
                }
            }

            return(passed);
        }
        /// <summary>
        /// Verifies the service implementation feature.
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out parameter to return violation information when rule does not pass</param>
        /// <returns>true if the service implementation feature passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;

            info = null;
            var    svcStatus = ServiceStatus.GetInstance();
            string entityTypeShortName;
            var    propNames = MetadataHelper.GetPropertyNames(
                "Edm.String",
                out entityTypeShortName,
                2,
                (elem) => {
                return(!(null != elem.Attribute("MaxLength") && elem.GetAttributeValue("MaxLength") == "max"));
            });

            if (null == propNames || propNames.Count < 2)
            {
                return(passed);
            }

            string propName1    = propNames[0];
            string propName2    = propNames[1];
            var    entitySetUrl = entityTypeShortName.MapEntityTypeShortNameToEntitySetURL();
            string url          = svcStatus.RootURL.TrimEnd('/') + "/" + entitySetUrl;
            var    resp         = WebHelper.Get(new Uri(url), string.Empty, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, svcStatus.DefaultHeaders);

            if (null != resp && HttpStatusCode.OK == resp.StatusCode)
            {
                JObject jObj     = JObject.Parse(resp.ResponsePayload);
                JArray  jArr     = jObj.GetValue(Constants.Value) as JArray;
                var     entity   = jArr.First as JObject;
                var     propVal1 = entity[propName1].ToString();
                var     propVal2 = entity[propName2].ToString();
                url  = string.Format("{0}?$filter=concat(concat({1}, ': '), {2}) eq '{3}: {4}'", url, propName1, propName2, propVal1, propVal2);
                resp = WebHelper.Get(new Uri(url), string.Empty, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, svcStatus.DefaultHeaders);
                var detail = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Get, string.Empty);
                info = new ExtensionRuleViolationInfo(new Uri(url), string.Empty, detail);
                if (null != resp && HttpStatusCode.OK == resp.StatusCode)
                {
                    jObj = JObject.Parse(resp.ResponsePayload);
                    jArr = jObj.GetValue(Constants.Value) as JArray;
                    foreach (JObject et in jArr)
                    {
                        passed = string.Format("{0}: {1}", et[propName1].ToString(), et[propName2].ToString()) == string.Format("{0}: {1}", propVal1, propVal2);
                    }
                }
                else
                {
                    passed = false;
                }
            }

            return(passed);
        }
        /// <summary>
        /// Verifies the service implementation feature.
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out parameter to return violation information when rule does not pass</param>
        /// <returns>true if the service implementation feature passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;

            info = null;
            var    svcStatus = ServiceStatus.GetInstance();
            string entityTypeShortName;
            var    propNames = MetadataHelper.GetPropertyNames("Edm.String", out entityTypeShortName);

            if (null == propNames || !propNames.Any())
            {
                return(passed);
            }

            string propName     = propNames[0];
            var    entitySetUrl = entityTypeShortName.MapEntityTypeShortNameToEntitySetURL();
            string url          = svcStatus.RootURL.TrimEnd('/') + "/" + entitySetUrl;
            var    resp         = WebHelper.Get(new Uri(url), string.Empty, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, svcStatus.DefaultHeaders);

            if (null != resp && HttpStatusCode.OK == resp.StatusCode)
            {
                JObject jObj    = JObject.Parse(resp.ResponsePayload);
                JArray  jArr    = jObj.GetValue(Constants.Value) as JArray;
                var     entity  = jArr.First as JObject;
                var     propVal = entity[propName].ToString();
                string  subStr  = propVal.Substring(propVal.Length / 2);
                url  = string.Format("{0}?$filter=contains({1}, '{2}')", url, propName, subStr);
                resp = WebHelper.Get(new Uri(url), string.Empty, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, svcStatus.DefaultHeaders);
                var detail = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Get, string.Empty);
                detail.URI                = url;
                detail.ResponsePayload    = resp.ResponsePayload;
                detail.ResponseHeaders    = resp.ResponseHeaders;
                detail.HTTPMethod         = "GET";
                detail.ResponseStatusCode = resp.StatusCode.ToString();

                info = new ExtensionRuleViolationInfo(new Uri(url), string.Empty, detail);
                if (null != resp && HttpStatusCode.OK == resp.StatusCode)
                {
                    jObj = JObject.Parse(resp.ResponsePayload);
                    jArr = jObj.GetValue(Constants.Value) as JArray;
                    foreach (JObject et in jArr)
                    {
                        passed = et[propName].ToString().Contains(subStr);
                    }
                }
                else
                {
                    passed = false;
                    detail.ErrorMessage = "The server returned an error response:  " + detail.ResponseStatusCode;
                }
            }

            return(passed);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Verifies the extension rule.
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out parameter to return violation information when rule does not pass</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?  passed             = null;
            string selectedName       = string.Empty;
            string functionactionName = "forFunctionAction";

            // Use the XPath query language to access the metadata document and get all Namespace and Alias value.
            XElement      metadata             = XElement.Parse(context.MetadataDocument);
            string        xpath                = @"//*[local-name()='DataServices']/*[local-name()='Schema']";
            List <string> appropriateNamespace = MetadataHelper.GetPropertyValues(context, xpath, "Namespace");

            // Use the XPath query language to access the metadata document and get all Function names and all Action names.
            xpath = @"//*[local-name()='EntityContainer']/*[local-name()='FunctionImport']";
            List <string> functionImportNames = MetadataHelper.GetPropertyValues(context, xpath, "Name");

            xpath = @"//*[local-name()='EntityContainer']/*[local-name()='ActionImport']";
            List <string> actionImportNames = MetadataHelper.GetPropertyValues(context, xpath, "Name");

            if (!functionImportNames.Contains(functionactionName) && !actionImportNames.Contains(functionactionName))
            {
                selectedName = functionactionName;
            }
            else
            {
                selectedName = functionactionName + "New";
            }

            string url = string.Format("{0}/?$select={1}.{2}", context.Destination.ToString().TrimEnd('/'), appropriateNamespace[0], selectedName);
            //var req = WebRequest.Create(url) as HttpWebRequest;
            //var response = WebHelper.Get(req, RuleEngineSetting.Instance().DefaultMaximumPayloadSize);//REPLACE HEADER
            var response = WebHelper.Get(url, null, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, context.RequestHeaders);
            ExtensionRuleResultDetail detail = new ExtensionRuleResultDetail(this.Name, url, "GET", string.Empty, response);

            if (response != null && response.StatusCode != null)
            {
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    passed = true;
                }
                else
                {
                    passed = false;
                    detail.ErrorMessage = "The OData service MUST fail any request that contains actions or functions that it does not understand.";
                }
            }
            else
            {
                passed = false;
                detail.ErrorMessage = String.Format("No response returned from above URI.");
            }

            info = new ExtensionRuleViolationInfo(context.Destination, context.ResponsePayload, detail);
            return(passed);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Verifies the service implementation feature.
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out parameter to return violation information when rule does not pass</param>
        /// <returns>true if the service implementation feature passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;

            info = null;
            var    svcStatus = ServiceStatus.GetInstance();
            string entityTypeShortName;
            var    navigPropNames = MetadataHelper.GetNavigationPropertyNames(
                out entityTypeShortName,
                null,
                (elem) => {
                return(!(null != elem.Attribute("Nullable") && elem.GetAttributeValue("Nullable") == "false"));
            });

            if (null == navigPropNames || !navigPropNames.Any())
            {
                return(passed);
            }

            string navigPropName = navigPropNames[0];

            navigPropNames.RemoveAt(0);
            var    entitySetUrl = entityTypeShortName.MapEntityTypeShortNameToEntitySetURL();
            string url          = string.Format("{0}/{1}?$expand={2}", svcStatus.RootURL.TrimEnd('/'), entitySetUrl, navigPropName);
            var    resp         = WebHelper.Get(new Uri(url), string.Empty, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, svcStatus.DefaultHeaders);
            var    detail       = new ExtensionRuleResultDetail("ServiceImpl_SystemQueryOptionExpand", url, HttpMethod.Get, string.Empty);

            info = new ExtensionRuleViolationInfo(new Uri(url), string.Empty, detail);
            if (null != resp && HttpStatusCode.OK == resp.StatusCode)
            {
                var jObj = JObject.Parse(resp.ResponsePayload);
                var jArr = jObj.GetValue("value") as JArray;
                foreach (JObject entity in jArr)
                {
                    passed = false;
                    foreach (JProperty prop in entity.Children())
                    {
                        if (prop.Name == navigPropName)
                        {
                            passed = true;
                            break;
                        }
                    }

                    if (passed == true)
                    {
                        break;
                    }
                }
            }

            return(passed);
        }
        /// <summary>
        /// Checks whether the context payload is a partial collection of entrities
        /// </summary>
        /// <param name="context">The service context</param>
        /// <returns>True if it is partial collection; false otherwise</returns>
        private static bool IsPartialColleclection(ServiceContext context)
        {
            bool anyNewEntry = false;

            JObject contextResponse = JsonParserHelper.GetResponseObject(context);

            if (contextResponse != null)
            {
                JArray contextEntries = JsonParserHelper.GetEntries(contextResponse);
                if (contextEntries.Count > 0)
                {
                    // if any more entries return, the context response payload was a partial collection
                    Uri prober = FeedCore2001.ConstructProbeUri(context);
                    var resp   = WebHelper.Get(prober, Constants.AcceptHeaderJson, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, context.RequestHeaders);

                    if (resp == null || string.IsNullOrEmpty(resp.ResponsePayload) || !JsonHelper.IsJsonVerboseFeed(resp.ResponsePayload))
                    {
                        return(false);
                    }

                    JObject response = JsonParserHelper.GetResponseObject(resp.ResponsePayload);
                    if (response != null)
                    {
                        JArray entries = JsonParserHelper.GetEntries(response);

                        if (entries.Count > 0)
                        {
                            // some producers do not respect $skipton;
                            // need to look at each entry to see whether there is any new entry.
                            HashSet <string> contextEntryKeys = new HashSet <string>(EqualityComparer <string> .Default);
                            foreach (var e in contextEntries)
                            {
                                if (e.Type == JTokenType.Object)
                                {
                                    var i = JsonParserHelper.GetTokenOfEntry((JObject)e);
                                    contextEntryKeys.Add(i);
                                }
                            }

                            foreach (var e in entries)
                            {
                                if (e.Type == JTokenType.Object)
                                {
                                    var i = JsonParserHelper.GetTokenOfEntry((JObject)e);
                                    if (!contextEntryKeys.Contains(i))
                                    {
                                        anyNewEntry = true;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return(anyNewEntry);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Verifies the service implementation feature.
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out parameter to return violation information when rule does not pass</param>
        /// <returns>true if the service implementation feature passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;

            info = null;
            var    svcStatus = ServiceStatus.GetInstance();
            string entityTypeShortName;
            var    propTypes = new string[1] {
                "Edm.DateTimeOffset"
            };
            var propNames = MetadataHelper.GetPropertyNames(propTypes, out entityTypeShortName);

            if (null == propNames || !propNames.Any())
            {
                return(passed);
            }

            string propName     = propNames[0];
            var    entitySetUrl = entityTypeShortName.GetAccessEntitySetURL();

            if (string.IsNullOrEmpty(entitySetUrl))
            {
                return(passed);
            }

            string url  = svcStatus.RootURL.TrimEnd('/') + "/" + entitySetUrl;
            var    resp = WebHelper.Get(new Uri(url), string.Empty, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, svcStatus.DefaultHeaders);

            if (null != resp && HttpStatusCode.OK == resp.StatusCode)
            {
                url  = string.Format("{0}?$filter={1} le maxdatetime()", url, propName);
                resp = WebHelper.Get(new Uri(url), string.Empty, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, svcStatus.DefaultHeaders);
                var detail = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Get, string.Empty);
                detail.URI                = url;
                detail.ResponsePayload    = resp.ResponsePayload;
                detail.ResponseHeaders    = resp.ResponseHeaders;
                detail.HTTPMethod         = "GET";
                detail.ResponseStatusCode = resp.StatusCode.ToString();

                info = new ExtensionRuleViolationInfo(new Uri(url), string.Empty, detail);
                if (null != resp && HttpStatusCode.OK == resp.StatusCode)
                {
                    passed = true;
                }
                else
                {
                    detail.ErrorMessage = "The server returned an error response:  " + detail.ResponseStatusCode;
                    passed = false;
                }
            }

            return(passed);
        }
        /// <summary>
        /// Verifies the extension rule.
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out parameter to return violation information when rule does not pass</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;
            bool?isInt64OrDecimalOrCountAsString = null;

            info = null;
            Response response = null;

            JObject jo;

            context.ResponsePayload.TryToJObject(out jo);

            string odataCount = Constants.V4OdataCount;

            if (context.Version == ODataVersion.V3)
            {
                odataCount = Constants.OdataCount;
            }

            if (context.PayloadType == RuleEngine.PayloadType.Entry || context.PayloadType == RuleEngine.PayloadType.Feed)
            {
                Uri absoluteUri = new Uri(context.Destination.OriginalString.Split('?')[0]);
                Uri relativeUri = new Uri("?$format=application/json;odata.metadata=full;IEEE754Compatible=true", UriKind.Relative);
                Uri combinedUri = new Uri(absoluteUri, relativeUri);

                // Send full metadata request.
                response = WebHelper.Get(combinedUri, Constants.AcceptHeaderJson, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, context.RequestHeaders);

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    response.ResponsePayload.TryToJObject(out jo);
                }
            }

            isInt64OrDecimalOrCountAsString = IsInt64OrDecimalAsString(jo, context.PayloadType, odataCount);
            if (isInt64OrDecimalOrCountAsString.HasValue && isInt64OrDecimalOrCountAsString.Value == true)
            {
                string contentType = response.ResponseHeaders.GetHeaderValue("Content-Type");

                if (Regex.Replace(contentType, @"\s+", "").Contains("IEEE754Compatible=true;"))
                {
                    passed = true;
                }
                else
                {
                    passed = false;
                    info   = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload);
                }
            }

            return(passed);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Verifies the service implementation feature.
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out parameter to return violation information when rule does not pass</param>
        /// <returns>true if the service implementation feature passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;

            info = null;
            var    svcStatus = ServiceStatus.GetInstance();
            string entityTypeShortName;
            var    propNames = MetadataHelper.GetPropertyNames(out entityTypeShortName);

            if (null == propNames || !propNames.Any())
            {
                return(passed);
            }

            string propName = propNames[0];

            propNames.RemoveAt(0);
            var    entitySetUrl = entityTypeShortName.MapEntityTypeShortNameToEntitySetURL();
            string url          = string.Format("{0}/{1}?$select={2}", svcStatus.RootURL.TrimEnd('/'), entitySetUrl, propName);
            var    resp         = WebHelper.Get(new Uri(url), string.Empty, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, svcStatus.DefaultHeaders);
            var    detail       = new ExtensionRuleResultDetail("ServiceImpl_SystemQueryOptionSelect", url, HttpMethod.Get, string.Empty);

            detail.URI                = url;
            detail.ResponsePayload    = resp.ResponsePayload;
            detail.ResponseHeaders    = resp.ResponseHeaders;
            detail.HTTPMethod         = "GET";
            detail.ResponseStatusCode = resp.StatusCode.ToString();

            info = new ExtensionRuleViolationInfo(new Uri(url), string.Empty, detail);
            if (null != resp && HttpStatusCode.OK == resp.StatusCode)
            {
                var jObj = JObject.Parse(resp.ResponsePayload);
                var jArr = jObj.GetValue("value") as JArray;
                foreach (JObject entity in jArr)
                {
                    foreach (JProperty prop in entity.Children())
                    {
                        passed = true;
                        if (propNames.Contains(prop.Name))
                        {
                            detail.ErrorMessage = propNames + " does not contain " + prop.Name;

                            passed = false;
                            break;
                        }
                    }
                }
            }

            return(passed);
        }
        /// <summary>
        /// Verifies the service implementation feature.
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out parameter to return violation information when rule does not pass</param>
        /// <returns>true if the service implementation feature passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;

            info = null;
            var    svcStatus = ServiceStatus.GetInstance();
            string entityTypeShortName;
            var    keyProp = MetadataHelper.GetKeyProperty(out entityTypeShortName);

            if (null == keyProp || string.IsNullOrEmpty(entityTypeShortName))
            {
                return(passed);
            }

            string keyPropName  = keyProp.Item1;
            string keyPropType  = keyProp.Item2;
            string entitySetUrl = entityTypeShortName.MapEntityTypeShortNameToEntitySetURL();

            if (string.IsNullOrEmpty(entitySetUrl))
            {
                return(passed);
            }

            string url  = svcStatus.RootURL.TrimEnd('/') + "/" + entitySetUrl;
            var    resp = WebHelper.Get(new Uri(url), string.Empty, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, svcStatus.DefaultHeaders);

            if (null == resp || HttpStatusCode.OK != resp.StatusCode)
            {
                return(passed);
            }

            var    jObj       = JObject.Parse(resp.ResponsePayload);
            string keyPropVal = jObj.GetValue(Constants.Value).First[keyPropName].ToString();
            string pattern    = "Edm.String" == keyPropType ? "{0}/$entity?$id={1}('{2}')" : "{0}/$entity?$id={1}({2})";

            url  = string.Format(pattern, svcStatus.RootURL.TrimEnd('/'), svcStatus.RootURL.TrimEnd('/') + "/" + entitySetUrl, keyPropVal);
            resp = WebHelper.Get(new Uri(url), string.Empty, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, svcStatus.DefaultHeaders);
            var detail = new ExtensionRuleResultDetail("ServiceImpl_SystemQueryOptionEntity_Id", url, HttpMethod.Get, string.Empty);

            info = new ExtensionRuleViolationInfo(new Uri(url), string.Empty, detail);
            if (null != resp && HttpStatusCode.OK == resp.StatusCode)
            {
                passed = true;
            }
            else
            {
                passed = false;
            }

            return(passed);
        }
        /// <summary>
        /// Verifies the semantic rule
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out paramater to return violation information when rule does not pass</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool passed = true;

            info = null;

            string   segment             = context.Destination.GetLeftPart(UriPartial.Path).Trim('/');
            XElement meta                = XElement.Parse(context.MetadataDocument);
            string   xpath               = string.Format(".//*[local-name() = 'EntityType' and @Name = '{0}' and @m:HasStream = 'true']", context.EntityTypeShortName);
            var      entityTypeHasStream = meta.XPathSelectElement(xpath, ODataNamespaceManager.Instance) != null;

            Uri resource = new Uri(context.ServiceBaseUri, segment + "/$value");
            var resp     = WebResponseHelper.GetWithHeaders(resource, false, null, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, context);

            if (resp.StatusCode.HasValue)
            {
                int statusCode = (int)resp.StatusCode.Value;
                if (statusCode >= 200 && statusCode < 300)
                {
                    // ensure metadata document defines HasStream attribute for the entity type
                    passed = entityTypeHasStream;
                    if (!passed)
                    {
                        passed = false;
                        info   = new ExtensionRuleViolationInfo("URI-17 is not associated to a MLE", context.Destination, "");
                    }
                }
                else
                {
                    // ensure metadata document does not defines HasStream attribute for the entity type
                    passed = !entityTypeHasStream;
                    if (!passed)
                    {
                        passed = false;
                        info   = new ExtensionRuleViolationInfo("URI-17 does not return the media resource", context.Destination, "");
                    }
                }
            }
            else
            {
                passed = !entityTypeHasStream;
                if (!passed)
                {
                    passed = false;
                    info   = new ExtensionRuleViolationInfo("URI-17 does not return the media resource", context.Destination, "");
                }
            }

            return(passed);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Verify Common.Core.4010
        /// </summary>
        /// <param name="context">Service context</param>
        /// <param name="info">out parameter to return violation information when rule fail</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;

            info = null;
            bool isSupportStream = false;

            Uri absoluteUri = new Uri(context.Destination.OriginalString.Split('?')[0]);
            Uri combinedUri = new Uri(absoluteUri.AbsoluteUri);

            // Send request with odata.streaming=true query parameter.
            string   acceptHeader = "application/json;odata.streaming=true";
            Response response     = WebHelper.Get(combinedUri, acceptHeader, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, context.RequestHeaders);

            if (response != null && !string.IsNullOrEmpty(response.ResponseHeaders))
            {
                // Get Content-Type from response headers.
                string   contentType = response.ResponseHeaders.GetHeaderValue("Content-Type");
                string[] elements    = contentType.Split(';');

                foreach (string element in elements)
                {
                    // Whether odata.streaming exist in response header.
                    if (Regex.Replace(element, @"\s", "").Equals("odata.streaming=true"))
                    {
                        isSupportStream = true;
                        break;
                    }
                    else
                    {
                        isSupportStream = false;
                    }
                }

                if (!isSupportStream)
                {
                    if (response.StatusCode == HttpStatusCode.NotAcceptable)
                    {
                        passed = true;
                    }
                    else
                    {
                        passed = false;
                        info   = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload);
                    }
                }
            }

            return(passed);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Verify the rule
        /// </summary>
        /// <param name="context">Service context</param>
        /// <param name="info">out parameter to return violation information when rule fail</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;

            info = null;

            // if concurrency token is not defined in metadata for the entity type,
            // verify the service in question returns 4xx code when If-Match header
            XElement meta;

            context.MetadataDocument.TryToXElement(out meta);
            string xpath = string.Format("//*[local-name()='EntityType' and @Name='{0}']/*[local-name()='Property' and @ConcurrencyMode='Fixed']",
                                         context.EntityTypeShortName);
            bool IsConcurrent = meta.XPathSelectElement(xpath, ODataNamespaceManager.Instance) != null;

            if (!IsConcurrent)
            {
                var headers = new List <KeyValuePair <string, string> > {
                    new KeyValuePair <string, string>("If-Match", "\t")
                };
                var resp = WebResponseHelper.GetWithHeaders(
                    context.Destination,
                    context.PayloadFormat == RuleEngine.PayloadFormat.Json,
                    headers,
                    RuleEngineSetting.Instance().DefaultMaximumPayloadSize,
                    context);

                if (resp.StatusCode.HasValue)
                {
                    int code = (int)resp.StatusCode.Value;
                    if (code >= 400 && code < 500)
                    {
                        passed = true;
                    }
                    else
                    {
                        info   = new ExtensionRuleViolationInfo(Resource.ExpectingError4xx, context.Destination, resp.StatusCode.Value.ToString());
                        passed = false;
                    }
                }
                else
                {
                    info   = new ExtensionRuleViolationInfo(Resource.ExpectingError4xx, context.Destination, null);
                    passed = false;
                }
            }

            return(passed);
        }
        /// <summary>
        /// Verifies the service implementation feature.
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out parameter to return violation information when rule does not pass</param>
        /// <returns>true if the service implementation feature passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;

            info = null;
            var    svcStatus          = ServiceStatus.GetInstance();
            string entitySetUrl       = MetadataHelper.GetEntitySetURLs().First();
            string entityTypeFullName = entitySetUrl.MapEntitySetURLToEntityTypeFullName();
            string url    = string.Format("{0}/{1}?$filter=isof('{2}')", svcStatus.RootURL.TrimEnd('/'), entitySetUrl, entityTypeFullName);
            var    resp   = WebHelper.Get(new Uri(url), string.Empty, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, svcStatus.DefaultHeaders);
            var    detail = new ExtensionRuleResultDetail(this.Name, url, HttpMethod.Get, string.Empty);

            detail.URI                = url;
            detail.ResponsePayload    = resp.ResponsePayload;
            detail.ResponseHeaders    = resp.ResponseHeaders;
            detail.HTTPMethod         = "GET";
            detail.ResponseStatusCode = resp.StatusCode.ToString();

            info = new ExtensionRuleViolationInfo(new Uri(url), string.Empty, detail);
            if (null != resp && HttpStatusCode.OK == resp.StatusCode)
            {
                JObject jObj = JObject.Parse(resp.ResponsePayload);
                JArray  jArr = jObj.GetValue(Constants.Value) as JArray;
                foreach (JObject entity in jArr)
                {
                    if (null == entity[Constants.V4OdataType])
                    {
                        passed = true;
                    }
                    else
                    {
                        passed = entity[Constants.V4OdataType].ToString() == entityTypeFullName;
                        if (passed == false)
                        {
                            detail.ErrorMessage = entity[Constants.V4OdataType].ToString() + " not equal to " + entityTypeFullName;
                            break;
                        }
                    }
                }
            }
            else
            {
                detail.ErrorMessage = "The server returned an error response:  " + detail.ResponseStatusCode;
                passed = false;
            }

            return(passed);
        }
            public Response GetResponse(Uri uri, ServiceContext ctx)
            {
                Response response;

                if (!this.TryGetValue(uri, out response))
                {
                    response = WebResponseHelper.GetWithHeaders(uri, false, null, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, ctx);
                    this.Add(uri, response);
                }

                return(response);
            }
        /// <summary>
        /// Verifies the semantic rule
        /// </summary>
        /// <param name="context">The Interop service context</param>
        /// <param name="info">out paramater to return violation information when rule does not pass</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool passed = true;

            info = null;

            // check there is only one segement in the relative path (after the service root uri)
            // ensure the segment is a URI-2
            string path;

            if (ResourcePathHelper.IsOneSegmentPath(context, out path))
            {
                if (RegexInUri.IsURI2(path, XElement.Parse(context.MetadataDocument)))
                {
                    // fetch the .../$count resource
                    Uri target = new Uri(context.DestinationBasePath + "/$count");
                    var resp   = WebResponseHelper.GetWithHeaders(
                        target,
                        false,  // $count response cannot be application/json Content-Type
                        null,
                        RuleEngineSetting.Instance().DefaultMaximumPayloadSize,
                        context);

                    if (resp.StatusCode.HasValue)
                    {
                        var  code = resp.StatusCode.Value;
                        bool isNonExistentCode = (code == System.Net.HttpStatusCode.NotFound) || (code == System.Net.HttpStatusCode.Gone);
                        if (isNonExistentCode)
                        {
                            passed = true;
                        }
                        else
                        {
                            passed = false;
                            info   = new ExtensionRuleViolationInfo("unexpected status code", target, code.ToString());
                        }
                    }
                    else
                    {
                        passed = false;
                        info   = new ExtensionRuleViolationInfo("no status code", target, null);
                    }
                }
            }

            return(passed);
        }