/// <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>
        /// Verify Metadata.Core.4020
        /// </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;

            XmlDocument metadata = new XmlDocument();

            metadata.LoadXml(context.MetadataDocument);
            string xpath = @"/*[local-name()='Edmx']/*[local-name()='Reference' and @Uri]/*[local-name()='Include' and @Namespace]";
            
            XmlNodeList includeElements = metadata.SelectNodes(xpath);

            foreach (XmlNode include in includeElements)
            {
                XmlDocument referencedCSDL = new XmlDocument();
                try
                {
                    WebRequest req = WebRequest.Create(include.ParentNode.Attributes["Uri"].Value);
                    Response resp = WebResponseHelper.Get(req as HttpWebRequest, null, RuleEngineSetting.Instance().DefaultMaximumPayloadSize);
                    referencedCSDL.LoadXml(resp.ResponsePayload);
                }
                catch (Exception e)
                {
                    if (!ExceptionHelper.IsCatchableExceptionType(e))
                    { throw; }
                }

                // Set to false now, will change to true if find a match.
                passed = false;
                string schemaXPath = @"/edmx:Edmx/edmx:DataServices/edm:Schema";
                XmlNodeList schemaElements = referencedCSDL.SelectNodes(schemaXPath, ODataNamespaceManager.Instance);
                if (schemaElements.Count == 0) { break; }

                foreach (XmlNode referencedSchema in schemaElements)
                {
                    if (referencedSchema.Attributes["Namespace"] == null)
                    {
                        break;
                    }
                    if (include.Attributes["Namespace"].Value == referencedSchema.Attributes["Namespace"].Value)
                    {
                        passed = true;
                    }
                }

                if (passed == false)
                {
                    break;
                }
            }
            
            info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload);
            return passed;
        }
 public void GetFileNameFromContentDispositionText()
 {
     "传入使用 UTF-8 编码的字符串,可以解析出文件名".Test(() =>
     {
         var contentDispositionText = "attachment; filename=__.dll; filename*=UTF-8''%E9%80%97%E6%AF%94.dll";
         var fileName = WebResponseHelper.GetFileNameFromContentDispositionText(contentDispositionText);
         Assert.AreEqual("逗比.dll", fileName);
     });
 }
Exemplo n.º 5
0
        private static HgResumeApiResponse HandleResponse(HttpWebResponse res)
        {
            var apiResponse = new HgResumeApiResponse();

            apiResponse.ResumableResponse = new HgResumeApiResponseHeaders(res.Headers);
            apiResponse.HttpStatus        = res.StatusCode;
            apiResponse.Content           = WebResponseHelper.ReadResponseContent(res);
            return(apiResponse);
        }
            protected override async Task <WebResponse> GetResponseAsync(WebRequest request)
            {
                var response = await request.GetResponseAsync();

                if (string.IsNullOrEmpty(ServerSuggestionFileName))
                {
                    ServerSuggestionFileName = WebResponseHelper.GetFileNameFromContentDisposition(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;

            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);
        }
Exemplo n.º 8
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);
        }
            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);
        }
        /// <summary>
        /// Verify Metadata.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;

            XmlDocument metadata = new XmlDocument();

            metadata.LoadXml(context.MetadataDocument);
            string      xpath             = @"/edmx:Edmx/edmx:Reference";
            XmlNodeList referenceElements = metadata.SelectNodes(xpath, ODataNamespaceManager.Instance);

            foreach (XmlNode reference in referenceElements)
            {
                if (reference.Attributes["Uri"] != null)
                {
                    try
                    {
                        WebRequest req  = WebRequest.Create(reference.Attributes["Uri"].Value);
                        Response   resp = WebResponseHelper.Get(req as HttpWebRequest, null, RuleEngineSetting.Instance().DefaultMaximumPayloadSize);

                        PayloadFormat          payloadFormat = resp.ResponsePayload.GetFormatFromPayload();
                        RuleEngine.PayloadType payloadType   = ContextHelper.GetPayloadType(resp.ResponsePayload, payloadFormat, resp.ResponseHeaders);
                        if (payloadType != RuleEngine.PayloadType.Metadata)
                        {
                            passed = false; break;
                        }
                        else
                        {
                            passed = true;
                        }
                    }
                    catch (Exception e)
                    {
                        if (!ExceptionHelper.IsCatchableExceptionType(e))
                        {
                            throw;
                        }
                        passed = false; break;
                    }
                }
            }

            info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload);
            return(passed);
        }
Exemplo n.º 12
0
        internal static WebResponseObject GetResponseObject(HttpResponseMessage response, Stream responseStream, ExecutionContext executionContext)
        {
            WebResponseObject output;

            if (WebResponseHelper.IsText(response))
            {
                output = new BasicHtmlWebResponseObject(response, responseStream);
            }
            else
            {
                output = new WebResponseObject(response, responseStream);
            }

            return(output);
        }
        /// <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 = false;

            string toAccept;

            if (TestingAcceptHeaders.TryGetValue(context.PayloadType, out toAccept))
            {
                var req     = WebRequest.Create(context.Destination);
                var reqHttp = req as HttpWebRequest;

                // TODO: make it to method
                // to carry over the request Http headers to be sent to server
                if (context.RequestHeaders != null)
                {
                    foreach (var head in context.RequestHeaders)
                    {
                        reqHttp.Headers[head.Key] = head.Value;
                    }
                }

                var resp = WebResponseHelper.Get(reqHttp, toAccept, RuleEngineSetting.Instance().DefaultMaximumPayloadSize);

                if (resp.StatusCode.HasValue)
                {
                    int statusCode = (int)resp.StatusCode.Value;
                    passed = statusCode >= 400 && statusCode < 500;
                    if (!passed.Value)
                    {
                        info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, resp.StatusCode.Value.ToString());
                    }
                }
                else
                {
                    passed = false;
                    info   = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, "no status code returned");
                }
            }


            return(passed);
        }
Exemplo n.º 14
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;

            // 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);
                    string payload = resp.ResponsePayload;
                    int    count;
                    if (Int32.TryParse(payload, out count))
                    {
                        passed = count == 1;
                    }
                    else
                    {
                        passed = false;
                    }

                    if (!passed.Value)
                    {
                        info = new ExtensionRuleViolationInfo("unexpected payload content", target, payload);
                    }
                }
            }

            return(passed);
        }
Exemplo n.º 15
0
        /// <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");
            }

            bool passed = false;

            info = null;
            string odataVersionString = "DataServiceVersion";

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

            var headers = new List <KeyValuePair <string, string> > {
                new KeyValuePair <string, string>(odataVersionString, "m.n")
            };
            var resp = WebResponseHelper.GetWithHeaders(
                context.Destination,
                context.PayloadFormat == RuleEngine.PayloadFormat.Json || context.PayloadFormat == RuleEngine.PayloadFormat.JsonLight,
                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());
                }
            }
            else
            {
                info = new ExtensionRuleViolationInfo(Resource.ExpectingError4xx, context.Destination, null);
            }

            return(passed);
        }
Exemplo n.º 16
0
        public void LogIn(out string error)
        {
            try
            {
                var response = LogIn();
                var content  = Encoding.UTF8.GetString(WebResponseHelper.ReadResponseContent(response, 300));
                HasLoggedIn        = true;
                error              = null;
                PasswordForSession = Password;
                // NB: I (Hasso) am tempted here to SaveUserSettings(); however,
                //  - if a user edits the settings for an already-received project, then clicks cancel,
                //		the user would expect all changes to be undone, and
                //  - if a user logs in to get a project from a colleague, the user is likely to click Download, which will save credentials.

                // Do this last so the user is "logged in" even if JSON parsing crashes
                PopulateAvailableProjects(content);
            }
            catch (WebException e)
            {
                HasLoggedIn = false;
                switch ((e.Response as HttpWebResponse)?.StatusCode)
                {
                case HttpStatusCode.NotFound:
                case HttpStatusCode.Forbidden:
                    error = LocalizationManager.GetString("ServerSettings.LogIn.BadUserOrPass", "Incorrect username or password");
                    if (IsPrivateServer)
                    {
                        HasLoggedIn = true;
                        error       = LocalizationManager.GetString("ServerSettings.PossibleErrorPrivateServer",
                                                                    "Your projects on the private server could not be listed, but you may still be able to download them.");
                    }
                    break;

                default:
                    error = e.Message;
                    break;
                }
            }
            catch (JsonReaderException)
            {
                error = LocalizationManager.GetString("ServerSettings.ErrorListingProjects",
                                                      "Your username and password are correct, but there was an error listing your projects. You can still try to download your project.");
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// Verify the code rule
        /// </summary>
        /// <param name="context">Service context</param>
        /// <param name="info">out paramater 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 no inlinecount is the target uri, fetch the one with this query option
            // and checks its structural
            RuleEngine.TestResult result;
            var queries = HttpUtility.ParseQueryString(context.Destination.Query);
            var count   = queries["$inlinecount"];

            if (count != null && count.Equals("allpages", StringComparison.Ordinal))
            {
                passed = JsonParserHelper.ValidateJson(jschema, context.ResponsePayload, out result);
                if (!passed.Value && result != null)
                {
                    info = new ExtensionRuleViolationInfo(result.ErrorDetail, context.Destination, context.ResponsePayload, result.LineNumberInError);
                }
            }
            else
            {
                queries["$inlinecount"] = "allpages";
                var qset = from z in queries.Cast <string>()
                           where !string.IsNullOrEmpty(queries[z])
                           select z + "=" + queries[z];
                var qstr      = string.Join("&", qset);
                var target    = context.Destination.GetLeftPart(UriPartial.Query) + "?" + qstr;
                Uri uriTarget = new Uri(target);
                var resp      = WebResponseHelper.GetWithHeaders(uriTarget, true, null, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, context);
                passed = JsonParserHelper.ValidateJson(jschema, resp.ResponsePayload, out result);
                if (!passed.Value && result != null)
                {
                    info = new ExtensionRuleViolationInfo(result.ErrorDetail, uriTarget, resp.ResponsePayload);
                }
            }

            return(passed);
        }
Exemplo n.º 18
0
        internal static StringBuilder GetRawContentHeader(HttpResponseMessage response)
        {
            StringBuilder raw = new();

            string protocol = WebResponseHelper.GetProtocol(response);

            if (!string.IsNullOrEmpty(protocol))
            {
                int    statusCode        = WebResponseHelper.GetStatusCode(response);
                string statusDescription = WebResponseHelper.GetStatusDescription(response);
                raw.AppendFormat("{0} {1} {2}", protocol, statusCode, statusDescription);
                raw.AppendLine();
            }

            HttpHeaders[] headerCollections =
            {
                response.Headers,
                response.Content?.Headers
            };

            foreach (var headerCollection in headerCollections)
            {
                if (headerCollection == null)
                {
                    continue;
                }

                foreach (var header in headerCollection)
                {
                    // Headers may have multiple entries with different values
                    foreach (var headerValue in header.Value)
                    {
                        raw.Append(header.Key);
                        raw.Append(": ");
                        raw.Append(headerValue);
                        raw.AppendLine();
                    }
                }
            }

            raw.AppendLine();
            return(raw);
        }
Exemplo n.º 19
0
        /// <summary>
        /// Verify the code 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;

            XElement meta;

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

            if (IsConcurrentMle)
            {
                // get ETag header value of the media resource
                XElement entry;
                context.ResponsePayload.TryToXElement(out entry);
                var m           = entry.XPathSelectElement("//atom:link[@rel='edit-media' and @href]", ODataNamespaceManager.Instance);
                var targetMedia = context.ServiceBaseUri.OriginalString.TrimEnd('/') + @"/" + m.GetAttributeValue("href");

                var         etag      = WebResponseHelper.GetETagOfEntry(targetMedia, Constants.AcceptHeaderAtom);
                string      rngSchema = string.Format(EntryCore2004.rngSchemaFormat, HttpUtility.HtmlEncode(etag));
                RngVerifier verifier  = new RngVerifier(rngSchema);
                TestResult  result;
                passed = verifier.Verify(context, out result);
                if (!passed.Value)
                {
                    info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload, result.LineNumberInError);
                }
            }

            return(passed);
        }
        /// <summary>
        /// Reads the response content from the web response.
        /// </summary>
        protected void InitializeContent()
        {
            string contentType = ContentHelper.GetContentType(BaseResponse);

            if (ContentHelper.IsText(contentType))
            {
                Encoding encoding = null;
                // fill the Content buffer
                string characterSet = WebResponseHelper.GetCharacterSet(BaseResponse);

                if (string.IsNullOrEmpty(characterSet) && ContentHelper.IsJson(contentType))
                {
                    characterSet = Encoding.UTF8.HeaderName;
                }

                this.Content  = StreamHelper.DecodeStream(RawContentStream, characterSet, out encoding);
                this.Encoding = encoding;
            }
            else
            {
                this.Content = string.Empty;
            }
        }
Exemplo n.º 21
0
        public List <Sprint> GetSprints()
        {
            var getSprintsJiraRestApiUrl = Properties.Settings.Default.JiraRestApiUrl + "agile/1.0/board/" + Properties.Settings.Default.JiraBoardId + "/sprint";
            var jiraApiResponse          = WebResponseHelper.GetWebResponse(Properties.Settings.Default.JiraUsername,
                                                                            Properties.Settings.Default.JiraPassword,
                                                                            getSprintsJiraRestApiUrl);
            var xmlJiraApiResponse = JsonToXmlHelper.JsonToXml(jiraApiResponse);

            var sprints = new List <Sprint>();

            foreach (XmlNode xmlNode in xmlJiraApiResponse.GetElementsByTagName("values"))
            {
                var sprintXml = "<Sprint>" + xmlNode.InnerXml + "</Sprint>";
                var sprint    = Sprint.DeserializeFromXml(sprintXml);

                var sprintIssues = this.GetSprintIssues(sprint.Id);
                sprint.SprintIssues = sprintIssues;

                sprints.Add(sprint);
            }

            return(sprints);
        }
Exemplo n.º 22
0
        /// <summary>
        /// Verify the code 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 entry in the feed has @m:etag, check @m:etag value is the same as ETag header value if single entry were represented.
            const string xpath = "//*[local-name()='entry' and @m:etag]";
            XElement     feed;

            context.ResponsePayload.TryToXElement(out feed);
            var x = feed.XPathSelectElements(xpath, ODataNamespaceManager.Instance);

            foreach (var e in x)
            {
                var href   = e.XPathSelectElement("atom:id", ODataNamespaceManager.Instance);
                var target = href.Value;
                // get the ETag header value for the entry
                var         etag      = WebResponseHelper.GetETagOfEntry(target, Constants.AcceptHeaderAtom);
                var         rngSchema = string.Format(FeedCore2003.rngSchemaFormat, HttpUtility.HtmlEncode(etag), HttpUtility.HtmlEncode(target), RngCommonPattern.CommonPatterns);
                RngVerifier verifier  = new RngVerifier(rngSchema);
                TestResult  result;
                passed = verifier.Verify(context, out result);
                if (!passed.Value)
                {
                    info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload, result.LineNumberInError);
                    break;
                }
            }

            return(passed);
        }
Exemplo n.º 23
0
        /// <summary>
        /// Verify the code rule
        /// </summary>
        /// <param name="context">Service context</param>
        /// <param name="info">out paramater 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;

            // for each entry within the collection (feed)
            // to check its __metadata.etag value (if existent) is the same as ETag header in the single entry response that would have been requested
            JObject feed;

            context.ResponsePayload.TryToJObject(out feed);
            ODataVersion version    = JsonParserHelper.GetPayloadODataVersion(feed);
            var          entries    = JsonParserHelper.GetEntries(feed);
            int          indexEntry = 0;
            int          count      = entries.Count;

            foreach (JObject e in entries)
            {
                var  etag        = e.GetPropertyOfElement("__metadata", "etag");
                bool etagInPlace = etag != null;
                if (etagInPlace)
                {
                    var targetSingleEntry = e.GetPropertyOfElement("__metadata", "uri");
                    // get the ETag header value for the entry
                    var etagInSingleEntry = WebResponseHelper.GetETagOfEntry(targetSingleEntry, Constants.AcceptHeaderAtom);

                    JSconSchemaBuilder builder;
                    if (version == ODataVersion.V2)
                    {
                        builder = new JSconSchemaBuilder(jschemaV2Header, jschemaV2Tail);
                    }
                    else
                    {
                        builder = new JSconSchemaBuilder(jschemaV1Header, jschemaV1Tail);
                    }

                    for (int i = 0; i < indexEntry; i++)
                    {
                        builder.AddItem("{},");
                    }

                    var    etagLiteral = StringHelper.ToLiteral(etagInSingleEntry);
                    string entryCore   = string.Format(entryCoreFormat, etagLiteral);
                    builder.AddItem(entryCore);

                    for (int i = indexEntry + 1; i < count; i++)
                    {
                        builder.AddItem(",{}");
                    }

                    var jSchema = builder.GetProduct();
                    RuleEngine.TestResult result = null;
                    passed = JsonParserHelper.ValidateJson(jSchema, context.ResponsePayload, out result);
                    if (!passed.Value)
                    {
                        info = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload, result != null ? result.LineNumberInError : -1);
                        break;
                    }
                }

                indexEntry++;
            }

            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;

            // get the first segment after the service root URI
            char[] delimiters   = new char[] { '/' };
            string path         = context.DestinationBasePath.Substring(context.ServiceBaseUri.AbsoluteUri.Length).Trim('/');
            string firstSegment = path.IndexOfAny(delimiters) >= 0 ? path.Substring(0, path.IndexOfAny(delimiters)) : path;

            firstSegment = firstSegment.Trim('/');

            // check whether the first segment is URI-2
            if (RegexInUri.IsURI2(firstSegment, XElement.Parse(context.MetadataDocument)))
            {
                if (!firstSegment.Equals(path.Trim('/')))
                {
                    Uri resource = new Uri(context.ServiceBaseUri, firstSegment);
                    var resp     = WebResponseHelper.GetWithHeaders(resource,
                                                                    context.PayloadFormat == RuleEngine.PayloadFormat.Json,
                                                                    null,
                                                                    RuleEngineSetting.Instance().DefaultMaximumPayloadSize,
                                                                    context);
                    if (resp.StatusCode.HasValue)
                    {
                        int statusCode = (int)resp.StatusCode.Value;
                        if (statusCode < 100 || statusCode >= 400)
                        {
                            if (!(context.HttpStatusCode.Value == System.Net.HttpStatusCode.NotFound || context.HttpStatusCode.Value == System.Net.HttpStatusCode.Gone))
                            {
                                passed = false;
                                info   = new ExtensionRuleViolationInfo("unexpected status code " + context.HttpStatusCode.Value.ToString(), context.Destination, context.HttpStatusCode.Value.ToString());
                            }
                            else if (context.PayloadType != RuleEngine.PayloadType.Error)
                            {
                                passed = false;
                                info   = new ExtensionRuleViolationInfo("error payload expected", context.Destination, context.PayloadType.ToString());
                            }
                        }
                    }
                }
                else
                {
                    if (context.PayloadType == RuleEngine.PayloadType.Error)
                    {
                        int statusCode = (int)context.HttpStatusCode.Value;
                        passed = statusCode >= 400 && statusCode < 500;
                        if (!passed)
                        {
                            info = new ExtensionRuleViolationInfo("unexpected HTTP status code", context.Destination, context.HttpStatusCode.Value.ToString());
                        }
                    }
                }
            }

            return(passed);
        }