diff --git a/ExtLibs/DroneCAN/DroneCAN.cs b/ExtLibs/DroneCAN/DroneCAN.cs index 4e1380e60b..620807982c 100644 --- a/ExtLibs/DroneCAN/DroneCAN.cs +++ b/ExtLibs/DroneCAN/DroneCAN.cs @@ -6,6 +6,7 @@ using System.IO; using System.Linq; using System.Net; +using System.Net.Http; using System.Reflection; using System.Runtime.InteropServices; using System.Text; @@ -1059,15 +1060,14 @@ public string LookForUpdate(string devicename, double hwversion, bool usebeta = var url = String.Format("{0}{1}/{2}/{3}", server, devicename, hwversion.ToString("0.0##", CultureInfo.InvariantCulture), "firmware.bin"); Console.WriteLine("LookForUpdate at " + url); - var req = WebRequest.Create(url); - ((HttpWebRequest)req).UserAgent = Assembly.GetExecutingAssembly().GetName().Name; - req.Timeout = 4000; // miliseconds - req.Method = "HEAD"; + var client = new HttpClient(); + client.DefaultRequestHeaders.Add("User-Agent", Assembly.GetExecutingAssembly().GetName().Name); + client.Timeout = TimeSpan.FromSeconds(4); + var req = client.SendAsync(new HttpRequestMessage(HttpMethod.Head, url)).Result; try { - var res = (HttpWebResponse)req.GetResponse(); - if (res.StatusCode == HttpStatusCode.OK) + if (req.StatusCode == HttpStatusCode.OK) { Console.WriteLine("LookForUpdate valid url " + url); return url; diff --git a/ExtLibs/Utilities/Download.cs b/ExtLibs/Utilities/Download.cs index 09d8a3058d..d7c33dbb0d 100644 --- a/ExtLibs/Utilities/Download.cs +++ b/ExtLibs/Utilities/Download.cs @@ -14,6 +14,24 @@ namespace MissionPlanner.Utilities { + public static class DownloadExt + { + public static DateTime LastModified(this HttpContentHeaders headers) + { + if (headers.Any(h => h.Key.Equals("Last-Modified"))) + return DateTime.Parse(headers.First(h => h.Key.Equals("Last-Modified")).Value.First()); + return DateTime.MinValue; + } + + public static int ContentLength(this HttpContentHeaders headers) + { + if (headers.Any(h => h.Key.Equals("Content-Length"))) + return int.Parse(headers.First(h => h.Key.Equals("Content-Length")).Value.First()); + return -1; + } + } + + public class DownloadStream : Stream { private long _length; @@ -418,43 +436,39 @@ public static bool getFilefromNet(string url, string saveto, Action { lock (log) log.Info(url); - // Create a request using a URL that can receive a post. - WebRequest request = WebRequest.Create(url); - if (!String.IsNullOrEmpty(Settings.Instance.UserAgent)) - ((HttpWebRequest)request).UserAgent = Settings.Instance.UserAgent; - request.Timeout = 10000; - // Set the Method property of the request to POST. - request.Method = "GET"; + var client = new HttpClient(); + client.DefaultRequestHeaders.Add("User-Agent", Settings.Instance.UserAgent); + client.Timeout = TimeSpan.FromSeconds(10); + // Get the response. - WebResponse response = request.GetResponse(); + var response = client.GetAsync(url).Result; // Display the status. lock (log) - log.Info(((HttpWebResponse)response).StatusDescription); - if (((HttpWebResponse)response).StatusCode != HttpStatusCode.OK) + log.Info(response.ReasonPhrase); + if (!response.IsSuccessStatusCode) return false; if (File.Exists(saveto)) { DateTime lastfilewrite = new FileInfo(saveto).LastWriteTime; - DateTime lasthttpmod = ((HttpWebResponse)response).LastModified; + DateTime lasthttpmod = response.Content.Headers.LastModified(); if (lasthttpmod < lastfilewrite) { - if (((HttpWebResponse)response).ContentLength == new FileInfo(saveto).Length) + if (response.Content.Headers.ContentLength() == new FileInfo(saveto).Length) { lock (log) - log.Info("got LastModified " + saveto + " " + ((HttpWebResponse)response).LastModified + + log.Info("got LastModified " + saveto + " " + (response.Content.Headers).LastModified() + " vs " + new FileInfo(saveto).LastWriteTime); - response.Close(); return true; } } } // Get the stream containing content returned by the server. - Stream dataStream = response.GetResponseStream(); + Stream dataStream = response.Content.ReadAsStreamAsync().Result; - long bytes = response.ContentLength; + long bytes = response.Content.Headers.ContentLength(); long contlen = bytes; byte[] buf1 = new byte[1024]; @@ -493,7 +507,6 @@ public static bool getFilefromNet(string url, string saveto, Action fs.Close(); dataStream.Close(); - response.Close(); if (File.Exists(saveto)) { @@ -528,34 +541,16 @@ public static bool CheckHTTPFileExists(string url) if (url == null || url == "" || uri == null) return false; - WebRequest webRequest = WebRequest.Create(url); - if (!String.IsNullOrEmpty(Settings.Instance.UserAgent)) - ((HttpWebRequest)webRequest).UserAgent = Settings.Instance.UserAgent; - webRequest.Timeout = 10000; // miliseconds - webRequest.Method = "HEAD"; - - HttpWebResponse response = null; - - try - { - response = (HttpWebResponse)webRequest.GetResponse(); - result = true; - } - catch - { - } - finally - { - if (response != null) - { - response.Close(); - } - } + var client = new HttpClient(); + client.DefaultRequestHeaders.Add("User-Agent", Settings.Instance.UserAgent); + client.Timeout = TimeSpan.FromSeconds(10); + var resp = client.SendAsync(new HttpRequestMessage(HttpMethod.Head, url)).Result; + return resp.IsSuccessStatusCode; - return result; } //https://stackoverflow.com/questions/13606523/retrieving-partial-content-using-multiple-http-requsets-to-fetch-data-via-parlle + [Obsolete] public static void ParallelDownloadFile(string uri, string filePath, int chunkSize = 0, Action status = null) { if (uri == null) @@ -653,14 +648,10 @@ public static long GetFileSize(string uri) if (fileSizeCache.ContainsKey(uri) && fileSizeCache[uri] > 0) return fileSizeCache[uri]; - HttpWebRequest request = (HttpWebRequest) WebRequest.Create(uri); - if (!String.IsNullOrEmpty(Settings.Instance.UserAgent)) - ((HttpWebRequest) request).UserAgent = Settings.Instance.UserAgent; - request.Method = "GET"; - HttpWebResponse response = (HttpWebResponse) request.GetResponse(); - var len = response.ContentLength; - response.Close(); + var responce = client.GetAsync(uri); + var len = responce.GetAwaiter().GetResult().Content.Headers.ContentLength(); fileSizeCache[uri] = len; + responce.Result.Dispose(); return len; } } diff --git a/ExtLibs/Utilities/GitHubContent.cs b/ExtLibs/Utilities/GitHubContent.cs index c3f389f2a9..b6b0c75ecd 100644 --- a/ExtLibs/Utilities/GitHubContent.cs +++ b/ExtLibs/Utilities/GitHubContent.cs @@ -3,6 +3,7 @@ using System.IO; using System.Linq; using System.Net; +using System.Net.Http; using System.Reflection; using System.Text; using log4net; @@ -78,18 +79,13 @@ public static List GetDirContent(string owner, string repo, string pat string url = String.Format("{0}/{1}/{2}{3}", githubapiurl, owner, repo, path); - WebRequest wr = WebRequest.Create(url); - ((HttpWebRequest) wr).AllowAutoRedirect = true; - ((HttpWebRequest) wr).UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko"; - var response = wr.GetResponse(); - var respstream = response.GetResponseStream(); - - string content = new StreamReader(respstream).ReadToEnd(); - - respstream.Close(); - - //WebClient wc = new WebClient(); - //string content = wc.DownloadString(url); + var handler = new HttpClientHandler() + { + AllowAutoRedirect = true + }; + var client = new HttpClient(handler); + client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko"); + string content = client.GetStringAsync(url).GetAwaiter().GetResult(); var output = JsonConvert.DeserializeObject(content); @@ -119,26 +115,22 @@ public static byte[] GetFileContent(string owner, string repo, string path) string url = String.Format("{0}/{1}/{2}{3}", githubapiurl, owner, repo, path); - WebRequest wr = WebRequest.Create(url); - ((HttpWebRequest) wr).AllowAutoRedirect = true; - ((HttpWebRequest) wr).UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko"; - using (var response = wr.GetResponse()) + var handler = new HttpClientHandler() { - var respstream = response.GetResponseStream(); + AllowAutoRedirect = true + }; + var client = new HttpClient(handler); + client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko"); + string content = client.GetStringAsync(url).GetAwaiter().GetResult(); - string content = new StreamReader(respstream).ReadToEnd(); + Dictionary output = JsonConvert.DeserializeObject>(content); - respstream.Close(); + if (output == null) + return null; - Dictionary output = JsonConvert.DeserializeObject>(content); + byte[] filecontent = Convert.FromBase64String(output["content"].ToString()); - if (output == null) - return null; - - byte[] filecontent = Convert.FromBase64String(output["content"].ToString()); - - return filecontent; - } + return filecontent; } } } \ No newline at end of file diff --git a/ExtLibs/Utilities/Tracking.cs b/ExtLibs/Utilities/Tracking.cs index f773e9bf91..639b9ae955 100644 --- a/ExtLibs/Utilities/Tracking.cs +++ b/ExtLibs/Utilities/Tracking.cs @@ -3,6 +3,7 @@ using System.Globalization; using System.IO; using System.Net; +using System.Net.Http; using log4net; namespace MissionPlanner.Utilities @@ -296,12 +297,9 @@ static void track(object temp) try { - - var httpWebRequest = (HttpWebRequest)WebRequest.Create(secureTrackingEndpoint); - httpWebRequest.ServicePoint.Expect100Continue = false; - httpWebRequest.UserAgent = productName + " " + productVersion + " ("+ Environment.OSVersion.VersionString +")"; - //httpWebRequest.ContentType = "text/plain"; - httpWebRequest.Method = "POST"; + var client = new HttpClient(); + client.DefaultRequestHeaders.Add("User-Agent", productName + " " + productVersion + " (" + Environment.OSVersion.VersionString + ")"); + client.Timeout = TimeSpan.FromSeconds(10); string data = ""; @@ -321,29 +319,9 @@ static void track(object temp) data += "&z=" + random.Next().ToString(CultureInfo.InvariantCulture); - httpWebRequest.ContentLength = data.Length; - log.Debug(data); - using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) - { - - streamWriter.Write(data); - streamWriter.Flush(); - - using (var httpResponse = (HttpWebResponse) httpWebRequest.GetResponse()) - { - if (httpResponse.StatusCode >= HttpStatusCode.OK && (int) httpResponse.StatusCode < 300) - { - // response is a gif file - log.Debug(httpResponse.StatusCode); - } - else - { - log.Debug(httpResponse.StatusCode); - } - } - } + client.PostAsync(secureTrackingEndpoint, new StringContent(data)); } catch { } } diff --git a/ExtLibs/Utilities/tfr.cs b/ExtLibs/Utilities/tfr.cs deleted file mode 100644 index bbd13fcb33..0000000000 --- a/ExtLibs/Utilities/tfr.cs +++ /dev/null @@ -1,296 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net; -using System.Text; -using System.Text.RegularExpressions; -using System.Xml.Linq; -using System.Globalization; -using GMap.NET; - -namespace MissionPlanner.Utilities -{ - public class tfr - { - //https://www.jeppesen.com/download/fstarfmap/TFR_Protocol.pdf - //http://www.jepptech.com/tfr/Query.asp?UserID=Public - - public static event EventHandler GotTFRs; - - public static string tfrurl = "http://www.jepptech.com/tfr/Query.asp?UserID=Public"; - - public static List tfrs = new List(); - - // center then radius - Regex circle = new Regex(@"[R,B]*C[N,S][0-9\.]+[E,W][0-9\.]+[R][0-9\.]+"); - - // center then start arc - Regex arc = new Regex(@"[R,B]*A[\+,\-][N,S][0-9\.]+[E,W][0-9\.]+[N,S][0-9\.]+[E,W][0-9\.]+"); - - // point - Regex line = new Regex(@"[R,B]*L[N,S][0-9\.]+[E,W][0-9\.]+"); - - static Regex all = new Regex(@"([R,B]*(L)([N,S])([0-9\.]+)([E,W])([0-9\.]+)|[R,B]*(A)([\+,\-])([N,S])([0-9\.]+)([E,W])([0-9\.]+)([N,S])([0-9\.]+)([E,W])([0-9\.]+)|[R,B]*(C)([N,S])([0-9\.]+)([E,W])([0-9\.]+)[R]([0-9\.]+))", RegexOptions.Multiline); - - // R is inclusive, B is exclusive - - public static string tfrcache = "tfr.xml"; - - public static void GetTFRs() - { - var request = WebRequest.Create(tfrurl); - if (!String.IsNullOrEmpty(Settings.Instance.UserAgent)) - ((HttpWebRequest)request).UserAgent = Settings.Instance.UserAgent; - request.BeginGetResponse(tfrcallback, request); - } - - private static void tfrcallback(IAsyncResult ar) - { - try - { - string content = ""; - - // check if cache exists and last write was today - if (File.Exists(tfrcache) && - new FileInfo(tfrcache).LastWriteTime.ToShortDateString() == DateTime.Now.ToShortDateString()) - { - content = File.ReadAllText(tfrcache); - } - else - { - // Set the State of request to asynchronous. - WebRequest myWebRequest1 = (WebRequest) ar.AsyncState; - - using (WebResponse response = myWebRequest1.EndGetResponse(ar)) - { - - var st = response.GetResponseStream(); - - StreamReader sr = new StreamReader(st); - - content = sr.ReadToEnd(); - - File.WriteAllText(tfrcache, content); - } - } - - XDocument xdoc = XDocument.Parse(content); - - tfritem currenttfr = new tfritem(); - - for (int a = 1; a < 100; a++) - { - var newtfrs = (from _item in xdoc.Element("TFRSET").Elements("TFR" + a) - select new tfritem - { - ID = _item.Element("ID").Value, - NID = _item.Element("NID").Value, - VERIFIED = _item.Element("VERIFIED").Value, - NAME = _item.Element("NAME").Value, - COMMENT = _item.Element("COMMENT").Value, - ACCESS = _item.Element("ACCESS").Value, - APPEAR = _item.Element("APPEAR").Value, - TYPE = _item.Element("TYPE").Value, - MINALT = _item.Element("MINALT").Value, - MAXALT = _item.Element("MAXALT").Value, - SEGS = _item.Element("SEGS").Value, - BOUND = _item.Element("BOUND").Value, - SRC = _item.Element("SRC").Value, - CREATED = _item.Element("CREATED").Value, - MODIFIED = _item.Element("MODIFIED").Value, - DELETED = _item.Element("DELETED").Value, - ACTIVE = _item.Element("ACTIVE").Value, - EXPIRES = _item.Element("EXPIRES").Value, - SUBMITID = _item.Element("SUBMITID").Value, - SUBMITHOST = _item.Element("SUBMITHOST").Value, - }).ToList(); - - if (newtfrs == null || newtfrs.Count == 0) - break; - - tfrs.AddRange(newtfrs); - } - - if (GotTFRs != null) - GotTFRs(tfrs, null); - } - catch - { - try - { - File.Delete(tfrcache); - } catch { } - } - } - - public class tfritem - { - public string ID;// Unique Identifier “42” - public string DELETED;// Deleted Flag "False" - public string VERIFIED; - public string NID;// NOTAM ID "ZAN 1/1109" - public string NAME;// Name "AK PAVD 1/1109 1 OF 2" - public string COMMENT;// Comments "...contact your local FSS." - public string ACCESS;// Access Specifier "Public" - public string APPEAR;// Appearance "2;0000ff;1;0000ff;30180c060381c060" - public string TYPE;// Type “Natural Disaster” - public string MINALT;// Minimum Altitude “2000A” - public string MAXALT;// Maximum Altitude “5000A” - public string SEGS;// Segment Count “7” - public string BOUND;// Boundary "CN38.837606W86.803R005.00" - public string SRC;// Source Text "!FDC 2/2183 ZID..." - public string CREATED;// Creation Date/Time "37461.7885756134" and "7/24/2002 6:55:33 PM" - public string MODIFIED;// Modification Date/Time "37461.7885756134" and "7/24/2002 6:55:33 PM" - public string ACTIVE;// Activation Date/Time "37461.7885756134" and "7/24/2002 6:55:33 PM" - public string EXPIRES;// Expiration Date/Time "37461.7885756134" and "7/24/2002 6:55:33 PM" - public string SUBMITID;// Submitter ID “Publisher” - public string SUBMITHOST;// Submitter Host “1.2.3.4” or “enduser5.faa.gov” - - public List> GetPaths() - { - //RLN27.576944W97.108611LN27.468056W96.961111LN27.322222W97.050000LN27.345833W97.088889LN27.439167W97.186944RLN27.672778W97.212222LN27.576944W97.108611LN27.533333W97.133333LN27.638333W97.237222RCN27.686333W97.294667R007.00 - - List> list = new List>(); - - List pointlist = new List(); - - var matches = all.Matches(BOUND); - - bool isarcterminate = false; - bool iscircleterminate = false; - int arcdir = 0; - PointLatLngAlt pointcent = null; - PointLatLngAlt pointstart = null; - - foreach (Match item in matches) - { - try - { - if (item.Groups[0].Value.ToString().StartsWith("R") || item.Groups[0].Value.ToString().StartsWith("B")) - { - // start new element - if (pointlist.Count > 0) - { - list.Add(pointlist); - pointlist = new List(); - } - } - - if (item.Groups[2].Value == "L") - { - var point = new PointLatLngAlt(double.Parse(item.Groups[4].Value, CultureInfo.InvariantCulture), double.Parse(item.Groups[6].Value, CultureInfo.InvariantCulture)); - - if (item.Groups[3].Value == "S") - point.Lat *= -1; - - if (item.Groups[5].Value == "W") - point.Lng *= -1; - - if (isarcterminate) - { - double radius = pointcent.GetDistance(pointstart); - - double startbearing = pointcent.GetBearing(pointstart); - - double endbearing = pointcent.GetBearing(point); - - if (arcdir > 0 && endbearing < startbearing) - endbearing += 360; - - if (arcdir < 0) - { - for (double a = startbearing; a > endbearing; a += (10 * arcdir)) - { - pointlist.Add(pointcent.newpos(a, radius)); - } - } - else - { - for (double a = startbearing; a < endbearing; a += (10 * arcdir)) - { - pointlist.Add(pointcent.newpos(a, radius)); - } - } - - pointlist.Add(point); - - - isarcterminate = false; - iscircleterminate = false; - - continue; - } - - if (iscircleterminate) - { - iscircleterminate = false; - continue; - } - - pointlist.Add(point); - - continue; - } - else if (item.Groups[7].Value == "A") - { - pointcent = new PointLatLngAlt(double.Parse(item.Groups[10].Value, CultureInfo.InvariantCulture), double.Parse(item.Groups[12].Value, CultureInfo.InvariantCulture)); - - if (item.Groups[9].Value == "S") - pointcent.Lat *= -1; - - if (item.Groups[11].Value == "W") - pointcent.Lng *= -1; - - pointstart = new PointLatLngAlt(double.Parse(item.Groups[14].Value, CultureInfo.InvariantCulture), double.Parse(item.Groups[16].Value, CultureInfo.InvariantCulture)); - - if (item.Groups[13].Value == "S") - pointstart.Lat *= -1; - - if (item.Groups[15].Value == "W") - pointstart.Lng *= -1; - - arcdir = item.Groups[8].Value == "+" ? 1 : -1; - - isarcterminate = true; - - continue; - } - else if (item.Groups[17].Value == "C") - { - var point = new PointLatLngAlt(double.Parse(item.Groups[19].Value, CultureInfo.InvariantCulture), double.Parse(item.Groups[21].Value, CultureInfo.InvariantCulture)); - - if (item.Groups[18].Value == "S") - point.Lat *= -1; - - if (item.Groups[20].Value == "W") - point.Lng *= -1; - - // radius in m from nautical miles - double radius = double.Parse(item.Groups[22].Value, CultureInfo.InvariantCulture) * 1852; - - for (int a = 0; a <= 360; a += 10) - { - pointlist.Add(point.newpos(a, radius)); - } - - list.Add(pointlist); - pointlist = new List(); - - iscircleterminate = true; - - continue; - } - } - catch { } - } - - if(pointlist.Count > 0) - list.Add(pointlist); - - return list; - } - } - } - -} diff --git a/GCSViews/ConfigurationView/ConfigFirmwareManifest.cs b/GCSViews/ConfigurationView/ConfigFirmwareManifest.cs index fc9eb28893..36735a6abe 100644 --- a/GCSViews/ConfigurationView/ConfigFirmwareManifest.cs +++ b/GCSViews/ConfigurationView/ConfigFirmwareManifest.cs @@ -10,6 +10,7 @@ using System.IO; using System.Linq; using System.Net; +using System.Net.Http; using System.Reflection; using System.Threading; using System.Threading.Tasks; @@ -250,23 +251,17 @@ private void LookForPort(APFirmware.MAV_TYPE mavtype, bool alloptions = false) var starttime = DateTime.Now; // Create a request using a URL that can receive a post. - WebRequest request = WebRequest.Create(baseurl); - if (!String.IsNullOrEmpty(Settings.Instance.UserAgent)) - ((HttpWebRequest)request).UserAgent = Settings.Instance.UserAgent; - request.Timeout = 10000; - // Set the Method property of the request to POST. - request.Method = "GET"; - // Get the request stream. - Stream dataStream; //= request.GetRequestStream(); - // Get the response (using statement is exception safe) - using (WebResponse response = request.GetResponse()) + var client = new HttpClient(); + client.DefaultRequestHeaders.Add("User-Agent", Settings.Instance.UserAgent); + client.Timeout = TimeSpan.FromSeconds(10); + using (var response = client.GetAsync(baseurl)) { // Display the status. - log.Info(((HttpWebResponse)response).StatusDescription); + log.Info(baseurl + " " + response.Result.ReasonPhrase); // Get the stream containing content returned by the server. - using (dataStream = response.GetResponseStream()) + using (var dataStream = response.Result.Content.ReadAsStreamAsync().Result) { - long bytes = response.ContentLength; + long bytes = int.Parse(response.Result.Content.Headers.First(h => h.Key.Equals("Content-Length")).Value.First()); long contlen = bytes; byte[] buf1 = new byte[1024]; @@ -275,7 +270,7 @@ private void LookForPort(APFirmware.MAV_TYPE mavtype, bool alloptions = false) { fw_Progress1(0, Strings.DownloadingFromInternet); - long length = response.ContentLength; + long length = int.Parse(response.Result.Content.Headers.First(h => h.Key.Equals("Content-Length")).Value.First()); long progress = 0; dataStream.ReadTimeout = 30000; @@ -300,7 +295,6 @@ private void LookForPort(APFirmware.MAV_TYPE mavtype, bool alloptions = false) } dataStream.Close(); } - response.Close(); } var timetook = (DateTime.Now - starttime).TotalMilliseconds; diff --git a/GCSViews/FlightData.cs b/GCSViews/FlightData.cs index bbfc125500..21da90aedb 100644 --- a/GCSViews/FlightData.cs +++ b/GCSViews/FlightData.cs @@ -2574,8 +2574,6 @@ private void FlightData_Load(object sender, EventArgs e) { POI.POIModified += POI_POIModified; - tfr.GotTFRs += tfr_GotTFRs; - if (!Settings.Instance.ContainsKey("ShowNoFly") || Settings.Instance.GetBoolean("ShowNoFly")) NoFly.NoFly.NoFlyEvent += NoFly_NoFlyEvent; @@ -5034,28 +5032,6 @@ private void takeOffToolStripMenuItem_Click(object sender, EventArgs e) } } - void tfr_GotTFRs(object sender, EventArgs e) - { - BeginInvoke((Action) delegate - { - foreach (var item in tfr.tfrs) - { - List> points = item.GetPaths(); - - foreach (var list in points) - { - GMapPolygon poly = new GMapPolygon(list, item.NAME); - - poly.Fill = new SolidBrush(Color.FromArgb(30, Color.Blue)); - - tfrpolygons.Polygons.Add(poly); - } - } - - tfrpolygons.IsVisibile = MainV2.ShowTFR; - }); - } - private void ZedGraphTimer_Tick(object sender, EventArgs e) { try diff --git a/GCSViews/FlightPlanner.cs b/GCSViews/FlightPlanner.cs index 8811944d86..e52b008a9b 100644 --- a/GCSViews/FlightPlanner.cs +++ b/GCSViews/FlightPlanner.cs @@ -30,7 +30,7 @@ using System.Globalization; using System.IO; using System.Linq; -using System.Net; +using System.Net.Http; using System.Reflection; using System.Runtime.Serialization.Formatters.Binary; using System.Text.RegularExpressions; @@ -295,7 +295,7 @@ public void Activate() timer1.Start(); // hide altmode if old copter version - if (MainV2.comPort.BaseStream.IsOpen && MainV2.comPort.MAV.cs.firmware == Firmwares.ArduCopter2 && + if (MainV2.comPort.BaseStream != null && MainV2.comPort.BaseStream.IsOpen && MainV2.comPort.MAV.cs.firmware == Firmwares.ArduCopter2 && MainV2.comPort.MAV.cs.version < new Version(3, 3)) { CMB_altmode.Visible = false; @@ -2221,7 +2221,8 @@ private void comboBoxMapType_SelectedValueChanged(object sender, EventArgs e) } MainMap.MapProvider = (GMapProvider) comboBoxMapType.SelectedItem; - FlightData.mymap.MapProvider = (GMapProvider) comboBoxMapType.SelectedItem; + if(FlightData.mymap != null) + FlightData.mymap.MapProvider = (GMapProvider) comboBoxMapType.SelectedItem; Settings.Instance["MapType"] = comboBoxMapType.Text; } catch (Exception ex) @@ -7761,18 +7762,17 @@ private void MainMap_OnTileLoadStart() } } - private XmlDocument MakeRequest(string requestUrl) + public XmlDocument MakeRequest(string requestUrl) { try { - HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest; - if (!String.IsNullOrEmpty(Settings.Instance.UserAgent)) - ((HttpWebRequest) request).UserAgent = Settings.Instance.UserAgent; - HttpWebResponse response = request.GetResponse() as HttpWebResponse; + var client = new HttpClient(); + client.DefaultRequestHeaders.Add("User-Agent", Settings.Instance.UserAgent); + client.Timeout = System.TimeSpan.FromSeconds(10); XmlDocument xmlDoc = new XmlDocument(); - xmlDoc.Load(response.GetResponseStream()); + xmlDoc.Load(client.GetStreamAsync(requestUrl).GetAwaiter().GetResult()); return (xmlDoc); } catch (Exception e) diff --git a/MainV2.cs b/MainV2.cs index 537389c90a..f97ee1f080 100644 --- a/MainV2.cs +++ b/MainV2.cs @@ -3939,19 +3939,6 @@ private void BGGetKIndex(object state) } } - private void BGgetTFR(object state) - { - try - { - tfr.tfrcache = Settings.GetUserDataDirectory() + "tfr.xml"; - tfr.GetTFRs(); - } - catch (Exception ex) - { - log.Error(ex); - } - } - private void BGNoFly(object state) { try diff --git a/MissionPlannerTests/GCSViews/FlightPlannerTests.cs b/MissionPlannerTests/GCSViews/FlightPlannerTests.cs new file mode 100644 index 0000000000..7d5559184e --- /dev/null +++ b/MissionPlannerTests/GCSViews/FlightPlannerTests.cs @@ -0,0 +1,27 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using MissionPlanner.GCSViews; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using MissionPlanner.Utilities; + +namespace MissionPlanner.GCSViews.Tests +{ + [TestClass()] + public class FlightPlannerTests + { + [TestMethod()] + public void MakeRequestTest() + { + FlightPlanner flightPlanner = new FlightPlanner(); + + var xmldoc = flightPlanner.MakeRequest("https://mesonet.agron.iastate.edu/cgi-bin/wms/iowa/rainfall.cgi?VERSION=1.1.1&REQUEST=GetCapabilities&SERVICE=WMS&"); + + Console.WriteLine(xmldoc.ToJSON()); + + Assert.IsNotNull(xmldoc); + } + } +} \ No newline at end of file diff --git a/MissionPlannerTests/Linked/DownloadTests.cs b/MissionPlannerTests/Linked/DownloadTests.cs new file mode 100644 index 0000000000..e331e6824a --- /dev/null +++ b/MissionPlannerTests/Linked/DownloadTests.cs @@ -0,0 +1,42 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using MissionPlanner.Utilities; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MissionPlanner.Utilities.Tests +{ + [TestClass()] + public class DownloadTests + { + [TestMethod()] + public void getFilefromNetTest() + { + if (Utilities.Download.getFilefromNet("https://www.google.com/", Path.GetTempFileName())) + return; + + Assert.Fail(); + } + + [TestMethod()] + public void CheckHTTPFileExists() + { + if (Utilities.Download.CheckHTTPFileExists("https://github.com/ArduPilot/MissionPlanner/releases/download/betarelease/MissionPlannerBeta.zip")) + return; + + Assert.Fail(); + } + + [TestMethod()] + public void GetFileSize() + { + if (Utilities.Download.GetFileSize("https://github.com/ArduPilot/MissionPlanner/releases/download/betarelease/MissionPlannerBeta.zip") > 0) + return; + + Assert.Fail(); + } + } +} \ No newline at end of file diff --git a/MissionPlannerTests/MissionPlannerTests.csproj b/MissionPlannerTests/MissionPlannerTests.csproj index 6df48daf72..dc511c3fb0 100644 --- a/MissionPlannerTests/MissionPlannerTests.csproj +++ b/MissionPlannerTests/MissionPlannerTests.csproj @@ -1,6 +1,6 @@  - + Debug AnyCPU {0B99EBF2-B964-4AAC-9EC5-76353610AAAE} @@ -36,16 +36,36 @@ prompt 4 - + + + + + {ca6345d3-7a6d-478b-a0ed-a58e50dcaa83} MissionPlanner.ArduPilot + + {C8B88795-6D01-494D-83AD-6944BD4C5023} + MissionPlanner.Controls + + + {3A413E59-A20E-477C-997E-64B1398E0E80} + DroneCAN + + + {13d2ec90-c41f-48a1-aada-859b6dc24edc} + MAVLink + + + {1378a66c-38e4-46f5-a05f-dc04ef7d4d16} + MissionPlanner.Utilities + {A2E22272-95FE-47B6-B050-9AE7E2055BF5} MissionPlanner @@ -69,9 +89,8 @@ ..\..\..\..\..\..\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.dll + - - \ No newline at end of file diff --git a/MissionPlannerTests/Utilities/BoardDetectTests.cs b/MissionPlannerTests/Utilities/BoardDetectTests.cs index 8fc9cd9650..b8339a48dd 100644 --- a/MissionPlannerTests/Utilities/BoardDetectTests.cs +++ b/MissionPlannerTests/Utilities/BoardDetectTests.cs @@ -27,6 +27,79 @@ public void DetectBoardTest() Assert.Fail(); } + [TestMethod()] + public void DetectBoardTestMany() + { + BoardDetect.boards ans; + /* + var ans = BoardDetect.DetectBoard("com1", + new List() + { + new DeviceInfo() + { + board = "PX4 BL FMU v1.x", description = "", hardwareid = @"USB\VID_26AC&PID_0010", name = "" + }, + }); + if(ans == BoardDetect.boards.none) + Assert.Fail();*/ + ans = BoardDetect.DetectBoard("com1", + new List() + { + new DeviceInfo() + { + board = "PX4 BL FMU v2.x", description = "", hardwareid = @"USB\VID_26AC&PID_0011", name = "" + }, + }); if (ans == BoardDetect.boards.none) + Assert.Fail(); + ans = BoardDetect.DetectBoard("com1", + new List() + { + new DeviceInfo() + { + board = "PX4 BL FMU v3.x", description = "", hardwareid = @"USB\VID_26AC&PID_0011", name = "" + }, + }); if (ans == BoardDetect.boards.none) + Assert.Fail(); + ans = BoardDetect.DetectBoard("com1", + new List() + { + new DeviceInfo() + { + board = "PX4 BL FMU v4.x", description = "", hardwareid = @"USB\VID_26AC&PID_0012", name = "" + }, + }); if (ans == BoardDetect.boards.none) + Assert.Fail(); + ans = BoardDetect.DetectBoard("com1", + new List() + { + new DeviceInfo() + { + board = "PX4 BL FMU v4.x PRO", description = "", hardwareid = @"USB\VID_26AC&PID_0013", + name = "" + }, + }); if (ans == BoardDetect.boards.none) + Assert.Fail(); + ans = BoardDetect.DetectBoard("com1", + new List() + { + new DeviceInfo() + { + board = "PX4 BL FMU v5.x", description = "", hardwareid = @"USB\VID_26AC&PID_0032", name = "" + }, + }); if (ans == BoardDetect.boards.none) + Assert.Fail(); + ans = BoardDetect.DetectBoard("com1", + new List() + { + new DeviceInfo() + { + board = "ProfiCNC CUBE F4 BL", description = "", hardwareid = @"USB\VID_2DAE&PID_0001", + name = "" + }, + }); + } + + [TestMethod()] public void DetectBoardTest1() { @@ -66,7 +139,8 @@ public void DetectBoardTest3() new List() { - new DeviceInfo() { board = "", description = "", hardwareid = @"USB\VID_2341&PID_0010", name = "" }, + new DeviceInfo() { board = "PX4 BL FMU v2.x", description = "", hardwareid = @"USB\VID_2341&PID_0010", name = "" }, + new DeviceInfo() { board = "PX4 FMU v2.x", description = "", hardwareid = @"USB\VID_2341&PID_0010", name = "" }, }); @@ -81,7 +155,8 @@ public void DetectBoardTest4() new List() { - new DeviceInfo() { board = "", description = "", hardwareid = @"USB\VID_26AC&PID_0010", name = "" }, + new DeviceInfo() { board = "PX4 BL FMU v2.x", description = "", hardwareid = @"USB\VID_26AC&PID_0010", name = "" }, + new DeviceInfo() { board = "PX4 FMU v2.x", description = "", hardwareid = @"USB\VID_26AC&PID_0010", name = "" }, }); @@ -96,7 +171,8 @@ public void DetectBoardTest5() new List() { - new DeviceInfo() { board = "", description = "", hardwareid = @"USB\VID_26AC&PID_0032", name = "" }, + new DeviceInfo() { board = "PX4 BL FMU v5.x", description = "", hardwareid = @"USB\VID_26AC&PID_0032", name = "" }, + new DeviceInfo() { board = "PX4 FMU v5.x", description = "", hardwareid = @"USB\VID_26AC&PID_0032", name = "" }, }); if (ans != BoardDetect.boards.chbootloader) @@ -111,7 +187,9 @@ public void DetectBoardTest6() { - new DeviceInfo() { board = "", description = "", hardwareid = @"USB\VID_26AC&PID_0001", name = "" }, + new DeviceInfo() { board = "PX4 BL FMU v3.x", description = "", hardwareid = @"USB\VID_26AC&PID_0011", name = "" }, + + new DeviceInfo() { board = "PX4 FMU v3.x", description = "", hardwareid = @"USB\VID_26AC&PID_0011", name = "" }, }); @@ -153,7 +231,11 @@ public void DetectBoardTest8() new DeviceInfo() { - board = "", description = "chibios or normal px4", hardwareid = @"USB\VID_26AC&PID_0011", + board = "PX4 BL FMU v2.x", description = "chibios or normal px4", hardwareid = @"USB\VID_26AC&PID_0011", + name = "" + }, new DeviceInfo() + { + board = "PX4 FMU v2.x", description = "chibios or normal px4", hardwareid = @"USB\VID_26AC&PID_0011", name = "" }, }); diff --git a/MissionPlannerTests/Utilities/FirmwareTests.cs b/MissionPlannerTests/Utilities/FirmwareTests.cs new file mode 100644 index 0000000000..5936a0b95c --- /dev/null +++ b/MissionPlannerTests/Utilities/FirmwareTests.cs @@ -0,0 +1,26 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using MissionPlanner.Utilities; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace MissionPlanner.Utilities.Tests +{ + [TestClass()] + public class FirmwareTests + { + [TestMethod()] + public void getFWListTest() + { + var list = new Firmware().getFWList(); + + Console.WriteLine(list.ToJSON()); + + if (list.Count > 0) + return; + Assert.Fail(); + } + } +} \ No newline at end of file diff --git a/MissionPlannerTests/Utilities/GitHubContentTests.cs b/MissionPlannerTests/Utilities/GitHubContentTests.cs new file mode 100644 index 0000000000..33990ae761 --- /dev/null +++ b/MissionPlannerTests/Utilities/GitHubContentTests.cs @@ -0,0 +1,36 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using MissionPlanner.Utilities; +using System; +using System.Collections.Generic; +using System.Text; + +namespace MissionPlanner.Utilities.Tests +{ + [TestClass()] + public class GitHubContentTests + { + [TestMethod()] + public void GetDirContentTest() + { + var paramfiles = GitHubContent.GetDirContent("ardupilot", "ardupilot", "/Tools/Frame_params/", ".param"); + + Console.WriteLine(paramfiles); + + if (paramfiles.Count > 0) + return; + Assert.Fail(); + } + [TestMethod()] + public void GetFileContentTest() + { + var paramfiles = GitHubContent.GetDirContent("ardupilot", "ardupilot", "/Tools/Frame_params/", ".param"); + var data = GitHubContent.GetFileContent("ardupilot", "ardupilot", (paramfiles[0].path)); + + Console.WriteLine(data); + + if (data.Length > 0) + return; + Assert.Fail(); + } + } +} \ No newline at end of file diff --git a/MissionPlannerTests/httpclient.cs b/MissionPlannerTests/httpclient.cs new file mode 100644 index 0000000000..b54e315de9 --- /dev/null +++ b/MissionPlannerTests/httpclient.cs @@ -0,0 +1,35 @@ +using DroneCAN; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +namespace MissionPlannerTests +{ + [TestClass()] + public class DroneCANTests + { + [TestMethod()] + public void DroneCAN1() + { + var ans = new DroneCAN.DroneCAN().LookForUpdate("com.cubepilot.test", 1.0, false); + + Console.WriteLine(ans); + + if (ans == String.Empty) + return; + Assert.Fail(); + } + [TestMethod()] + public void DroneCAN2() + { + var ans = new DroneCAN.DroneCAN().LookForUpdate("com.cubepilot.herepro", 19.137, false); + Console.WriteLine(ans); + if (ans != String.Empty) + return; + Assert.Fail(); + } + } +} diff --git a/ResEdit.cs b/ResEdit.cs index 3086e94772..bf2ef2621b 100644 --- a/ResEdit.cs +++ b/ResEdit.cs @@ -392,7 +392,6 @@ private void BUT_clipboard_Click(object sender, EventArgs e) lastitem = item.Value.ToString(); sb += '"' + item.Value.ToString() + '"' + ","; } - //sb += new StreamReader(WebRequest.Create("https://www.googleapis.com/language/translate/v2?q=" + lastitem + "&target=zh&source=en&key=" + ApiKey).GetResponse().GetResponseStream()).ReadToEnd(); sb += "\n"; } diff --git a/SikRadio/Common.cs b/SikRadio/Common.cs index b19433fec1..569046252c 100644 --- a/SikRadio/Common.cs +++ b/SikRadio/Common.cs @@ -1,74 +1,5 @@ -using System; -using System.IO; -using System.Net; -using System.Reflection; -using System.Windows.Forms; -using log4net; -// config file -// dll imports + namespace MissionPlanner { - public class Common - { - private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); - - public static bool getFilefromNet(string url, string saveto) - { - try - { - log.Info("Get " + url); - - // Create a request using a URL that can receive a post. - var request = WebRequest.Create(url); - if (!String.IsNullOrEmpty(Settings.Instance.UserAgent)) - ((HttpWebRequest)request).UserAgent = Settings.Instance.UserAgent; - request.Timeout = 10000; - // Set the Method property of the request to POST. - request.Method = "GET"; - // Get the response. - var response = request.GetResponse(); - // Display the status. - log.Info(((HttpWebResponse) response).StatusDescription); - if (((HttpWebResponse) response).StatusCode != HttpStatusCode.OK) - return false; - // Get the stream containing content returned by the server. - var dataStream = response.GetResponseStream(); - - var bytes = response.ContentLength; - var contlen = bytes; - - var buf1 = new byte[1024]; - - var fs = new FileStream(saveto + ".new", FileMode.Create); - - var dt = DateTime.Now; - - while (dataStream.CanRead && bytes > 0) - { - Application.DoEvents(); - log.Debug(saveto + " " + bytes); - var len = dataStream.Read(buf1, 0, buf1.Length); - bytes -= len; - fs.Write(buf1, 0, len); - } - - fs.Close(); - dataStream.Close(); - response.Close(); - - File.Delete(saveto); - File.Move(saveto + ".new", saveto); - - log.Info("Done " + saveto); - - return true; - } - catch (Exception ex) - { - log.Info("getFilefromNet(): " + ex); - return false; - } - } - } } \ No newline at end of file diff --git a/Utilities/BoardDetect.cs b/Utilities/BoardDetect.cs index 1cce07beb7..c691b8cf0b 100644 --- a/Utilities/BoardDetect.cs +++ b/Utilities/BoardDetect.cs @@ -140,7 +140,12 @@ public static boards DetectBoard(string port, List ports) log.Info("is a px4v4 pixracer"); return boards.px4v4; } - else if (item.board == "PX4 FMU v2.x") + else if (item.board == "PX4 FMU v1.x") + { + log.Info("is a px4v1"); + return boards.px4; + } + else if (item.board == "PX4 FMU v2.x" || item.board == "PX4 FMU v3.x") { CustomMessageBox.Show(Strings.PleaseUnplugTheBoardAnd); diff --git a/Utilities/Firmware.cs b/Utilities/Firmware.cs index 26143b0f5a..d09e78fb32 100644 --- a/Utilities/Firmware.cs +++ b/Utilities/Firmware.cs @@ -11,6 +11,7 @@ using System.IO; using System.Linq; using System.Net; +using System.Net.Http; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Reflection; @@ -201,13 +202,12 @@ public List getFWList(string firmwareurl = "") XmlSerializer xms = new XmlSerializer(typeof(optionsObject), new Type[] { typeof(software) }); log.Info("url: " + url); - WebRequest request = WebRequest.Create(url); - if (!String.IsNullOrEmpty(Settings.Instance.UserAgent)) - ((HttpWebRequest)request).UserAgent = Settings.Instance.UserAgent; - request.Timeout = 10000; + var client = new HttpClient(); + client.DefaultRequestHeaders.Add("User-Agent", Settings.Instance.UserAgent); + client.Timeout = TimeSpan.FromSeconds(10); - using (WebResponse response = request.GetResponse()) - using (XmlReader xmlreader = XmlReader.Create(response.GetResponseStream())) + using (var response = client.GetAsync(url)) + using (XmlReader xmlreader = XmlReader.Create(response.Result.Content.ReadAsStreamAsync().Result)) { options = (optionsObject)xms.Deserialize(xmlreader); } @@ -303,7 +303,7 @@ void getAPMVersion(object tempin) } } - private string GetAPMVERSIONFile(Uri url) + public string GetAPMVERSIONFile(Uri url) { lock (urlcachelock) if (!urlcacheSem.ContainsKey(url.AbsoluteUri)) @@ -320,12 +320,12 @@ private string GetAPMVERSIONFile(Uri url) return urlcache[url.AbsoluteUri]; } - WebRequest wr = WebRequest.Create(url); - if (!String.IsNullOrEmpty(Settings.Instance.UserAgent)) - ((HttpWebRequest)wr).UserAgent = Settings.Instance.UserAgent; - wr.Timeout = 10000; - using (WebResponse wresp = wr.GetResponse()) - using (StreamReader sr = new StreamReader(wresp.GetResponseStream())) + var client = new HttpClient(); + client.DefaultRequestHeaders.Add("User-Agent", Settings.Instance.UserAgent); + client.Timeout = TimeSpan.FromSeconds(10); + + using (var response = client.GetAsync(url)) + using (StreamReader sr = new StreamReader(response.GetAwaiter().GetResult().Content.ReadAsStreamAsync().GetAwaiter().GetResult())) { while (!sr.EndOfStream) { @@ -530,61 +530,9 @@ public bool updateLegacy(string comport, software temp, string historyhash, List var starttime = DateTime.Now; - // Create a request using a URL that can receive a post. - WebRequest request = WebRequest.Create(baseurl); - if (!String.IsNullOrEmpty(Settings.Instance.UserAgent)) - ((HttpWebRequest)request).UserAgent = Settings.Instance.UserAgent; - request.Timeout = 10000; - // Set the Method property of the request to POST. - request.Method = "GET"; - // Get the request stream. - Stream dataStream; //= request.GetRequestStream(); - // Get the response (using statement is exception safe) - using (WebResponse response = request.GetResponse()) - { - // Display the status. - log.Info(((HttpWebResponse)response).StatusDescription); - // Get the stream containing content returned by the server. - using (dataStream = response.GetResponseStream()) - { - long bytes = response.ContentLength; - long contlen = bytes; - - byte[] buf1 = new byte[1024]; - - using (FileStream fs = new FileStream( - Settings.GetUserDataDirectory() + - @"firmware.hex", FileMode.Create)) - { - updateProgress(0, Strings.DownloadingFromInternet); - - long length = response.ContentLength; - long progress = 0; - dataStream.ReadTimeout = 30000; - - while (dataStream.CanRead) - { - try - { - updateProgress(length == 0 ? 50 : (int)((progress * 100) / length), Strings.DownloadingFromInternet); - } - catch - { - } - int len = dataStream.Read(buf1, 0, 1024); - if (len == 0) - break; - progress += len; - bytes -= len; - fs.Write(buf1, 0, len); - } - - fs.Close(); - } - dataStream.Close(); - } - response.Close(); - } + Download.getFilefromNet(baseurl, Settings.GetUserDataDirectory() + + @"firmware.hex", + (i, s) => updateProgress(i, s)); var timetook = (DateTime.Now - starttime).TotalMilliseconds; diff --git a/Utilities/Update.cs b/Utilities/Update.cs index cd685a689a..2b4a51f8db 100644 --- a/Utilities/Update.cs +++ b/Utilities/Update.cs @@ -595,28 +595,19 @@ static void GetNewFile(IProgressReporterDialogue frmProgressReporter, string bas try { string url = baseurl + file + "?" + new Random().Next(); - // Create a request using a URL that can receive a post. - WebRequest request = WebRequest.Create(url); - if (!String.IsNullOrEmpty(Settings.Instance.UserAgent)) - ((HttpWebRequest)request).UserAgent = Settings.Instance.UserAgent; - log.Info("GetNewFile " + url); - // Set the Method property of the request to GET. - request.Method = "GET"; - // Allow compressed content - ((HttpWebRequest)request).AutomaticDecompression = DecompressionMethods.GZip | - DecompressionMethods.Deflate; - // tell server we allow compress content - request.Headers.Add("Accept-Encoding", "gzip,deflate"); + var client = new HttpClient(); + client.DefaultRequestHeaders.Add("User-Agent", Settings.Instance.UserAgent); + client.Timeout = TimeSpan.FromSeconds(10); // Get the response. - using (WebResponse response = request.GetResponse()) + using (var response = client.GetAsync(url).GetAwaiter().GetResult()) { // Display the status. - log.Info(((HttpWebResponse)response).StatusDescription); + log.Info(response.ReasonPhrase); // Get the stream containing content returned by the server. - Stream dataStream = response.GetResponseStream(); + Stream dataStream = response.Content.ReadAsStreamAsync().GetAwaiter().GetResult(); // from head - long bytes = response.ContentLength; + long bytes = response.Content.Headers.ContentLength(); long contlen = bytes;