Skip to content

Allow caller to Specify desired OutputType #499

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 18 commits into from
Jan 27, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
111 changes: 81 additions & 30 deletions src/Authentication/Authentication/Cmdlets/InvokeMgGraphRequest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,34 @@ public InvokeMgGraphRequest()
HelpMessage = "Custom User Specified User Agent")]
public string UserAgent { get; set; }

/// <summary>
/// Return full Graph Http Response without interpreting
/// </summary>
[Parameter(Mandatory = false,
Position = 19,
ParameterSetName = Constants.UserParameterSet,
HelpMessage = "Return full Graph Http Response without interpreting. " +
"Specifying -RequestClone stores the original request in a variable")]
public SwitchParameter Raw { get; set; }

/// <summary>
/// Cloned Copy of Original Http Request
/// </summary>
[Parameter(Position = 20, ParameterSetName = Constants.UserParameterSet,
Mandatory = false,
HelpMessage = "A clone of the original request will be stored here")]
[Alias("ORC")]
public string OriginalRequestClone { get; set; }

/// <summary>
/// Return full JSON Form, without converting to HashTable
/// </summary>
[Parameter(Mandatory = false,
Position = 21,
ParameterSetName = Constants.UserParameterSet,
HelpMessage = "Return full Json Response")]
public SwitchParameter Json { get; set; }

/// <summary>
/// Wait for .NET debugger to attach
/// </summary>
Expand Down Expand Up @@ -420,50 +448,73 @@ private Uri PrepareUri(HttpClient httpClient, Uri uri)
/// Process Http Response
/// </summary>
/// <param name="response"></param>
internal void ProcessResponse(HttpResponseMessage response)
internal async Task ProcessResponse(HttpResponseMessage response)
{
if (response == null) throw new ArgumentNullException(nameof(response));

var baseResponseStream = response.GetResponseStream();

if (ShouldWriteToPipeline)
{
using (var responseStream = new BufferingStreamReader(baseResponseStream))
//When -Raw is Specified, print out the actual HttpResponse.
if (Raw)
{
// determine the response type
var returnType = response.CheckReturnType();
// Try to get the response encoding from the ContentType header.
Encoding encoding = null;
var charSet = response.Content.Headers.ContentType?.CharSet;
if (!string.IsNullOrEmpty(charSet))
// if -ORC "originalRequestClone" is specified, clone and store.
if (!string.IsNullOrEmpty(OriginalRequestClone))
{
charSet.TryGetEncoding(out encoding);
var vi = SessionState.PSVariable;
var originalRequest = await response.CloneHttpRequestWithContent();
vi.Set(OriginalRequestClone, originalRequest);
}

if (string.IsNullOrEmpty(charSet) && returnType == RestReturnType.Json)
WriteObject(response);
}
else
{
using (var responseStream = new BufferingStreamReader(baseResponseStream))
{
encoding = Encoding.UTF8;
}
// determine the response type
var returnType = response.CheckReturnType();
// Try to get the response encoding from the ContentType header.
Encoding encoding = null;
var charSet = response.Content.Headers.ContentType?.CharSet;
if (!string.IsNullOrEmpty(charSet))
{
charSet.TryGetEncoding(out encoding);
}

Exception ex = null;
if (string.IsNullOrEmpty(charSet) && returnType == RestReturnType.Json)
{
encoding = Encoding.UTF8;
}

var str = responseStream.DecodeStream(ref encoding);
Exception ex = null;

string encodingVerboseName;
try
{
encodingVerboseName = string.IsNullOrEmpty(encoding.HeaderName)
? encoding.EncodingName
: encoding.HeaderName;
}
catch (NotSupportedException)
{
encodingVerboseName = encoding.EncodingName;
}
var str = responseStream.DecodeStream(ref encoding);

// NOTE: Tests use this verbose output to verify the encoding.
WriteVerbose(Resources.ContentEncodingVerboseMessage.FormatCurrentCulture(encodingVerboseName));
WriteObject(str.TryConvertToJson(out var obj, ref ex) ? obj : str);
string encodingVerboseName;
try
{
encodingVerboseName = string.IsNullOrEmpty(encoding.HeaderName)
? encoding.EncodingName
: encoding.HeaderName;
}
catch (NotSupportedException)
{
encodingVerboseName = encoding.EncodingName;
}

// NOTE: Tests use this verbose output to verify the encoding.
WriteVerbose(Resources.ContentEncodingVerboseMessage.FormatCurrentCulture(encodingVerboseName));
//If -Json is specified, return the Json string without converting to HashTable
if (Json)
{
WriteObject(str);
}
else
{
WriteObject(str.TryConvertToJson(out var obj, ref ex) ? obj : str);
}
}
}
}

Expand Down Expand Up @@ -1117,7 +1168,7 @@ private async Task ProcessRecordAsync()
ThrowTerminatingError(httpErrorRecord);
}

ProcessResponse(httpResponseMessage);
await ProcessResponse(httpResponseMessage);
}
}
catch (HttpRequestException ex)
Expand Down
91 changes: 89 additions & 2 deletions src/Authentication/Authentication/Helpers/WebResponseHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,8 @@

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net.Http;
using Microsoft.Graph.PowerShell.Authentication.Cmdlets;
using System.Threading.Tasks;

namespace Microsoft.Graph.PowerShell.Authentication.Helpers
{
Expand Down Expand Up @@ -34,5 +33,93 @@ internal static Dictionary<string, IEnumerable<string>> GetHttpResponseHeaders(t

return headers;
}

/// <summary>
/// Clones an HttpRequestMessage (without the content)
/// </summary>
/// <param name="original">Original HttpRequestMessage (Will be diposed before returning)</param>
/// <param name="requestUri"></param>
/// <param name="method"></param>
/// <returns>A clone of the HttpRequestMessage</returns>
private static HttpRequestMessage CloneHttpRequest(this HttpRequestMessage original, Uri requestUri = null, HttpMethod method = null)
{
var clone = new HttpRequestMessage
{
Method = method ?? original.Method,
RequestUri = requestUri ?? original.RequestUri,
Version = original.Version,
};

foreach (var prop in original.Properties)
{
clone.Properties.Add(prop);
}

foreach (var header in original.Headers)
{
/*
**temporarily skip cloning telemetry related headers**
clone.Headers.TryAddWithoutValidation(header.Key, header.Value);
*/
if (!"x-ms-unique-id".Equals(header.Key) && !"x-ms-client-request-id".Equals(header.Key) && !"CommandName".Equals(header.Key) && !"FullCommandName".Equals(header.Key) && !"ParameterSetName".Equals(header.Key) && !"User-Agent".Equals(header.Key))
{
clone.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
}

return clone;
}

/// <summary>
/// Clones an HttpRequestMessage (including the content stream and content headers)
/// </summary>
/// <param name="original">Original HttpRequestMessage (Will be diposed before returning)</param>
/// <param name="requestUri"></param>
/// <param name="method"></param>
/// <returns>A clone of the HttpRequestMessage</returns>
private static async Task<HttpRequestMessage> CloneHttpRequestWithContent(this HttpRequestMessage original, Uri requestUri = null, HttpMethod method = null)
{
var clone = original.CloneHttpRequest(requestUri, method);
var stream = new System.IO.MemoryStream();
if (original.Content != null)
{
await original.Content.CopyToAsync(stream).ConfigureAwait(false);
stream.Position = 0;
clone.Content = new StreamContent(stream);
if (original.Content.Headers != null)
{
foreach (var h in original.Content.Headers)
{
clone.Content.Headers.Add(h.Key, h.Value);
}
}
}
return clone;
}

/// <summary>
/// Clones a HttpRequestMessage contained in a corresponding HttpResponseMessage (including the content stream and content headers)
/// </summary>
/// <param name="original">Original HttpRequestMessage (Will be disposed before returning)</param>
/// <param name="requestUri"></param>
/// <param name="method"></param>
/// <returns>A clone of the HttpRequestMessage</returns>
internal static Task<HttpRequestMessage> CloneHttpRequestWithContent(this HttpResponseMessage original,
Uri requestUri = null, HttpMethod method = null)
{
return original.RequestMessage.CloneHttpRequestWithContent(requestUri, method);
}
/// <summary>
/// Clones a HttpRequestMessage contained in a corresponding HttpResponseMessage
/// </summary>
/// <param name="original">Original HttpRequestMessage (Will be disposed before returning)</param>
/// <param name="requestUri"></param>
/// <param name="method"></param>
/// <returns>A clone of the HttpRequestMessage</returns>
internal static HttpRequestMessage CloneHttpRequest(this HttpResponseMessage original, Uri requestUri = null,
HttpMethod method = null)
{
return original.RequestMessage.CloneHttpRequest(requestUri, method);
}
}
}