public void GetBatchCertificateODataTest() { // Setup cmdlet to get a single certificate BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.ThumbprintAlgorithm = "sha1"; cmdlet.Thumbprint = "123456789"; cmdlet.Select = "thumbprint,state"; string requestSelect = null; // Fetch the OData clauses off the request. The OData clauses are applied after user provided RequestInterceptors, so a ResponseInterceptor is used. CertificateGetResponse getResponse = BatchTestHelpers.CreateCertificateGetResponse(cmdlet.Thumbprint); RequestInterceptor requestInterceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor <CertificateGetParameters, CertificateGetResponse>(getResponse); ResponseInterceptor responseInterceptor = new ResponseInterceptor((response, request) => { requestSelect = request.Parameters.DetailLevel.SelectClause; return(Task.FromResult(response)); }); cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>() { requestInterceptor, responseInterceptor }; cmdlet.ExecuteCmdlet(); Assert.Equal(cmdlet.Select, requestSelect); }
public void GetBatchCertificateTest() { // Setup cmdlet to get a cert by its thumbprint BatchAccountContext context = BatchTestHelpers.CreateBatchContextWithKeys(); cmdlet.BatchContext = context; cmdlet.ThumbprintAlgorithm = "sha1"; cmdlet.Thumbprint = "123456789"; cmdlet.Filter = null; // Build a Certificate instead of querying the service on a Get Certificate call CertificateGetResponse response = BatchTestHelpers.CreateCertificateGetResponse(cmdlet.Thumbprint); RequestInterceptor interceptor = BatchTestHelpers.CreateFakeServiceResponseInterceptor <CertificateGetParameters, CertificateGetResponse>(response); cmdlet.AdditionalBehaviors = new List <BatchClientBehavior>() { interceptor }; // Setup the cmdlet to write pipeline output to a list that can be examined later List <PSCertificate> pipeline = new List <PSCertificate>(); commandRuntimeMock.Setup(r => r.WriteObject(It.IsAny <PSCertificate>())).Callback <object>(c => pipeline.Add((PSCertificate)c)); cmdlet.ExecuteCmdlet(); // Verify that the cmdlet wrote the cert returned from the OM to the pipeline Assert.Equal(1, pipeline.Count); Assert.Equal(cmdlet.Thumbprint, pipeline[0].Thumbprint); }
/// <summary> /// Gets specific certificate. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='certificateId'> /// Required. Identifier of the certificate. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Get Certificate operation response details. /// </returns> public async Task <CertificateGetResponse> GetAsync(string resourceGroupName, string serviceName, string certificateId, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serviceName == null) { throw new ArgumentNullException("serviceName"); } if (certificateId == null) { throw new ArgumentNullException("certificateId"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("certificateId", certificateId); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.ApiManagement"; url = url + "/service/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/certificates/"; url = url + Uri.EscapeDataString(certificateId); List <string> queryParameters = new List <string>(); queryParameters.Add("api-version=2016-07-07"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result CertificateGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new CertificateGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { CertificateContract valueInstance = new CertificateContract(); result.Value = valueInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); valueInstance.IdPath = idInstance; } JToken subjectValue = responseDoc["subject"]; if (subjectValue != null && subjectValue.Type != JTokenType.Null) { string subjectInstance = ((string)subjectValue); valueInstance.Subject = subjectInstance; } JToken thumbprintValue = responseDoc["thumbprint"]; if (thumbprintValue != null && thumbprintValue.Type != JTokenType.Null) { string thumbprintInstance = ((string)thumbprintValue); valueInstance.Thumbprint = thumbprintInstance; } JToken expirationDateValue = responseDoc["expirationDate"]; if (expirationDateValue != null && expirationDateValue.Type != JTokenType.Null) { DateTime expirationDateInstance = ((DateTime)expirationDateValue); valueInstance.ExpirationDate = expirationDateInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("ETag")) { result.ETag = httpResponse.Headers.GetValues("ETag").FirstOrDefault(); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return(result); } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } }
/// <summary> /// Returns if the asset exists locally or in the cloud /// </summary> /// <param name="assetName"></param> /// <param name="assetType"></param> /// <param name="localWorkspacePath"></param> /// <param name="automationApi"></param> /// <param name="resourceGroupName"></param> /// <param name="automationAccountName"></param> /// <param name="encryptionCertThumbprint"></param> /// <returns>null if the asset does not exist or else returns the asset</returns> public static async Task <AutomationAsset> GetAsset(String assetName, String assetType, String localWorkspacePath, AutomationManagementClient automationApi, string resourceGroupName, string automationAccountName, string encryptionCertThumbprint, ICollection <ConnectionType> connectionTypes) { AutomationAsset automationAsset = null; // Get local assets LocalAssets localAssets = LocalAssetsStore.Get(localWorkspacePath, encryptionCertThumbprint, connectionTypes); // Search for variables CancellationTokenSource cts = new CancellationTokenSource(); cts.CancelAfter(TIMEOUT_MS); if (assetType == Constants.AssetType.Variable) { // Check local asset store first var localVariable = localAssets.Variables.Find(asset => asset.Name == assetName); if (localVariable != null) { automationAsset = new AutomationVariable(localVariable); } else { try { // Check cloud. Catch exception if it doesn't exist VariableGetResponse cloudVariable = await automationApi.Variables.GetAsync(resourceGroupName, automationAccountName, assetName, cts.Token); automationAsset = new AutomationVariable(cloudVariable.Variable); } catch (Exception e) { // If the exception is not found, don't throw new exception as this is expected if (e.HResult != -2146233088) { throw e; } } } } // Search for credentials else if (assetType == Constants.AssetType.Credential) { // Check local asset store first var localCredential = localAssets.PSCredentials.Find(asset => asset.Name == assetName); if (localCredential != null) { automationAsset = new AutomationCredential(localCredential); } else { try { // Check cloud. Catch execption if it doesn't exist CredentialGetResponse cloudVariable = await automationApi.PsCredentials.GetAsync(resourceGroupName, automationAccountName, assetName, cts.Token); automationAsset = new AutomationCredential(cloudVariable.Credential); } catch (Exception e) { // If the exception is not found, don't throw new exception as this is expected if (e.HResult != -2146233088) { throw e; } } } } // Search for connections else if (assetType == Constants.AssetType.Connection) { // Check local asset store first var localConnection = localAssets.Connections.Find(asset => asset.Name == assetName); if (localConnection != null) { automationAsset = new AutomationConnection(localConnection); } else { try { // Check cloud. Catch exception if it doesn't exist ConnectionGetResponse cloudConnection = await automationApi.Connections.GetAsync(resourceGroupName, automationAccountName, assetName, cts.Token); cts = new CancellationTokenSource(); cts.CancelAfter(TIMEOUT_MS); ConnectionTypeGetResponse connectionType = await automationApi.ConnectionTypes.GetAsync(resourceGroupName, automationAccountName, cloudConnection.Connection.Properties.ConnectionType.Name, cts.Token); automationAsset = new AutomationConnection(cloudConnection.Connection, connectionType.ConnectionType); } catch (Exception e) { // If the exception is not found, don't throw new exception as this is expected if (e.HResult != -2146233088) { throw e; } } } } // Search for certificates else if (assetType == Constants.AssetType.Certificate) { // Check local asset store first var localCertificate = localAssets.Certificate.Find(asset => asset.Name == assetName); if (localCertificate != null) { automationAsset = new AutomationCertificate(localCertificate); } else { try { // Check cloud. Catch execption if it doesn't exist CertificateGetResponse cloudCertificate = await automationApi.Certificates.GetAsync(resourceGroupName, automationAccountName, assetName, cts.Token); automationAsset = new AutomationCertificate(cloudCertificate.Certificate); } catch (Exception e) { // If the exception is not found, don't throw new exception as this is expected if (e.HResult != -2146233088) { throw e; } } } } return(automationAsset); }