< Summary - SonghayCore

Information
Class: Songhay.Extensions.HttpWebRequestExtensions
Assembly: SonghayCore
File(s): /home/rasx/sourceRoot/SonghayCore/SonghayCore/Extensions/HttpWebRequestExtensions.cs
Line coverage
0%
Covered lines: 0
Uncovered lines: 106
Coverable lines: 106
Total lines: 257
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 32
Branch coverage: 0%
Method coverage

Method coverage is only available for sponsors.

Upgrade to PRO version

Metrics

File(s)

/home/rasx/sourceRoot/SonghayCore/SonghayCore/Extensions/HttpWebRequestExtensions.cs

#LineLine coverage
 1namespace Songhay.Extensions;
 2
 3/// <summary>
 4/// Extensions of <see cref="HttpWebRequest"/>
 5/// </summary>
 6public static class HttpWebRequestExtensions
 7{
 8    /// <summary>
 9    /// Downloads to file.
 10    /// </summary>
 11    /// <param name="request">The request.</param>
 12    /// <param name="path">The path.</param>
 13    public static void DownloadToFile(this HttpWebRequest? request, string? path) =>
 014        request.DownloadToFile(path, null, bypassProxy: true);
 15
 16    /// <summary>
 17    /// Downloads to file.
 18    /// </summary>
 19    /// <param name="request">The request.</param>
 20    /// <param name="path">The path.</param>
 21    /// <param name="proxyLocation">The proxy location.</param>
 22    /// <param name="bypassProxy">if set to <c>true</c> [bypass proxy].</param>
 23    public static void DownloadToFile(this HttpWebRequest? request, string? path, Uri? proxyLocation, bool bypassProxy)
 024    {
 025        if (request == null) return;
 026        path.ThrowWhenNullOrWhiteSpace();
 27
 028        var buffer = new byte[32768];
 029        var fileName = Path.GetFileName(path);
 30
 031        request.Headers.Add("Content-Disposition", $"attachment; filename={fileName}");
 32
 033        var response = request
 034            .WithProxy(proxyLocation, bypassProxy)
 035            .ToHttpWebResponse()
 036            .ToReferenceTypeValueOrThrow();
 37
 038        var stream = response.GetResponseStream();
 39        try
 040        {
 041            using var fs = File.Create(path);
 42
 43            int bytesRead;
 044            while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
 045            {
 046                fs.Write(buffer, 0, bytesRead);
 047            }
 048        }
 49        finally
 050        {
 051            stream.Close();
 052            response.Close();
 053        }
 054    }
 55
 56    /// <summary>
 57    /// Downloads to string.
 58    /// </summary>
 59    /// <param name="request">The request.</param>
 60    public static string? DownloadToString(this HttpWebRequest? request) =>
 061        request.DownloadToString(null, bypassProxy: true);
 62
 63    /// <summary>
 64    /// Downloads to string.
 65    /// </summary>
 66    /// <param name="request">The request.</param>
 67    /// <param name="proxyLocation">The proxy location</param>
 68    /// <param name="bypassProxy">when <c>true</c>, bypass proxy</param>
 69    public static string? DownloadToString(this HttpWebRequest? request, Uri? proxyLocation, bool bypassProxy)
 070    {
 071        if (request == null) return null;
 72
 73        string? content;
 074        var response = request
 075            .WithProxy(proxyLocation, bypassProxy)
 076            .ToHttpWebResponse()
 077            .ToReferenceTypeValueOrThrow();
 78        try
 079        {
 080            using var sr = new StreamReader(response.GetResponseStream());
 81
 082            content = sr.ReadToEnd();
 083        }
 84        finally
 085        {
 086            response.Close();
 087        }
 88
 089        return content;
 090    }
 91
 92    /// <summary>
 93    /// Posts the form.
 94    /// </summary>
 95    /// <param name="request">The request.</param>
 96    /// <param name="postData">The post data.</param>
 97    public static string? PostForm(this HttpWebRequest? request, Hashtable? postData) =>
 098        request.PostForm(postData, proxyLocation: null, bypassProxy: true);
 99
 100    /// <summary>
 101    /// Posts the form.
 102    /// </summary>
 103    /// <param name="request">The request.</param>
 104    /// <param name="postData">The post data.</param>
 105    /// <param name="proxyLocation">The proxy location.</param>
 106    /// <param name="bypassProxy">if set to <c>true</c> [bypass proxy].</param>
 107    public static string? PostForm(this HttpWebRequest? request, Hashtable? postData,
 108        Uri? proxyLocation, bool bypassProxy)
 0109    {
 0110        if (request == null) return null;
 0111        ArgumentNullException.ThrowIfNull(postData);
 112
 0113        var postParams = GetPostData(postData);
 114
 0115        request
 0116            .WithProxy(proxyLocation, bypassProxy)
 0117            .WithRequestBody(postParams, "POST", MimeTypes.ApplicationFormUrlEncoded);
 118
 0119        var response = request.DownloadToString();
 120
 0121        return response;
 0122    }
 123
 124    /// <summary>
 125    /// Posts the XML.
 126    /// </summary>
 127    /// <param name="request">The request.</param>
 128    /// <param name="xmlFragment">The XML fragment.</param>
 129    public static string? PostXml(this HttpWebRequest? request, string? xmlFragment) =>
 0130        request.PostXml(xmlFragment, null, bypassProxy: true);
 131
 132    /// <summary>
 133    /// Posts the XML.
 134    /// </summary>
 135    /// <param name="request">The request.</param>
 136    /// <param name="xmlFragment">The XML fragment.</param>
 137    /// <param name="proxyLocation">The proxy location.</param>
 138    /// <param name="bypassProxy">if set to <c>true</c> [bypass proxy].</param>
 139    public static string? PostXml(this HttpWebRequest? request, string? xmlFragment, Uri? proxyLocation,
 140        bool bypassProxy)
 0141    {
 0142        if (request == null) return null;
 143
 0144        request
 0145            .WithProxy(proxyLocation, bypassProxy)
 0146            .WithRequestBody(xmlFragment, "POST", MimeTypes.TextXml);
 147
 0148        var response = request.DownloadToString();
 149
 0150        return response;
 0151    }
 152
 153    /// <summary>
 154    /// Converts the <see cref="HttpWebRequest"/> into a HTTP status code.
 155    /// </summary>
 156    /// <param name="request">The request.</param>
 157    public static HttpStatusCode ToHttpStatusCode(this HttpWebRequest? request)
 0158    {
 0159        if (request == null) return HttpStatusCode.Unused;
 160
 161        HttpStatusCode code;
 162        try
 0163        {
 0164            using var response = request.ToHttpWebResponse();
 165
 0166            code = response?.StatusCode ?? HttpStatusCode.Unused;
 0167        }
 0168        catch (WebException ex)
 0169        {
 0170            using HttpWebResponse? response = ex.Response as HttpWebResponse;
 171
 0172            code = response?.StatusCode ?? HttpStatusCode.Unused;
 0173        }
 174
 0175        return code;
 0176    }
 177
 178    /// <summary>
 179    /// Converts the <see cref="HttpWebRequest"/> into a HTTP web response.
 180    /// </summary>
 181    /// <param name="request">The request.</param>
 182    public static HttpWebResponse? ToHttpWebResponse(this HttpWebRequest? request) =>
 0183        request?.GetResponse() as HttpWebResponse;
 184
 185    /// <summary>
 186    /// Returns the <see cref="HttpWebRequest" />
 187    /// with a <see cref="WebProxy" />.
 188    /// </summary>
 189    /// <param name="request">The request.</param>
 190    /// <param name="proxyLocation">The proxy location.</param>
 191    /// <param name="bypassProxy">if set to <c>true</c> [bypass proxy].</param>
 192    public static HttpWebRequest? WithProxy(this HttpWebRequest? request, Uri? proxyLocation, bool bypassProxy)
 0193    {
 0194        if (request == null) return null;
 195
 0196        request.Credentials = CredentialCache.DefaultNetworkCredentials;
 197
 0198        if (proxyLocation != null && (!string.IsNullOrWhiteSpace(proxyLocation.AbsoluteUri)))
 0199            request.Proxy = new WebProxy(proxyLocation, bypassProxy);
 200
 0201        return request;
 0202    }
 203
 204    /// <summary>
 205    /// Returns <see cref="HttpWebRequest" /> with the request body.
 206    /// </summary>
 207    /// <param name="request">The request.</param>
 208    /// <param name="requestBody">The request body.</param>
 209    /// <param name="requestMethod">The request method.</param>
 210    public static HttpWebRequest? WithRequestBody(this HttpWebRequest? request, string? requestBody,
 0211        string? requestMethod) => request.WithRequestBody(requestBody, requestMethod, contentType: null);
 212
 213    /// <summary>
 214    /// Returns <see cref="HttpWebRequest" /> with the request body.
 215    /// </summary>
 216    /// <param name="request">The request.</param>
 217    /// <param name="requestBody">The request body.</param>
 218    /// <param name="requestMethod">The request method.</param>
 219    /// <param name="contentType">The request content type.</param>
 220    public static HttpWebRequest? WithRequestBody(this HttpWebRequest? request, string? requestBody,
 221        string? requestMethod, string? contentType)
 0222    {
 0223        if (request == null) return null;
 224
 0225        requestBody.ThrowWhenNullOrWhiteSpace();
 0226        requestMethod.ThrowWhenNullOrWhiteSpace();
 227
 0228        if (string.IsNullOrWhiteSpace(contentType)) contentType = MimeTypes.TextPlain;
 229
 0230        request.Method = requestMethod;
 0231        request.ContentType = contentType;
 232
 0233        byte[] body = Encoding.UTF8.GetBytes(requestBody);
 234
 0235        using Stream dataStream = request.GetRequestStream();
 236
 0237        dataStream.Write(body, 0, requestBody.Length);
 238
 0239        return request;
 0240    }
 241
 242    static string GetPostData(Hashtable postData)
 0243    {
 0244        var sb = new StringBuilder();
 0245        string s = sb.ToString();
 246
 0247        foreach (DictionaryEntry entry in postData)
 0248        {
 0249            s = (string.IsNullOrWhiteSpace(s))
 0250                ? string.Format(CultureInfo.InvariantCulture, "{0}={1}", entry.Key, entry.Value)
 0251                : string.Format(CultureInfo.InvariantCulture, "&{0}={1}", entry.Key, entry.Value);
 0252            sb.Append(s);
 0253        }
 254
 0255        return sb.ToString();
 0256    }
 257}