Skip to content

Commit 5606f92

Browse files
committed
moved classes to separate files
1 parent 1c523be commit 5606f92

14 files changed

+736
-418
lines changed
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
// ----------------------------------------------------------------------------------
2+
//
3+
// Copyright Microsoft Corporation
4+
// Licensed under the Apache License, Version 2.0 (the "License");
5+
// you may not use this file except in compliance with the License.
6+
// You may obtain a copy of the License at
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
// Unless required by applicable law or agreed to in writing, software
9+
// distributed under the License is distributed on an "AS IS" BASIS,
10+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
// See the License for the specific language governing permissions and
12+
// limitations under the License.
13+
// ----------------------------------------------------------------------------------
14+
15+
using System;
16+
using System.Threading;
17+
using System.Threading.Tasks;
18+
using System.Net.Http;
19+
using System.Collections.Generic;
20+
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
21+
using Microsoft.Azure.Commands.Common.Authentication.Abstractions.Core;
22+
using Microsoft.Azure.Commands.Profile.Models;
23+
using System.Globalization;
24+
using Microsoft.Azure.Commands.Common.Authentication;
25+
26+
namespace Microsoft.Azure.Commands.Common
27+
{
28+
using NextDelegate = Func<HttpRequestMessage, CancellationToken, Action, Func<string, CancellationToken, Func<EventArgs>, Task>, Task<HttpResponseMessage>>;
29+
using SignalDelegate = Func<string, CancellationToken, Func<EventArgs>, Task>;
30+
using PipelineChangeDelegate = Action<Func<HttpRequestMessage, CancellationToken, Action, Func<string, CancellationToken, Func<EventArgs>, Task>, Func<HttpRequestMessage, CancellationToken, Action, Func<string, CancellationToken, Func<EventArgs>, Task>, Task<HttpResponseMessage>>, Task<HttpResponseMessage>>>;
31+
32+
internal class ContextAdapter
33+
{
34+
IProfileProvider _provider = AzureRmProfileProvider.Instance;
35+
IAuthenticationFactory _authenticator = AzureSession.Instance.AuthenticationFactory;
36+
37+
internal static ContextAdapter Instance => new ContextAdapter();
38+
39+
public void OnNewRequest(Dictionary<string, object> boundParameters, PipelineChangeDelegate prependStep, PipelineChangeDelegate appendStep)
40+
{
41+
appendStep(this.SendHandler(GetDefaultContext(_provider, boundParameters), AzureEnvironment.Endpoint.ResourceManager));
42+
}
43+
44+
public object GetParameterValue(string resourceId, string moduleName, Dictionary<string, object> boundParameters, string name)
45+
{
46+
var defaultContext = GetDefaultContext(_provider, boundParameters);
47+
var endpoint = GetDefaultEndpoint(defaultContext, AzureEnvironment.Endpoint.ResourceManager);
48+
switch (name)
49+
{
50+
case "subscriptionId":
51+
return defaultContext?.Subscription?.Id;
52+
case "host":
53+
return endpoint?.Host;
54+
case "port":
55+
return endpoint?.Port;
56+
}
57+
58+
return string.Empty;
59+
}
60+
61+
static IAzureContext GetDefaultContext(IProfileProvider provider, Dictionary<string, object> boundParameters)
62+
{
63+
IAzureContextContainer context;
64+
var contextConverter = new AzureContextConverter();
65+
if (boundParameters.ContainsKey("DefaultContext")
66+
&& contextConverter.CanConvertFrom(boundParameters["DefaultContext"], typeof(IAzureContextContainer)))
67+
{
68+
context = contextConverter.ConvertFrom(boundParameters["DefaultContext"], typeof(IAzureContextContainer), CultureInfo.InvariantCulture, true) as IAzureContextContainer;
69+
}
70+
else
71+
{
72+
context = provider.Profile;
73+
}
74+
75+
return context?.DefaultContext;
76+
}
77+
78+
static Uri GetDefaultEndpoint(IAzureContext context, string endpointName = AzureEnvironment.Endpoint.ResourceManager)
79+
{
80+
var environment = context?.Environment ?? AzureEnvironment.PublicEnvironments[EnvironmentName.AzureCloud];
81+
return environment.GetEndpointAsUri(endpointName);
82+
}
83+
84+
internal Func<HttpRequestMessage, CancellationToken, Action, SignalDelegate, NextDelegate, Task<HttpResponseMessage>> SendHandler(IAzureContext context, string resourceId)
85+
{
86+
return async (request, cancelToken, cancelAction, signal, next) =>
87+
{
88+
await AuthorizeRequest(context, resourceId, request, cancelToken);
89+
return await next(request, cancelToken, cancelAction, signal);
90+
};
91+
}
92+
93+
internal async Task AuthorizeRequest(IAzureContext context, string resourceId, HttpRequestMessage request, CancellationToken outerToken)
94+
{
95+
await Task.Run(() =>
96+
{
97+
var authToken = _authenticator.Authenticate(context.Account, context.Environment, context.Tenant.Id, null, "Never", null, resourceId);
98+
authToken.AuthorizeRequest((type, token) => request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(type, token));
99+
}, outerToken);
100+
}
101+
}
102+
103+
}

src/Accounts/Accounts/CommonModule/EventData.cs

Lines changed: 37 additions & 125 deletions
Original file line numberDiff line numberDiff line change
@@ -18,64 +18,21 @@
1818
using System.ComponentModel;
1919
using System.Diagnostics.Tracing;
2020
using System.Net.Http;
21-
using System.Threading;
2221
using System.Threading.Tasks;
23-
using GetEventData = System.Func<Microsoft.Azure.Commands.Common.EventData>;
2422

2523

2624
namespace Microsoft.Azure.Commands.Common
2725
{
2826

2927

30-
using EventListenerDelegate = Func<EventData, Task>;
31-
using GetParameterDelegate = Func<string, Dictionary<string, object>, string, object>;
32-
using SendAsyncStep = Func<HttpRequestMessage, IEventListener, ISendAsync, Task<HttpResponseMessage>>;
33-
using PipelineChangeDelegate = Action<EventData>;
28+
using EventListenerDelegate = Func<EventData, Task>;
29+
using GetParameterDelegate = Func<string, Dictionary<string, object>, string, object>;
30+
using SendAsyncStep = Func<HttpRequestMessage, IEventListener, ISendAsync, Task<HttpResponseMessage>>;
31+
using PipelineChangeDelegate = Action<EventData>;
3432

35-
/// <summary>
36-
/// The IEventListener Interface defines the communication mechanism for Signaling events during a remote call.
37-
/// </summary>
38-
/// <remarks>
39-
/// The interface is designed to be as minimal as possible, allow for quick peeking of the event type (<c>id</c>)
40-
/// and the cancellation status and provides a delegate for retrieving the event details themselves.
41-
/// </remarks>
42-
public interface IEventListener
43-
{
44-
Task Signal(string id, CancellationToken token, GetEventData createMessage);
45-
CancellationToken Token { get; }
46-
System.Action Cancel { get; }
47-
}
48-
49-
public class Response : EventData
50-
{
51-
public Response() : base()
52-
{
53-
}
54-
}
55-
56-
public class Response<T> : Response
57-
{
58-
private Func<Task<T>> _resultDelegate;
59-
private Task<T> _resultValue;
60-
61-
public Response(T value) : base() => _resultValue = Task.FromResult(value);
62-
public Response(Func<T> value) : base() => _resultDelegate = () => Task.FromResult(value());
63-
public Response(Func<Task<T>> value) : base() => _resultDelegate = value;
64-
public Task<T> Result => _resultValue ?? (_resultValue = this._resultDelegate());
65-
}
66-
67-
68-
/// <summary>
69-
/// The interface for sending an HTTP request across the wire.
70-
/// </summary>
71-
public interface ISendAsync
72-
{
73-
Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, IEventListener callback);
74-
}
7533

7634

77-
78-
[TypeConverter(typeof(EventDataConverter))]
35+
[TypeConverter(typeof(EventDataConverter))]
7936
/// <remarks>
8037
/// In PowerShell, we add on the EventDataConverter to support sending events between modules.
8138
/// Obviously, this code would need to be duplcated on both modules.
@@ -135,6 +92,38 @@ public partial class EventData : EventArgs
13592
/// </summary>
13693
public object ResponseMessage;
13794

95+
/// <summary>
96+
/// The name of the cmdlet that is being executed
97+
/// </summary>
98+
public string CmdletName;
99+
100+
/// <summary>
101+
/// Correlation Id for cmdlet invocation
102+
/// </summary>
103+
public string CmdletInvocationId;
104+
105+
/// <summary>
106+
///
107+
/// </summary>
108+
public string ProcessRecordId;
109+
110+
/// <summary>
111+
///
112+
/// </summary>
113+
public string ParameterSet;
114+
115+
/// <summary>
116+
///
117+
/// </summary>
118+
public string RequestCorrelationId;
119+
120+
/// <summary>
121+
/// The 'this.MyInvocation.BoundParameters' from the cmdlet
122+
/// </summary>
123+
public System.Collections.Generic.IDictionary<string,object> BoundParamters;
124+
125+
public System.Exception Exception;
126+
138127
/// <summary>
139128
/// Cancellation method for this event.
140129
///
@@ -146,81 +135,4 @@ public partial class EventData : EventArgs
146135
public System.Action Cancel;
147136
}
148137

149-
/// <summary>
150-
/// A PowerShell PSTypeConverter to adapt an <c>EventData</c> object that has been passed.
151-
/// Usually used between modules.
152-
/// </summary>
153-
public class EventDataConverter : System.Management.Automation.PSTypeConverter
154-
{
155-
public override bool CanConvertTo(object sourceValue, Type destinationType) => false;
156-
public override object ConvertTo(object sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase) => null;
157-
public override bool CanConvertFrom(dynamic sourceValue, Type destinationType) => destinationType == typeof(EventData) && CanConvertFrom(sourceValue);
158-
public override object ConvertFrom(dynamic sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue);
159-
160-
public static bool CanConvertFrom(dynamic sv)
161-
{
162-
var result = true;
163-
try
164-
{
165-
// check if this has required parameters...
166-
sv?.Id?.GetType();
167-
sv?.Message?.GetType();
168-
sv?.Parameter?.GetType();
169-
sv?.Value?.GetType();
170-
sv?.RequestMessage?.GetType();
171-
sv?.ResponseMessage?.GetType();
172-
sv?.Cancel?.GetType();
173-
}
174-
catch
175-
{
176-
return false;
177-
}
178-
return result;
179-
}
180-
181-
public static EventData ConvertFrom(dynamic sv)
182-
{
183-
try
184-
{
185-
return new EventData
186-
{
187-
Id = sv.Id,
188-
Message = sv.Message,
189-
Parameter = sv.Parameter,
190-
Value = sv.Value,
191-
RequestMessage = sv.RequestMessage,
192-
ResponseMessage = sv.ResponseMessage,
193-
Cancel = sv.Cancel
194-
};
195-
}
196-
catch
197-
{
198-
}
199-
return null;
200-
}
201-
}
202-
public static class Events
203-
{
204-
public const string Log = nameof(Log);
205-
public const string Validation = nameof(Validation);
206-
public const string ValidationWarning = nameof(ValidationWarning);
207-
public const string AfterValidation = nameof(AfterValidation);
208-
public const string RequestCreated = nameof(RequestCreated);
209-
public const string ResponseCreated = nameof(ResponseCreated);
210-
public const string URLCreated = nameof(URLCreated);
211-
public const string Finally = nameof(Finally);
212-
public const string HeaderParametersAdded = nameof( HeaderParametersAdded);
213-
public const string BodyContentSet = nameof( BodyContentSet);
214-
public const string BeforeCall = nameof( BeforeCall);
215-
public const string BeforeResponseDispatch = nameof( BeforeResponseDispatch);
216-
public const string CmdletProcessRecordStart = nameof(CmdletProcessRecordStart);
217-
public const string CmdletException = nameof(CmdletException);
218-
public const string CmdletGetPipeline = nameof(CmdletGetPipeline);
219-
public const string CmdletBeforeAPICall = nameof(CmdletBeforeAPICall);
220-
public const string CmdletAfterAPICall = nameof(CmdletAfterAPICall);
221-
public const string FollowingNextLink = nameof(FollowingNextLink);
222-
public const string DelayBeforePolling = nameof(DelayBeforePolling);
223-
public const string Polling = nameof(Polling);
224-
}
225-
226138
}
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
// ----------------------------------------------------------------------------------
2+
//
3+
// Copyright Microsoft Corporation
4+
// Licensed under the Apache License, Version 2.0 (the "License");
5+
// you may not use this file except in compliance with the License.
6+
// You may obtain a copy of the License at
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
// Unless required by applicable law or agreed to in writing, software
9+
// distributed under the License is distributed on an "AS IS" BASIS,
10+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11+
// See the License for the specific language governing permissions and
12+
// limitations under the License.
13+
// ----------------------------------------------------------------------------------
14+
15+
16+
using System;
17+
using System.Collections.Generic;
18+
using System.Net.Http;
19+
using System.Threading.Tasks;
20+
21+
22+
namespace Microsoft.Azure.Commands.Common
23+
{
24+
/// <summary>
25+
/// A PowerShell PSTypeConverter to adapt an <c>EventData</c> object that has been passed.
26+
/// Usually used between modules.
27+
/// </summary>
28+
public class EventDataConverter : System.Management.Automation.PSTypeConverter
29+
{
30+
public override bool CanConvertTo(object sourceValue, Type destinationType) => false;
31+
public override object ConvertTo(object sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase) => null;
32+
public override bool CanConvertFrom(dynamic sourceValue, Type destinationType) => destinationType == typeof(EventData) && CanConvertFrom(sourceValue);
33+
public override object ConvertFrom(dynamic sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue);
34+
35+
public static bool CanConvertFrom(dynamic sv)
36+
{
37+
var result = true;
38+
try
39+
{
40+
// check if this has required parameters...
41+
sv?.Id?.GetType();
42+
sv?.Message?.GetType();
43+
sv?.Parameter?.GetType();
44+
sv?.Value?.GetType();
45+
sv?.RequestMessage?.GetType();
46+
sv?.ResponseMessage?.GetType();
47+
sv?.Cancel?.GetType();
48+
}
49+
catch
50+
{
51+
return false;
52+
}
53+
return result;
54+
}
55+
56+
public static EventData ConvertFrom(dynamic sv)
57+
{
58+
try
59+
{
60+
return new EventData
61+
{
62+
Id = sv.Id,
63+
Message = sv.Message,
64+
Parameter = sv.Parameter,
65+
Value = sv.Value,
66+
RequestMessage = sv.RequestMessage,
67+
ResponseMessage = sv.ResponseMessage,
68+
Cancel = sv.Cancel
69+
};
70+
}
71+
catch
72+
{
73+
}
74+
return null;
75+
}
76+
}
77+
78+
}

0 commit comments

Comments
 (0)