Skip to content

Commit 5de3987

Browse files
committed
Update Net.cs to use async HttpClient rather than obsolete HttpWebRequests.
Making this use async methods also helps speed loading.
1 parent 8e46b74 commit 5de3987

3 files changed

Lines changed: 91 additions & 104 deletions

File tree

NavigationMonitor/NavigationMonitor.cs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -79,13 +79,16 @@ public NavigationMonitor()
7979
private void LoadMonitor()
8080
{
8181
ReadNavConfig();
82-
GetGalacticPOIs();
82+
Task.Run( GetGalacticPOIsAsync );
8383
}
8484

85-
private void GetGalacticPOIs()
85+
private async Task GetGalacticPOIsAsync()
8686
{
8787
// Build a Galactic POI list
88-
GalacticPOIs = EDAstro.GetPOIs();
88+
foreach (var navBookmark in await EDAstro.GetPOIsAsync() )
89+
{
90+
GalacticPOIs.Add( navBookmark );
91+
}
8992
GetBookmarkExtras(GalacticPOIs);
9093
}
9194

NavigationService/EDAstro.cs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,18 +5,19 @@
55
using System.Collections.ObjectModel;
66
using System.Linq;
77
using System.Net;
8+
using System.Threading.Tasks;
89
using Utilities;
910

1011
namespace EddiNavigationService
1112
{
1213
public static class EDAstro
1314
{
1415
private const string GalacticPOI_URI = "https://edastro.com/poi/json/combined";
15-
public static ObservableCollection<NavBookmark> GetPOIs()
16+
public static async Task<ObservableCollection<NavBookmark>> GetPOIsAsync()
1617
{
1718
var galacticPOIs = new ObservableCollection<NavBookmark>();
1819

19-
var jsonString = Net.DownloadString(GalacticPOI_URI);
20+
var jsonString = await Net.DownloadStringAsync(GalacticPOI_URI);
2021
if (!string.IsNullOrEmpty(jsonString))
2122
{
2223
var jArray = JArray.Parse(jsonString);

Utilities/Net.cs

Lines changed: 82 additions & 99 deletions
Original file line numberDiff line numberDiff line change
@@ -1,198 +1,181 @@
11
using Microsoft.Win32;
22
using System;
33
using System.IO;
4-
using System.Net;
54
using System.Net.Http;
65
using System.Text;
7-
using System.Threading;
86
using System.Threading.Tasks;
97

108
namespace Utilities
119
{
1210
public static class Net
1311
{
14-
public static string DownloadString(string uri)
12+
private static readonly HttpClient httpClient = new HttpClient(
13+
new HttpClientHandler
14+
{
15+
AutomaticDecompression =
16+
System.Net.DecompressionMethods.Deflate | System.Net.DecompressionMethods.GZip
17+
} );
18+
19+
public static async Task<string> DownloadStringAsync ( string uri )
1520
{
1621
try
1722
{
18-
HttpWebRequest request = GetRequest(uri);
19-
request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
20-
using ( HttpWebResponse response = GetResponse( request ) )
23+
Logging.Debug( "Requesting " + uri );
24+
using ( var response = await httpClient.GetAsync( uri, HttpCompletionOption.ResponseHeadersRead ) )
2125
{
22-
if ( response == null ) // Means that the system was not found
26+
if ( !response.IsSuccessStatusCode )
2327
{
28+
Logging.Error( $"Error obtaining string response from {uri}: {response.StatusCode}" );
2429
return null;
2530
}
2631

27-
// Obtain and parse our response
28-
var encoding = string.IsNullOrEmpty(response.CharacterSet)
29-
? Encoding.UTF8
30-
: Encoding.GetEncoding(response.CharacterSet);
31-
32+
var encoding = GetEncodingFromResponse( response );
3233
Logging.Debug( "Reading response from " + uri );
33-
return ReadResponseString( response, encoding );
34+
return await ReadResponseStringAsync( response, encoding );
3435
}
3536
}
3637
catch ( Exception e )
3738
{
38-
Logging.Error($"Error obtaining string response from {uri}: {e.Message}", e);
39+
Logging.Error( $"Error obtaining string response from {uri}: {e.Message}", e );
3940
return null;
4041
}
4142
}
4243

43-
private static string ReadResponseString(HttpWebResponse response, Encoding encoding)
44+
private static Encoding GetEncodingFromResponse ( HttpResponseMessage response )
45+
{
46+
if ( response.Content.Headers.ContentType?.CharSet != null )
47+
{
48+
try
49+
{
50+
return Encoding.GetEncoding( response.Content.Headers.ContentType.CharSet );
51+
}
52+
catch
53+
{
54+
// Fallback to UTF8 if encoding is not supported
55+
}
56+
}
57+
58+
return Encoding.UTF8;
59+
}
60+
61+
private static async Task<string> ReadResponseStringAsync ( HttpResponseMessage response, Encoding encoding )
4462
{
4563
string data = null;
46-
int attempts = 0;
64+
var attempts = 0;
4765
Exception ex = null;
4866

49-
while (data is null && attempts < 10)
67+
while ( data is null && attempts < 10 )
5068
{
5169
try
5270
{
53-
using (var stream = response.GetResponseStream())
71+
using ( var stream = await response.Content.ReadAsStreamAsync() )
5472
{
55-
if (stream != null)
73+
if ( stream != null )
5674
{
57-
var reader = new StreamReader(stream, encoding);
58-
data = reader.ReadToEnd();
59-
return data;
75+
using ( var reader = new StreamReader( stream, encoding ) )
76+
{
77+
data = await reader.ReadToEndAsync();
78+
return data;
79+
}
6080
}
81+
6182
return null;
6283
}
6384
}
64-
catch (Exception e)
85+
catch ( Exception e )
6586
{
6687
attempts++;
67-
Thread.Sleep(50);
88+
await Task.Delay( 50 );
6889
ex = e;
6990
}
7091
}
7192

72-
if (attempts >= 10 && ex != null)
93+
if ( attempts >= 10 && ex != null )
7394
{
74-
Logging.Warn(ex.Message, ex);
95+
Logging.Warn( ex.Message, ex );
7596
}
7697

7798
return data;
7899
}
79100

80-
public static async Task<string> DownloadFileAsync(string uri, string name)
101+
public static async Task<string> DownloadFileAsync ( string uri, string name )
81102
{
82103
try
83104
{
84-
var fileName = Path.GetTempPath() + @"\" + name;
85-
var response = await new HttpClient().GetAsync(uri);
86-
if ( !response.IsSuccessStatusCode )
87-
{
88-
Logging.Error( $"Failed to download update file. Status code: {response.StatusCode}" );
89-
return null;
90-
}
91-
using (var fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write))
105+
var fileName = Path.Combine( Path.GetTempPath(), name );
106+
using ( var response = await httpClient.GetAsync( uri, HttpCompletionOption.ResponseHeadersRead ) )
92107
{
93-
await response.Content.CopyToAsync(fs);
108+
if ( !response.IsSuccessStatusCode )
109+
{
110+
Logging.Error( $"Failed to download update file. Status code: {response.StatusCode}" );
111+
return null;
112+
}
113+
114+
using ( var fs = new FileStream( fileName, FileMode.OpenOrCreate, FileAccess.Write ) )
115+
{
116+
await response.Content.CopyToAsync( fs );
117+
}
94118
}
119+
95120
return fileName;
96121
}
97-
catch (Exception ex)
122+
catch ( Exception ex )
98123
{
99-
Logging.Error("Failed to download file " + uri, ex);
124+
Logging.Error( "Failed to download file " + uri, ex );
100125
return null;
101126
}
102127
}
103128

104-
// Set up a request with the correct parameters for talking to the companion app
105-
private static HttpWebRequest GetRequest(string url)
106-
{
107-
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
108-
request.Timeout = 10000;
109-
request.ReadWriteTimeout = 10000;
110-
return request;
111-
}
112-
113-
// Obtain a response, ensuring that we obtain the response's cookies
114-
private static HttpWebResponse GetResponse(HttpWebRequest request)
115-
{
116-
Logging.Debug("Requesting " + request.RequestUri);
117-
118-
HttpWebResponse response;
119-
try
120-
{
121-
response = (HttpWebResponse)request.GetResponse();
122-
}
123-
catch (WebException wex)
124-
{
125-
if (!(wex.Response is HttpWebResponse errorResponse))
126-
{
127-
// No error response
128-
Logging.Warn("Failed to obtain response, error code " + wex.Status);
129-
return null;
130-
}
131-
else if (errorResponse.StatusCode == HttpStatusCode.NotFound)
132-
{
133-
// Not found is usual
134-
return null;
135-
}
136-
else
137-
{
138-
Logging.Warn("Bad response, error code " + wex.Status);
139-
throw;
140-
}
141-
}
142-
Logging.Debug("Response is: ", response);
143-
return response;
144-
}
145-
146-
public static string GetDefaultBrowserPath()
129+
public static string GetDefaultBrowserPath ()
147130
{
148-
string urlAssociation = @"Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http";
149-
string browserPathKey = @"$BROWSER$\shell\open\command";
131+
var urlAssociation = @"Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http";
132+
var browserPathKey = @"$BROWSER$\shell\open\command";
150133

151134
try
152135
{
153136
// Read default browser path from userChoiceLKey
154-
var userChoiceKey = Registry.CurrentUser.OpenSubKey(urlAssociation + @"\UserChoice", false);
137+
var userChoiceKey = Registry.CurrentUser.OpenSubKey( urlAssociation + @"\UserChoice", false );
155138

156139
// If user choice was not found, try machine default
157-
if (userChoiceKey == null)
140+
if ( userChoiceKey == null )
158141
{
159142
// Read default browser path from Win XP registry key
160143
// If browser path wasn’t found, try Win Vista (and newer) registry key
161-
var browserKey = Registry.ClassesRoot.OpenSubKey(@"HTTP\shell\open\command", false) ??
144+
var browserKey = Registry.ClassesRoot.OpenSubKey( @"HTTP\shell\open\command", false ) ??
162145
Registry.CurrentUser.OpenSubKey(
163-
urlAssociation, false);
146+
urlAssociation, false );
164147

165-
var path = CleanifyBrowserPath(browserKey?.GetValue(null) as string);
148+
var path = CleanifyBrowserPath( browserKey?.GetValue( null ) as string );
166149
browserKey?.Close();
167-
Logging.Debug("Browser path (1) is " + path);
150+
Logging.Debug( "Browser path (1) is " + path );
168151
return path;
169152
}
170153
else
171154
{
172155
// user defined browser choice was found
173-
string progId = (userChoiceKey.GetValue("ProgId")?.ToString());
156+
var progId = userChoiceKey.GetValue( "ProgId" )?.ToString();
174157
userChoiceKey.Close();
175158

176159
// now look up the path of the executable
177-
string concreteBrowserKey = browserPathKey.Replace("$BROWSER$", progId);
178-
var kp = Registry.ClassesRoot.OpenSubKey(concreteBrowserKey, false);
179-
var browserPath = CleanifyBrowserPath(kp?.GetValue(null) as string);
160+
var concreteBrowserKey = browserPathKey.Replace( "$BROWSER$", progId );
161+
var kp = Registry.ClassesRoot.OpenSubKey( concreteBrowserKey, false );
162+
var browserPath = CleanifyBrowserPath( kp?.GetValue( null ) as string );
180163
kp?.Close();
181-
Logging.Debug("Browser path (2) is " + browserPath);
164+
Logging.Debug( "Browser path (2) is " + browserPath );
182165
return browserPath;
183166
}
184167
}
185-
catch (Exception ex)
168+
catch ( Exception ex )
186169
{
187-
Logging.Error("Failed to find default browser: ", ex);
170+
Logging.Error( "Failed to find default browser: ", ex );
188171
return "explorer.exe";
189172
}
190173
}
191174

192-
private static string CleanifyBrowserPath(string p)
175+
private static string CleanifyBrowserPath ( string p )
193176
{
194-
string[] url = p.Split('"');
195-
string clean = url[1];
177+
var url = p.Split( '"' );
178+
var clean = url[ 1 ];
196179
return clean;
197180
}
198181
}

0 commit comments

Comments
 (0)