Skip to content

Makes the ARM cmdlets even more generic #562

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Jul 7, 2015
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
Original file line number Diff line number Diff line change
Expand Up @@ -76,14 +76,14 @@ internal LongRunningOperationHelper(string activityName, Func<ResourceManagerRes
/// Waits for the operation to complete.
/// </summary>
/// <param name="operationResult">The operation result.</param>
internal JToken WaitOnOperation(OperationResult operationResult)
internal string WaitOnOperation(OperationResult operationResult)
{
// TODO: Re-factor this mess.
this.ProgressTrackerObject.UpdateProgress("Starting", 0);

var trackingResult = this.HandleOperationResponse(operationResult, this.IsResourceCreateOrUpdate ? operationResult.OperationUri : operationResult.LocationUri);

while (trackingResult.ShouldWait)
while (trackingResult != null && trackingResult.ShouldWait)
{
operationResult =
this.GetResourcesClient()
Expand Down Expand Up @@ -161,10 +161,11 @@ private TrackingOperationResult HandleOperationResponse(OperationResult operatio
/// <param name="operationResult">The result of the operation.</param>
private TrackingOperationResult HandleCreateOrUpdateResponse(OperationResult operationResult)
{
var resource = operationResult.Value == null
? null
: operationResult.Value
.ToObject<Resource<InsensitiveDictionary<JToken>>>(JsonExtensions.JsonObjectTypeSerializer);
Resource<InsensitiveDictionary<JToken>> resource;
if (!operationResult.Value.TryConvertTo<Resource<InsensitiveDictionary<JToken>>>(out resource))
{
return null;
}

if(resource == null && operationResult.HttpStatusCode == HttpStatusCode.Created)
{
Expand Down Expand Up @@ -444,11 +445,12 @@ private string GetAzureAsyncOperationState(OperationResult operationResult)
/// <param name="operationResult">The operation result.</param>
private static string GetResourceState(OperationResult operationResult)
{
var resource = operationResult.Value == null
? null
: operationResult.Value
.ToObject<Resource<InsensitiveDictionary<JToken>>>(JsonExtensions.JsonObjectTypeSerializer);

Resource<InsensitiveDictionary<JToken>> resource;
if (!operationResult.Value.TryConvertTo<Resource<InsensitiveDictionary<JToken>>>(out resource))
{
return null;
}

if (resource == null)
{
return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,6 @@ public class OperationResult
/// <summary>
/// Gets or sets the value.
/// </summary>
public JObject Value { get; set; }
public string Value { get; set; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public static string GetResourceId(string resourceId, string extensionResourceTy
resourceIdBuilder.Append(ResourceIdUtility.ProcessResourceTypeAndName(resourceType: extensionResourceType, resourceName: extensionResourceName));
}

return resourceId.ToString();
return resourceIdBuilder.ToString();
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Extensions
{
using System;
using System.Management.Automation;
using Microsoft.Azure.Commands.ResourceManager.Cmdlets.Entities.ErrorResponses;

Expand All @@ -31,5 +32,25 @@ internal static ErrorRecord ToErrorRecord(this ErrorResponseMessageException exc
// TODO: Improve this.
return new ErrorRecord(exception, exception.ErrorResponseMessage == null ? exception.HttpStatus.ToString() : exception.ErrorResponseMessage.Error.Code, ErrorCategory.CloseError, null);
}

/// <summary>
/// Converts <see cref="Exception"/> objects into <see cref="ErrorRecord"/>
/// </summary>
/// <param name="exception">The exception</param>
internal static ErrorRecord ToErrorRecord(this Exception exception)
{
// TODO: Improve this.
return new ErrorRecord(exception, exception.Message, ErrorCategory.CloseError, null);
}

/// <summary>
/// Converts <see cref="AggregateException"/> objects into <see cref="ErrorRecord"/>
/// </summary>
/// <param name="exception">The exception</param>
internal static ErrorRecord ToErrorRecord(this AggregateException aggregateException)
{
// TODO: Improve this.
return new ErrorRecord(aggregateException, aggregateException.ToString(), ErrorCategory.CloseError, null);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -50,5 +50,35 @@ public static async Task<T> ReadContentAsJsonAsync<T>(this HttpResponseMessage m
}
}
}

/// <summary>
/// Reads the JSON content from the http response message.
/// </summary>
/// <typeparam name="T">The type of object contained in the JSON.</typeparam>
/// <param name="message">The response message to be read.</param>
/// <param name="rewindContentStream">Rewind content stream if set to true.</param>
/// <returns>An object of type T instantiated from the response message's body.</returns>
public static async Task<string> ReadContentAsStringAsync(this HttpResponseMessage message, bool rewindContentStream = false)
{
using (var stream = await message.Content
.ReadAsStreamAsync()
.ConfigureAwait(continueOnCapturedContext: false))
using (var streamReader = new StreamReader(stream))
{
var streamPosition = stream.Position;
try
{

return streamReader.ReadToEnd();
}
finally
{
if (stream.CanSeek && streamPosition != stream.Position && rewindContentStream)
{
stream.Seek(streamPosition, SeekOrigin.Begin);
}
}
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,39 @@ public static bool CanConvertTo<TType>(this JToken jobject)
return jobject.TryConvertTo(out ignored);
}

/// <summary>
/// Checks if a conversion from the supplied <see cref="JToken"/> to a <typeparamref name="TType"/> can be made.
/// </summary>
/// <typeparam name="TType">The type to convert to.</typeparam>
/// <param name="str">The string.</param>
/// <param name="result">The result.</param>
public static bool TryConvertTo<TType>(this string str, out TType result)
{
if (string.IsNullOrWhiteSpace(str))
{
result = default(TType);
return true;
}

try
{
result = str.FromJson<TType>();
return !object.Equals(result, default(TType));
}
catch (FormatException)
{
}
catch (ArgumentException)
{
}
catch (JsonException)
{
}

result = default(TType);
return false;
}

/// <summary>
/// Checks if a conversion from the supplied <see cref="JToken"/> to a <typeparamref name="TType"/> can be made.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,10 +80,10 @@ protected override void OnProcessRecord()
odataQuery: this.ODataQuery);

var activity = string.Format("POST {0}", managementUri.PathAndQuery);
var result = this.GetLongRunningOperationTracker(activityName: activity, isResourceCreateOrUpdate: false)
var resultString = this.GetLongRunningOperationTracker(activityName: activity, isResourceCreateOrUpdate: false)
.WaitOnOperation(operationResult: operationResult);

this.WriteObject(result, ResourceObjectFormat.New);
this.TryConvertAndWriteObject(resultString, ResourceObjectFormat.New);
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ private void RunCmdlet()
isResourceCreateOrUpdate: false)
.WaitOnOperation(operationResult: operationResult);

this.WriteObject(result, ResourceObjectFormat.New);
this.TryConvertAndWriteObject(result, ResourceObjectFormat.New);
}
else
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ protected override void OnProcessRecord()
var result = this.GetLongRunningOperationTracker(activityName: activity, isResourceCreateOrUpdate: true)
.WaitOnOperation(operationResult: operationResult);

this.WriteObject(result.ToResource().ToPsObject(this.OutputObjectFormat.Value));
this.TryConvertAndWriteObject(result, this.OutputObjectFormat.Value);
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ protected override void OnProcessRecord()

var activity = string.Format("DELETE {0}", managementUri.PathAndQuery);

var result = this.GetLongRunningOperationTracker(activityName: activity, isResourceCreateOrUpdate: false)
this.GetLongRunningOperationTracker(activityName: activity, isResourceCreateOrUpdate: false)
.WaitOnOperation(operationResult: operationResult);

this.WriteObject(true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,24 @@ public ResourceManagerRestRestClient GetResourcesClient()
headerValues: AzureSession.ClientFactory.UserAgents));
}

/// <summary>
/// Writes the object
/// </summary>
/// <param name="resultString">The result as a string</param>
/// <param name="objectFormat">The <see cref="ResourceObjectFormat"/></param>
protected void TryConvertAndWriteObject(string resultString, ResourceObjectFormat objectFormat)
{
JToken resultJToken;
if (resultString.TryConvertTo<JToken>(out resultJToken))
{
this.WriteObject(resultJToken, objectFormat);
}
else
{
this.WriteObject(resultString);
}
}

/// <summary>
/// Writes a <see cref="JToken"/> object as a <see cref="PSObject"/>.
/// </summary>
Expand Down Expand Up @@ -326,10 +344,12 @@ private void HandleException(ExceptionDispatchInfo capturedException)
{
this.ThrowTerminatingError(errorResponseException.ToErrorRecord());
}

this.ThrowTerminatingError(aggregateException.InnerExceptions.Single().ToErrorRecord());
}
else
{
throw aggregateException.Flatten();
this.ThrowTerminatingError(aggregateException.ToErrorRecord());
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,8 +123,8 @@ protected override void OnProcessRecord()
var activity = string.Format("{0} {1}", this.ShouldUsePatchSemantics() ? "PATCH" : "PUT", managementUri.PathAndQuery);
var result = this.GetLongRunningOperationTracker(activityName: activity, isResourceCreateOrUpdate: true)
.WaitOnOperation(operationResult: operationResult);

this.WriteObject(result.ToResource().ToPsObject(this.OutputObjectFormat.Value));
this.TryConvertAndWriteObject(result, this.OutputObjectFormat.Value);
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,7 @@ private async Task<OperationResult> GetOperationResult(HttpResponseMessage respo
var operationResult = new OperationResult
{
Value = await response
.ReadContentAsJsonAsync<JObject>()
.ReadContentAsStringAsync()
.ConfigureAwait(continueOnCapturedContext: false),
};

Expand Down