Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
405 changes: 146 additions & 259 deletions Samples/SampleWdpClient.UniversalWindows/MainPage.xaml.cs

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ private async Task<Stream> DeleteAsync(Uri uri)
{
if (!response.IsSuccessStatusCode)
{
throw new DevicePortalException(response);
throw await DevicePortalException.CreateAsync(response);
Copy link
Copy Markdown
Contributor Author

@dotMorten dotMorten Feb 15, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You shouldn't have async code in a constructor, so I changed the exception creation to be a static async creator (see further down), and changed all uses of it to this instead.

}

if (response.Content != null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ private async Task<Stream> GetAsync(
{
if (!response.IsSuccessStatusCode)
{
throw new DevicePortalException(response);
throw await DevicePortalException.CreateAsync(response);
}

using (HttpContent content = response.Content)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ private async Task<Stream> PostAsync(
{
if (!response.IsSuccessStatusCode)
{
throw new DevicePortalException(response);
throw await DevicePortalException.CreateAsync(response);
}

if (response.Content != null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ private async Task<Stream> PutAsync(
{
if (!response.IsSuccessStatusCode)
{
throw new DevicePortalException(response);
throw await DevicePortalException.CreateAsync(response);
}

if (response.Content != null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,22 +116,19 @@ private async Task StartListeningForMessagesInternalAsync()
while (this.keepListeningForMessages)
{
await webSocketTask.ConfigureAwait(false);
webSocketTask.Wait();

using (HttpResponseMessage response = webSocketTask.Result)
{
if (!response.IsSuccessStatusCode)
{
throw new DevicePortalException(response);
throw await DevicePortalException.CreateAsync(response);
}

using (HttpContent content = response.Content)
{
MemoryStream dataStream = new MemoryStream();

Task copyTask = content.CopyToAsync(dataStream);
await copyTask.ConfigureAwait(false);
copyTask.Wait();
await content.CopyToAsync(dataStream).ConfigureAwait(false);

// Ensure we return with the stream pointed at the origin.
dataStream.Position = 0;
Expand Down Expand Up @@ -165,7 +162,7 @@ private async Task SendMessageInternalAsync(string message)
{
if (!response.IsSuccessStatusCode)
{
throw new DevicePortalException(response);
throw await DevicePortalException.CreateAsync(response);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ public async Task InstallApplicationAsync(

await Task.Delay(TimeSpan.FromMilliseconds(stateCheckIntervalMs));

status = await this.GetInstallStatusAsync();
status = await this.GetInstallStatusAsync().ConfigureAwait(false);
}
while (status == ApplicationInstallStatus.InProgress);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ public enum DevicePortalPlatforms
/// <returns>String containing the device's family.</returns>
public async Task<string> GetDeviceFamilyAsync()
{
DeviceOsFamily deviceFamily = await this.GetAsync<DeviceOsFamily>(DeviceFamilyApi);
DeviceOsFamily deviceFamily = await this.GetAsync<DeviceOsFamily>(DeviceFamilyApi).ConfigureAwait(false);
return deviceFamily.Family;
}

Expand All @@ -111,9 +111,9 @@ public async Task<string> GetDeviceNameAsync()
/// Gets information about the device's operating system.
/// </summary>
/// <returns>OperatingSystemInformation object containing details of the installed operating system.</returns>
public async Task<OperatingSystemInformation> GetOperatingSystemInformationAsync()
public Task<OperatingSystemInformation> GetOperatingSystemInformationAsync()
{
return await this.GetAsync<OperatingSystemInformation>(OsInfoApi);
return this.GetAsync<OperatingSystemInformation>(OsInfoApi);
}

/// <summary>
Expand All @@ -122,9 +122,9 @@ public async Task<OperatingSystemInformation> GetOperatingSystemInformationAsync
/// <param name="name">The name to assign to the device.</param>
/// <remarks>The new name does not take effect until the device has been restarted.</remarks>
/// <returns>Task tracking setting the device name completion.</returns>
public async Task SetDeviceNameAsync(string name)
public Task SetDeviceNameAsync(string name)
{
await this.PostAsync(
return this.PostAsync(
MachineNameApi,
string.Format("name={0}", Utilities.Hex64Encode(name)));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -216,8 +216,8 @@ public async Task ConnectAsync(
DeviceConnectionStatus.Connecting,
DeviceConnectionPhase.RequestingOperatingSystemInformation,
connectionPhaseDescription);
this.deviceConnection.Family = await this.GetDeviceFamilyAsync();
this.deviceConnection.OsInfo = await this.GetOperatingSystemInformationAsync();
this.deviceConnection.Family = await this.GetDeviceFamilyAsync().ConfigureAwait(false);
this.deviceConnection.OsInfo = await this.GetOperatingSystemInformationAsync().ConfigureAwait(false);

// Default to using whatever was specified in the connection.
bool requiresHttps = this.IsUsingHttps();
Expand All @@ -231,7 +231,7 @@ public async Task ConnectAsync(
DeviceConnectionStatus.Connecting,
DeviceConnectionPhase.DeterminingConnectionRequirements,
connectionPhaseDescription);
requiresHttps = await this.GetIsHttpsRequiredAsync();
requiresHttps = await this.GetIsHttpsRequiredAsync().ConfigureAwait(false);
}

// Connect the device to the specified network.
Expand All @@ -242,10 +242,10 @@ public async Task ConnectAsync(
DeviceConnectionStatus.Connecting,
DeviceConnectionPhase.ConnectingToTargetNetwork,
connectionPhaseDescription);
WifiInterfaces wifiInterfaces = await this.GetWifiInterfacesAsync();
WifiInterfaces wifiInterfaces = await this.GetWifiInterfacesAsync().ConfigureAwait(false);

// TODO - consider what to do if there is more than one wifi interface on a device
await this.ConnectToWifiNetworkAsync(wifiInterfaces.Interfaces[0].Guid, ssid, ssidKey);
await this.ConnectToWifiNetworkAsync(wifiInterfaces.Interfaces[0].Guid, ssid, ssidKey).ConfigureAwait(false);
}

// Get the device's IP configuration and update the connection as appropriate.
Expand All @@ -268,7 +268,7 @@ public async Task ConnectAsync(
}

this.deviceConnection.UpdateConnection(
await this.GetIpConfigAsync(),
await this.GetIpConfigAsync().ConfigureAwait(false),
requiresHttps,
preservePort);
}
Expand Down Expand Up @@ -296,6 +296,7 @@ await this.GetIpConfigAsync(),
while (innermostException.InnerException != null)
{
innermostException = innermostException.InnerException;
await Task.Yield();
}

this.ConnectionFailedDescription = innermostException.Message;
Expand Down Expand Up @@ -372,16 +373,13 @@ public async Task SaveEndpointResponseToFileAsync(

websocket.WebSocketStreamReceived += streamReceivedHandler;

Task connect = websocket.ConnectAsync(endpoint);
connect.Wait();
await websocket.ConnectAsync(endpoint);

Task startListeningForStreamTask = websocket.ReceiveMessagesAsync();
startListeningForStreamTask.Wait();
await websocket.ReceiveMessagesAsync();

streamReceived.WaitOne();

Task stopListeningForStreamTask = websocket.CloseAsync();
stopListeningForStreamTask.Wait();
await websocket.CloseAsync();

websocket.WebSocketStreamReceived -= streamReceivedHandler;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,16 +72,16 @@ public DevicePortalException(
/// <param name="responseMessage">Http response message.</param>
/// <param name="message">Optional exception message.</param>
/// <param name="innerException">Optional inner exception.</param>
public DevicePortalException(
public static async Task<DevicePortalException> CreateAsync(
HttpResponseMessage responseMessage,
string message = "",
Exception innerException = null) : this(
responseMessage.StatusCode,
Exception innerException = null)
{
DevicePortalException error = new DevicePortalException(responseMessage.StatusCode,
responseMessage.ReasonPhrase,
responseMessage.RequestMessage != null ? responseMessage.RequestMessage.RequestUri : null,
message,
innerException)
{
innerException);
try
{
if (responseMessage.Content != null)
Expand All @@ -92,9 +92,7 @@ public DevicePortalException(
{
dataStream = new MemoryStream();

Task copyTask = content.CopyToAsync(dataStream);
copyTask.ConfigureAwait(false);
copyTask.Wait();
await content.CopyToAsync(dataStream).ConfigureAwait(false);

// Ensure we point the stream at the origin.
dataStream.Position = 0;
Expand All @@ -103,12 +101,7 @@ public DevicePortalException(
IBuffer dataBuffer = null;
using (IHttpContent messageContent = responseMessage.Content)
{
IAsyncOperationWithProgress<IBuffer, ulong> bufferOperation = messageContent.ReadAsBufferAsync();
while (bufferOperation.Status != AsyncStatus.Completed)
{
}

dataBuffer = bufferOperation.GetResults();
dataBuffer = await messageContent.ReadAsBufferAsync();

if (dataBuffer != null)
{
Expand All @@ -123,26 +116,29 @@ public DevicePortalException(

HttpErrorResponse errorResponse = (HttpErrorResponse)serializer.ReadObject(dataStream);

this.HResult = errorResponse.ErrorCode;
this.Reason = errorResponse.ErrorMessage;
error.HResult = errorResponse.ErrorCode;
error.Reason = errorResponse.ErrorMessage;

// If we didn't get the Hresult and reason from these properties, try the other ones.
if (this.HResult == 0)
if (error.HResult == 0)
{
this.HResult = errorResponse.Code;
error.HResult = errorResponse.Code;
}

if (string.IsNullOrEmpty(this.Reason))
if (string.IsNullOrEmpty(error.Reason))
{
this.Reason = errorResponse.Reason;
error.Reason = errorResponse.Reason;
}

dataStream.Dispose();
}
}
}
catch (Exception)
{
// Do nothing if we fail to get additional error details from the response body.
}
return error;
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ private async Task<T> GetAsync<T>(

DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));

using (Stream dataStream = await this.GetAsync(uri))
using (Stream dataStream = await this.GetAsync(uri).ConfigureAwait(false))
{
if ((dataStream != null) &&
(dataStream.Length != 0))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ public partial class DevicePortal
/// Gets the available bluetooth device information.
/// </summary>
/// <returns>List of Available bluetooth devices</returns>
public AvailableBluetoothDevicesInfo GetAvailableBluetoothDevicesInfo()
public async Task<AvailableBluetoothDevicesInfo> GetAvailableBluetoothDevicesInfoAsync()
{
AvailableBluetoothDevicesInfo bluetooth = null;
ManualResetEvent bluetoothReceived = new ManualResetEvent(false);
Expand All @@ -87,13 +87,11 @@ public AvailableBluetoothDevicesInfo GetAvailableBluetoothDevicesInfo()
};
this.BluetoothDeviceListReceived += bluetoothReceivedHandler;

Task startListeningForBluetooth = this.StartListeningForBluetoothAsync(AvailableBluetoothDevicesApi);
startListeningForBluetooth.Wait();
await this.StartListeningForBluetoothAsync(AvailableBluetoothDevicesApi);

bluetoothReceived.WaitOne();

Task stopListeningForBluetooth = this.StopListeningForBluetoothAsync();
stopListeningForBluetooth.Wait();
await this.StopListeningForBluetoothAsync();

this.BluetoothDeviceListReceived -= bluetoothReceivedHandler;
return bluetooth;
Expand All @@ -103,7 +101,7 @@ public AvailableBluetoothDevicesInfo GetAvailableBluetoothDevicesInfo()
/// Gets the paired bluetooth device information.
/// </summary>
/// <returns>List of paired bluetooth devices</returns>
public PairedBluetoothDevicesInfo GetPairedBluetoothDevicesInfo()
public async Task<PairedBluetoothDevicesInfo> GetPairedBluetoothDevicesInfoAsync()
{
PairedBluetoothDevicesInfo bluetooth = null;
ManualResetEvent pairedBluetoothReceived = new ManualResetEvent(false);
Expand All @@ -118,13 +116,11 @@ public PairedBluetoothDevicesInfo GetPairedBluetoothDevicesInfo()
};
this.PairedBluetoothDeviceListReceived += pairedBluetoothReceivedHandler;

Task startListeningForPairedBluetooth = this.StartListeningForPairedBluetoothAsync(PairedBluetoothDevicesApi);
startListeningForPairedBluetooth.Wait();
await this.StartListeningForPairedBluetoothAsync(PairedBluetoothDevicesApi);

pairedBluetoothReceived.WaitOne();

Task stopListeningForPairedBluetooth = this.StopListeningForPairedBluetoothAsync();
stopListeningForPairedBluetooth.Wait();
await this.StopListeningForPairedBluetoothAsync();

this.PairedBluetoothDeviceListReceived -= pairedBluetoothReceivedHandler;
return bluetooth;
Expand All @@ -135,7 +131,7 @@ public PairedBluetoothDevicesInfo GetPairedBluetoothDevicesInfo()
/// </summary>
/// <param name="deviceId">Device Id.</param>
/// <returns>Results of pairing a bluetooth device</returns>
public PairBluetoothDevicesInfo GetPairBluetoothDevicesInfo(string deviceId)
public async Task<PairBluetoothDevicesInfo> GetPairBluetoothDevicesInfoAsync(string deviceId)
{
PairBluetoothDevicesInfo bluetooth = null;
ManualResetEvent pairBluetoothReceived = new ManualResetEvent(false);
Expand All @@ -150,13 +146,11 @@ public PairBluetoothDevicesInfo GetPairBluetoothDevicesInfo(string deviceId)
};
this.PairBluetoothDeviceListReceived += pairBluetoothReceivedHandler;

Task startListeningForPairBluetooth = this.StartListeningForPairBluetoothAsync(PairBluetoothDevicesApi, string.Format("deviceId={0}", Utilities.Hex64Encode(deviceId)));
startListeningForPairBluetooth.Wait();
await this.StartListeningForPairBluetoothAsync(PairBluetoothDevicesApi, string.Format("deviceId={0}", Utilities.Hex64Encode(deviceId)));

pairBluetoothReceived.WaitOne();

Task stopListeningForPairBluetooth = this.StopListeningForPairBluetoothAsync();
stopListeningForPairBluetooth.Wait();
await this.StopListeningForPairBluetoothAsync();

this.PairBluetoothDeviceListReceived -= pairBluetoothReceivedHandler;
return bluetooth;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,15 @@ public async Task RegisterApplicationAsync(string folderName)

await this.PostAsync(
RegisterPackageApi,
string.Format("folder={0}", Utilities.Hex64Encode(folderName)));
string.Format("folder={0}", Utilities.Hex64Encode(folderName))).ConfigureAwait(false);

// Poll the status until complete.
ApplicationInstallStatus status = ApplicationInstallStatus.InProgress;
do
{
await Task.Delay(TimeSpan.FromMilliseconds(500));
await Task.Delay(TimeSpan.FromMilliseconds(500)).ConfigureAwait(false);

status = await this.GetInstallStatusAsync();
status = await this.GetInstallStatusAsync().ConfigureAwait(false);
}
while (status == ApplicationInstallStatus.InProgress);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,24 +43,11 @@ public async Task<Certificate> GetRootDeviceCertificateAsync(bool acceptUntruste
using (HttpClient client = new HttpClient(requestSettings))
{
this.ApplyHttpHeaders(client, HttpMethods.Get);

IAsyncOperationWithProgress<HttpResponseMessage, HttpProgress> responseOperation = client.GetAsync(uri);
TaskAwaiter<HttpResponseMessage> responseAwaiter = responseOperation.GetAwaiter();
while (!responseAwaiter.IsCompleted)
{
}

using (HttpResponseMessage response = responseOperation.GetResults())
using (HttpResponseMessage response = await client.GetAsync(uri))
{
using (IHttpContent messageContent = response.Content)
{
IAsyncOperationWithProgress<IBuffer, ulong> bufferOperation = messageContent.ReadAsBufferAsync();
TaskAwaiter<IBuffer> readBufferAwaiter = bufferOperation.GetAwaiter();
while (!readBufferAwaiter.IsCompleted)
{
}

certificate = new Certificate(bufferOperation.GetResults());
certificate = new Certificate(await messageContent.ReadAsBufferAsync());
}
}
}
Expand Down
Loading