Beispiel #1
0
        private HttpWebRequest prepareRequest(string method, Uri uri, object data, IEnumerable <Tag> tags, bool expectBundleResponse)
        {
            byte[] body = null;

            Uri api = uri;

            if (UseFormatParam)
            {
                api = api.AddParam(HttpUtil.RESTPARAM_FORMAT, ContentType.BuildFormatParam(PreferredFormat));
            }

            var req = initializeRequest(api, method);

            if (!UseFormatParam)
            {
                req.Accept = ContentType.BuildContentType(PreferredFormat, forBundle: expectBundleResponse);
            }

            if (data is Binary)
            {
                var bin = (Binary)data;
                body            = bin.Content;
                req.ContentType = bin.ContentType;
            }
            else if (data is Resource)
            {
                body = PreferredFormat == ResourceFormat.Xml ?
                       FhirSerializer.SerializeResourceToXmlBytes((Resource)data) :
                       FhirSerializer.SerializeResourceToJsonBytes((Resource)data);

                req.ContentType = ContentType.BuildContentType(PreferredFormat, false);
            }
            else if (data is Bundle)
            {
                body = PreferredFormat == ResourceFormat.Xml ?
                       FhirSerializer.SerializeBundleToXmlBytes((Bundle)data) :
                       FhirSerializer.SerializeBundleToJsonBytes((Bundle)data);

                req.ContentType = ContentType.BuildContentType(PreferredFormat, true);
            }
            else if (data is TagList)
            {
                body = PreferredFormat == ResourceFormat.Xml ?
                       FhirSerializer.SerializeTagListToXmlBytes((TagList)data) :
                       FhirSerializer.SerializeTagListToJsonBytes((TagList)data);

                req.ContentType = ContentType.BuildContentType(PreferredFormat, false);
            }

            if (tags != null)
            {
                req.Headers[HttpUtil.CATEGORY] = HttpUtil.BuildCategoryHeader(tags);
            }

            if (body != null)
            {
                writeBody(req, body);
            }
            return(req);
        }
Beispiel #2
0
        public FhirResponse GetResponse(ResourceFormat?acceptFormat)
        {
            bool needsFormatParam = UseFormatParameter && acceptFormat.HasValue;

            var location = new RestUrl(_location);

            if (needsFormatParam)
            {
                location.AddParam(HttpUtil.RESTPARAM_FORMAT, ContentType.BuildFormatParam(acceptFormat.Value));
            }

            System.Diagnostics.Debug.WriteLine("{0}: {1}", _method, location.Uri.OriginalString);

            var request = createRequest(location.Uri, _method);

            if (acceptFormat != null && !UseFormatParameter)
            {
                request.Accept = ContentType.BuildContentType(acceptFormat.Value, forBundle: false);
            }

            if (_body != null)
            {
                request.WriteBody(_body);
                request.ContentType = _contentType;
                if (_contentLocation != null)
                {
                    request.Headers[HttpRequestHeader.ContentLocation] = _contentLocation;
                }
            }

            if (_categoryHeader != null)
            {
                request.Headers[HttpUtil.CATEGORY] = _categoryHeader;
            }

            FhirResponse result = null;

#if !PORTABLE45
            request.Timeout = Timeout;
#endif

            // Make sure the HttpResponse gets disposed!
            if (_beforeRequest != null)
            {
                _beforeRequest(request);
            }
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponseNoEx())
            {
                result = FhirResponse.FromHttpWebResponse(response);
                if (_afterRequest != null)
                {
                    _afterRequest(response);
                }
            }

            return(result);
        }
Beispiel #3
0
        public void SetBody(Bundle bundle, ResourceFormat format)
        {
            if (bundle == null)
            {
                throw Error.ArgumentNull("bundle");
            }

            _body = format == ResourceFormat.Xml ?
                    FhirSerializer.SerializeBundleToXmlBytes(bundle, summary: false) :
                    FhirSerializer.SerializeBundleToJsonBytes(bundle, summary: false);

            _contentType = ContentType.BuildContentType(format, forBundle: true);
        }
Beispiel #4
0
        public void SetBody(TagList tagList, ResourceFormat format)
        {
            if (tagList == null)
            {
                throw Error.ArgumentNull("tagList");
            }

            _body = format == ResourceFormat.Xml ?
                    FhirSerializer.SerializeTagListToXmlBytes(tagList) :
                    FhirSerializer.SerializeTagListToJsonBytes(tagList);

            _contentType = ContentType.BuildContentType(format, forBundle: false);
        }
Beispiel #5
0
        public async Task <WebResponse> GetResponseAsync(ResourceFormat?acceptFormat)
        {
            bool needsFormatParam = UseFormatParameter && acceptFormat.HasValue;

            var location = new RestUrl(_location);

            if (needsFormatParam)
            {
                location.AddParam(HttpUtil.RESTPARAM_FORMAT, ContentType.BuildFormatParam(acceptFormat.Value));
            }

            System.Diagnostics.Debug.WriteLine("(async) {0}: {1}", _method, location.ToString());

            HttpWebRequest request = createRequest(location.Uri, _method);

            if (acceptFormat != null && !UseFormatParameter)
            {
                request.Accept = ContentType.BuildContentType(acceptFormat.Value, forBundle: false);
            }

            if (_categoryHeader != null)
            {
                request.Headers[HttpUtil.CATEGORY] = _categoryHeader;
            }

            if (_body != null)
            {
                request.ContentType = _contentType;
                if (_contentLocation != null)
                {
                    request.Headers[HttpRequestHeader.ContentLocation] = _contentLocation;
                }
                await request.WriteBodyAsync(_body);
            }



            // Make sure the caller disposes the HttpResponse gets disposed...
            if (_beforeRequest != null)
            {
                _beforeRequest(request);
            }
            var response = await request.GetResponseAsync(TimeSpan.FromMilliseconds(Timeout));

            if (_afterRequest != null)
            {
                _afterRequest(response);
            }

            return(response);
        }
        private static void setContentAndContentType(HttpRequestMessage request, byte[] data, string contentType, ResourceFormat format)
        {
            if (data == null)
            {
                throw Error.ArgumentNull(nameof(data));
            }

            request.Content = new ByteArrayContent(data);

            if (contentType == null)
            {
                contentType = ContentType.BuildContentType(format, forBundle: false);
            }

            request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(contentType);
        }
Beispiel #7
0
        public void SetBody(Resource resource, ResourceFormat format)
        {
            if (resource == null)
            {
                throw Error.ArgumentNull("resource");
            }

            if (resource is Binary)
            {
                var bin = (Binary)resource;
                _body        = bin.Content;
                _contentType = bin.ContentType;
            }
            else
            {
                _body = format == ResourceFormat.Xml ?
                        FhirSerializer.SerializeResourceToXmlBytes(resource, summary: false) :
                        FhirSerializer.SerializeResourceToJsonBytes(resource, summary: false);

                _contentType = ContentType.BuildContentType(format, forBundle: false);
            }
        }
        public static HttpRequestMessage ToHttpRequestMessage(this EntryRequest entry, Uri baseUrl, FhirClientSettings settings)
        {
            System.Diagnostics.Debug.WriteLine("{0}: {1}", entry.Method, entry.Url);

            if (entry.RequestBodyContent != null && !(entry.Method == HTTPVerb.POST || entry.Method == HTTPVerb.PUT))
            {
                throw Error.InvalidOperation("Cannot have a body on an Http " + entry.Method.ToString());
            }

            // Create an absolute uri when the interaction.Url is relative.
            var uri = new Uri(entry.Url, UriKind.RelativeOrAbsolute);

            if (!uri.IsAbsoluteUri)
            {
                uri = HttpUtil.MakeAbsoluteToBase(uri, baseUrl);
            }

            var location = new RestUrl(uri);

            if (settings.UseFormatParameter)
            {
                location.AddParam(HttpUtil.RESTPARAM_FORMAT, ContentType.BuildFormatParam(settings.PreferredFormat));
            }

            var request = new HttpRequestMessage(getMethod(entry.Method), location.Uri);

            request.Headers.Add("User-Agent", ".NET FhirClient for FHIR " + entry.Agent);

            if (!settings.UseFormatParameter)
            {
                request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse(ContentType.BuildContentType(settings.PreferredFormat, forBundle: false)));
            }

            if (entry.Headers.IfMatch != null)
            {
                request.Headers.Add("If-Match", entry.Headers.IfMatch);
            }
            if (entry.Headers.IfNoneMatch != null)
            {
                request.Headers.Add("If-None-Match", entry.Headers.IfNoneMatch);
            }
            if (entry.Headers.IfModifiedSince != null)
            {
                request.Headers.IfModifiedSince = entry.Headers.IfModifiedSince.Value.UtcDateTime;
            }
            if (entry.Headers.IfNoneExist != null)
            {
                request.Headers.Add("If-None-Exist", entry.Headers.IfNoneExist);
            }

            var interactionType = entry.Type;

            bool canHaveReturnPreference() => entry.Type == InteractionType.Create ||
            entry.Type == InteractionType.Update ||
            entry.Type == InteractionType.Patch;

            if (canHaveReturnPreference() && settings.PreferredReturn != null)
            {
                if (settings.PreferredReturn == Prefer.RespondAsync)
                {
                    request.Headers.Add("Prefer", PrimitiveTypeConverter.ConvertTo <string>(settings.PreferredReturn));
                }
                else
                {
                    request.Headers.Add("Prefer", "return=" + PrimitiveTypeConverter.ConvertTo <string>(settings.PreferredReturn));
                }
            }

            else if (interactionType == InteractionType.Search && settings.PreferredParameterHandling != null)
            {
                List <string> preferHeader = new List <string>();
                if (settings.PreferredParameterHandling.HasValue)
                {
                    preferHeader.Add("handling=" + settings.PreferredParameterHandling.GetLiteral());
                }
                if (settings.PreferredReturn.HasValue && settings.PreferredReturn == Prefer.RespondAsync)
                {
                    preferHeader.Add(settings.PreferredReturn.GetLiteral());
                }
                if (preferHeader.Count > 0)
                {
                    request.Headers.Add("Prefer", string.Join(", ", preferHeader));
                }
            }


            if (entry.RequestBodyContent != null)
            {
                setContentAndContentType(request, entry.RequestBodyContent, entry.ContentType, settings.PreferredFormat);
            }

            return(request);
        }
        public static HttpWebRequest ToHttpWebRequest(this EntryRequest entry, Uri baseUrl, FhirClientSettings settings)
        {
            System.Diagnostics.Debug.WriteLine("{0}: {1}", (object)entry.Method, (object)entry.Url);

            if (entry.RequestBodyContent != null && !(entry.Method == HTTPVerb.POST || entry.Method == HTTPVerb.PUT))
            {
                throw Error.InvalidOperation((string)("Cannot have a body on an Http " + entry.Method.ToString()));
            }

            // Create an absolute uri when the interaction.Url is relative.
            var uri = new Uri(entry.Url, UriKind.RelativeOrAbsolute);

            if (!uri.IsAbsoluteUri)
            {
                uri = HttpUtil.MakeAbsoluteToBase(uri, baseUrl);
            }

            var location = new RestUrl(uri);



            if (settings.UseFormatParameter)
            {
                location.AddParam(HttpUtil.RESTPARAM_FORMAT, ContentType.BuildFormatParam(settings.PreferredFormat));
            }

            var request = (HttpWebRequest)HttpWebRequest.Create(location.Uri);

            request.Method = entry.Method.ToString();
            setAgent(request, ".NET FhirClient for FHIR " + entry.Agent);

            if (!settings.UseFormatParameter)
            {
                request.Accept = ContentType.BuildContentType(settings.PreferredFormat, forBundle: false);
            }

            request.ContentType = entry.ContentType ?? ContentType.BuildContentType(settings.PreferredFormat, forBundle: false);

            if (entry.Headers.IfMatch != null)
            {
                request.Headers["If-Match"] = entry.Headers.IfMatch;
            }
            if (entry.Headers.IfNoneMatch != null)
            {
                request.Headers["If-None-Match"] = entry.Headers.IfNoneMatch;
            }
#if NETSTANDARD1_1
            if (entry.Headers.IfModifiedSince != null)
            {
                request.Headers["If-Modified-Since"] = entry.Headers.IfModifiedSince.Value.UtcDateTime.ToString();
            }
#else
            if (entry.Headers.IfModifiedSince != null)
            {
                request.IfModifiedSince = entry.Headers.IfModifiedSince.Value.UtcDateTime;
            }
#endif
            if (entry.Headers.IfNoneExist != null)
            {
                request.Headers["If-None-Exist"] = entry.Headers.IfNoneExist;
            }

            if (canHaveReturnPreference() && settings.PreferredReturn.HasValue)
            {
                if (settings.PreferredReturn == Prefer.RespondAsync)
                {
                    request.Headers["Prefer"] = PrimitiveTypeConverter.ConvertTo <string>(settings.PreferredReturn);
                }
                else
                {
                    request.Headers["Prefer"] = "return=" + PrimitiveTypeConverter.ConvertTo <string>(settings.PreferredReturn);
                }
            }
            else if (entry.Type == InteractionType.Search)
            {
                List <string> preferHeader = new List <string>();
                if (settings.PreferredParameterHandling.HasValue)
                {
                    preferHeader.Add("handling=" + settings.PreferredParameterHandling.GetLiteral());
                }
                if (settings.PreferredReturn.HasValue && settings.PreferredReturn == Prefer.RespondAsync)
                {
                    preferHeader.Add(settings.PreferredReturn.GetLiteral());
                }
                if (preferHeader.Count > 0)
                {
                    request.Headers["Prefer"] = string.Join(", ", preferHeader);
                }
            }


            bool canHaveReturnPreference() => entry.Type == InteractionType.Create ||
            entry.Type == InteractionType.Update ||
            entry.Type == InteractionType.Patch;

            // PCL doesn't support setting the length (and in this case will be empty anyway)
#if !NETSTANDARD1_1
            if (entry.RequestBodyContent == null)
            {
                request.ContentLength = 0;
            }
#endif
            return(request);
        }