public Response <DecryptResult> Decrypt(EncryptionAlgorithm algorithm, byte[] ciphertext, byte[] iv = default, byte[] authenticationData = default, byte[] authenticationTag = default, CancellationToken cancellationToken = default) { var parameters = new KeyEncryptParameters() { Algorithm = algorithm, Value = ciphertext, Iv = iv, AuthenticationData = authenticationData, AuthenticationTag = authenticationTag }; using DiagnosticScope scope = Pipeline.CreateScope("Azure.Security.KeyVault.Keys.Cryptography.RemoteCryptographyClient.Decrypt"); scope.AddAttribute("key", _keyId); scope.Start(); try { return(Pipeline.SendRequest(RequestMethod.Post, parameters, () => new DecryptResult { Algorithm = algorithm }, cancellationToken, "/decrypt")); } catch (Exception e) { scope.Failed(e); throw; } }
/// <summary> /// Schedules a message to appear on Service Bus at a later time. /// </summary> /// /// <param name="message">The message to schedule.</param> /// <param name="scheduledEnqueueTime">The UTC time at which the message should be available for processing</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param> /// /// <remarks>Although the message will not be available to be received until the scheduledEnqueueTime, it can still be peeked before that time.</remarks> /// <returns>The sequence number of the message that was scheduled.</returns> public virtual async Task <long> ScheduleMessageAsync( ServiceBusMessage message, DateTimeOffset scheduledEnqueueTime, CancellationToken cancellationToken = default) { Argument.AssertNotNull(message, nameof(message)); Argument.AssertNotClosed(IsDisposed, nameof(ServiceBusSender)); cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); Logger.ScheduleMessageStart(Identifier, scheduledEnqueueTime.ToString(CultureInfo.InvariantCulture)); using DiagnosticScope scope = CreateDiagnosticScope( new ServiceBusMessage[] { message }, DiagnosticProperty.ScheduleActivityName); scope.Start(); long sequenceNumber; try { message.ScheduledEnqueueTime = scheduledEnqueueTime.UtcDateTime; sequenceNumber = await _innerSender.ScheduleMessageAsync(message, cancellationToken).ConfigureAwait(false); } catch (Exception exception) { Logger.ScheduleMessageException(Identifier, exception.ToString()); scope.Failed(exception); throw; } cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); Logger.ScheduleMessageComplete(Identifier); scope.AddAttribute(DiagnosticProperty.SequenceNumbersAttribute, sequenceNumber); return(sequenceNumber); }
/// <summary> /// Cancels a message that was scheduled. /// </summary> /// <param name="sequenceNumber">The <see cref="ServiceBusReceivedMessage.SequenceNumber"/> of the message to be cancelled.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param> public virtual async Task CancelScheduledMessageAsync( long sequenceNumber, CancellationToken cancellationToken = default) { Argument.AssertNotClosed(IsDisposed, nameof(ServiceBusSender)); cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); Logger.CancelScheduledMessageStart(Identifier, sequenceNumber); using DiagnosticScope scope = _scopeFactory.CreateScope( DiagnosticProperty.CancelActivityName, DiagnosticProperty.ClientKind); scope.AddAttribute(DiagnosticProperty.SequenceNumbersAttribute, sequenceNumber); scope.Start(); try { await _innerSender.CancelScheduledMessageAsync(sequenceNumber, cancellationToken).ConfigureAwait(false); } catch (Exception ex) { Logger.CancelScheduledMessageException(Identifier, ex.ToString()); throw; } cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); Logger.CancelScheduledMessageComplete(Identifier); }
/// <summary> /// Receives a <see cref="IList{Message}"/> of deferred messages identified by <paramref name="sequenceNumbers"/>. /// </summary> /// /// <param name="sequenceNumbers">An <see cref="IEnumerable{T}"/> containing the sequence numbers to receive.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param> /// /// <returns>Messages identified by sequence number are returned. Returns null if no messages are found. /// Throws if the messages have not been deferred.</returns> /// <seealso cref="DeferAsync(ServiceBusReceivedMessage, IDictionary{string, object}, CancellationToken)"/> /// <seealso cref="DeferAsync(string, IDictionary{string, object}, CancellationToken)"/> public virtual async Task <IList <ServiceBusReceivedMessage> > ReceiveDeferredMessageBatchAsync( IEnumerable <long> sequenceNumbers, CancellationToken cancellationToken = default) { Argument.AssertNotClosed(IsDisposed, nameof(ServiceBusReceiver)); Argument.AssertNotNullOrEmpty(sequenceNumbers, nameof(sequenceNumbers)); cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); var sequenceNumbersList = sequenceNumbers.ToList(); Logger.ReceiveDeferredMessageStart(Identifier, sequenceNumbersList.Count, sequenceNumbersList); using DiagnosticScope scope = _scopeFactory.CreateScope(DiagnosticProperty.ReceiveDeferredActivityName); scope.AddAttribute( DiagnosticProperty.SequenceNumbersAttribute, string.Join(",", sequenceNumbers)); scope.Start(); IList <ServiceBusReceivedMessage> deferredMessages = null; try { deferredMessages = await InnerReceiver.ReceiveDeferredMessageBatchAsync( sequenceNumbersList, cancellationToken).ConfigureAwait(false); } catch (Exception exception) { Logger.ReceiveDeferredMessageException(Identifier, exception.ToString()); scope.Failed(exception); throw; } Logger.ReceiveDeferredMessageComplete(Identifier, deferredMessages.Count); scope.SetMessageData(deferredMessages); return(deferredMessages); }
/// <summary> /// Renews the lock on the message. The lock will be renewed based on the setting specified on the queue. /// </summary> /// /// <remarks> /// When a message is received in <see cref="ReceiveMode.PeekLock"/> mode, the message is locked on the server for this /// receiver instance for a duration as specified during the Queue/Subscription creation (LockDuration). /// If processing of the message requires longer than this duration, the lock needs to be renewed. /// For each renewal, it resets the time the message is locked by the LockDuration set on the Entity. /// </remarks> /// /// <param name="lockToken">The lockToken of the <see cref="ServiceBusReceivedMessage"/> to renew the lock for.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param> public virtual async Task <DateTimeOffset> RenewMessageLockAsync( string lockToken, CancellationToken cancellationToken = default) { ThrowIfLockTokenIsEmpty(lockToken); Argument.AssertNotClosed(IsDisposed, nameof(ServiceBusReceiver)); ThrowIfNotPeekLockMode(); ThrowIfSessionReceiver(); cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>(); Logger.RenewMessageLockStart(Identifier, 1, lockToken); using DiagnosticScope scope = _scopeFactory.CreateScope( DiagnosticProperty.RenewMessageLockActivityName, lockToken: lockToken); scope.Start(); DateTimeOffset lockedUntil; try { lockedUntil = await InnerReceiver.RenewMessageLockAsync( lockToken, cancellationToken).ConfigureAwait(false); } catch (Exception exception) { Logger.RenewMessageLockException(Identifier, exception.ToString()); scope.Failed(exception); throw; } Logger.RenewMessageLockComplete(Identifier); scope.AddAttribute(DiagnosticProperty.LockedUntilAttribute, lockedUntil); return(lockedUntil); }
/// <summary> /// Retrieve an existing <see cref="ConfigurationSetting"/> from the configuration store. /// </summary> /// <param name="key">The primary identifier of a configuration setting.</param> /// <param name="label">The value used to group configuration settings.</param> /// <param name="acceptDateTime">The setting will be retrieved exactly as it existed at the provided time.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> public virtual Response <ConfigurationSetting> Get(string key, string label = default, DateTimeOffset acceptDateTime = default, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _pipeline.Diagnostics.CreateScope("Azure.ApplicationModel.Configuration.ConfigurationClient.Get"); scope.AddAttribute(nameof(key), key); scope.Start(); try { using (Request request = CreateGetRequest(key, label, acceptDateTime)) { Response response = _pipeline.SendRequest(request, cancellationToken); switch (response.Status) { case 200: return(CreateResponse(response)); default: throw response.CreateRequestFailedException(); } } } catch (Exception e) { scope.Failed(e); throw; } }
/// <summary> /// Retrieve an existing <see cref="ConfigurationSetting"/> from the configuration store. /// </summary> /// <param name="key">The primary identifier of a configuration setting.</param> /// <param name="label">The value used to group configuration settings.</param> /// <param name="acceptDateTime">The setting will be retrieved exactly as it existed at the provided time.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> public virtual async Task <Response <ConfigurationSetting> > GetAsync(string key, string label = default, DateTimeOffset acceptDateTime = default, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _pipeline.Diagnostics.CreateScope("Azure.ApplicationModel.Configuration.ConfigurationClient.Get"); scope.AddAttribute("key", key); scope.Start(); try { using Request request = CreateGetRequest(key, label, acceptDateTime); Response response = await _pipeline.SendRequestAsync(request, cancellationToken).ConfigureAwait(false); switch (response.Status) { case 200: return(await CreateResponseAsync(response, cancellationToken).ConfigureAwait(false)); default: throw await response.CreateRequestFailedExceptionAsync().ConfigureAwait(false); } } catch (Exception e) { scope.Failed(e); throw; } }
/// <summary> /// Deletes an existing <see cref="ConfigurationSetting"/> in the configuration store. /// </summary> /// <param name="key">The primary identifier of a configuration setting.</param> /// <param name="label">The value used to group configuration settings.</param> /// <param name="etag">The value of an etag indicates the state of a configuration setting within a configuration store. /// If it is specified, the configuration setting is only deleted if etag value matches etag value in the configuration store. /// If no etag value is passed in, then the setting is always deleted.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> public virtual Response Delete(string key, string label = default, ETag etag = default, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _pipeline.Diagnostics.CreateScope("Azure.ApplicationModel.Configuration.ConfigurationClient.Delete"); scope.AddAttribute("key", key); scope.Start(); try { using Request request = CreateDeleteRequest(key, label, etag); Response response = _pipeline.SendRequest(request, cancellationToken); switch (response.Status) { case 200: case 204: return(response); default: throw response.CreateRequestFailedException(); } } catch (Exception e) { scope.Failed(e); throw; } }
/// <summary> /// Updates an existing <see cref="ConfigurationSetting"/> in the configuration store. /// </summary> /// <param name="setting"><see cref="ConfigurationSetting"/> to update.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> public virtual Response <ConfigurationSetting> Update(ConfigurationSetting setting, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _pipeline.Diagnostics.CreateScope("Azure.ApplicationModel.Configuration.ConfigurationClient.Update"); scope.AddAttribute("key", setting?.Key); scope.Start(); try { using Request request = CreateUpdateRequest(setting); Response response = _pipeline.SendRequest(request, cancellationToken); switch (response.Status) { case 200: return(CreateResponse(response)); default: throw response.CreateRequestFailedException(); } } catch (Exception e) { scope.Failed(e); throw; } }
/// <summary> /// Creates a <see cref="ConfigurationSetting"/> if it doesn't exist or overrides an existing setting in the configuration store. /// </summary> /// <param name="setting"><see cref="ConfigurationSetting"/> to create.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> public virtual async Task <Response <ConfigurationSetting> > SetAsync(ConfigurationSetting setting, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _pipeline.Diagnostics.CreateScope("Azure.ApplicationModel.Configuration.ConfigurationClient.Set"); scope.AddAttribute("key", setting?.Key); scope.Start(); try { using Request request = CreateSetRequest(setting); Response response = await _pipeline.SendRequestAsync(request, cancellationToken).ConfigureAwait(false); switch (response.Status) { case 200: return(await CreateResponseAsync(response, cancellationToken).ConfigureAwait(false)); case 409: throw await response.CreateRequestFailedExceptionAsync("The setting is locked").ConfigureAwait(false); default: throw await response.CreateRequestFailedExceptionAsync().ConfigureAwait(false); } } catch (Exception e) { scope.Failed(e); throw; } }
/// <summary> /// Get a specified secret from a given key vault. /// </summary> /// <remarks> /// The get operation is applicable to any secret stored in Azure Key Vault. /// This operation requires the secrets/get permission. /// </remarks> /// <param name="name">The name of the secret.</param> /// <param name="version">The version of the secret.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="ArgumentException"><paramref name="name"/> is an empty string.</exception> /// <exception cref="ArgumentNullException"><paramref name="name"/> is null.</exception> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual async Task <Response <KeyVaultSecret> > GetSecretAsync(string name, string version = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(name, nameof(name)); using DiagnosticScope scope = _pipeline.CreateScope($"{nameof(SecretClient)}.{nameof(GetSecret)}"); scope.AddAttribute("secret", name); scope.AddAttribute("version", version); scope.Start(); try { return(await _pipeline.SendRequestAsync(RequestMethod.Get, () => new KeyVaultSecret(), cancellationToken, SecretsPath, name, "/", version).ConfigureAwait(false)); } catch (Exception e) { scope.Failed(e); throw; } }
/// <summary> /// Updates the attributes associated with a specified secret. /// </summary> /// <remarks> /// The update operation changes specified attributes of an existing stored /// secret. Attributes that are not specified in the request are left /// unchanged. The value of a secret itself cannot be changed. This operation /// requires the secrets/set permission. /// </remarks> /// <param name="properties">The secret object with updated properties.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> controlling the request lifetime.</param> /// <exception cref="ArgumentNullException"><paramref name="properties"/> or <see cref="SecretProperties.Version"/> is null.</exception> /// <exception cref="RequestFailedException">The server returned an error. See <see cref="Exception.Message"/> for details returned from the server.</exception> public virtual Response <SecretProperties> UpdateSecretProperties(SecretProperties properties, CancellationToken cancellationToken = default) { Argument.AssertNotNull(properties, nameof(properties)); Argument.AssertNotNull(properties.Version, nameof(properties.Version)); using DiagnosticScope scope = _pipeline.CreateScope($"{nameof(SecretClient)}.{nameof(UpdateSecretProperties)}"); scope.AddAttribute("secret", properties.Name); scope.AddAttribute("version", properties.Version); scope.Start(); try { return(_pipeline.SendRequest(RequestMethod.Patch, properties, () => new SecretProperties(), cancellationToken, SecretsPath, properties.Name, "/", properties.Version)); } catch (Exception e) { scope.Failed(e); throw; } }
/// <summary> /// Applies diagnostics instrumentation to a given event. /// </summary> /// /// <param name="eventData">The event to instrument.</param> /// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace to use for instrumentation.</param> /// <param name="eventHubName">The name of the specific Event Hub to associate the event with.</param> /// /// <returns><c>true</c> if the event was instrumented in response to this request; otherwise, <c>false</c>.</returns> /// public static bool InstrumentEvent(EventData eventData, string fullyQualifiedNamespace, string eventHubName) { if (!eventData.Properties.ContainsKey(DiagnosticProperty.DiagnosticIdAttribute)) { using DiagnosticScope messageScope = ScopeFactory.CreateScope(DiagnosticProperty.EventActivityName, DiagnosticScope.ActivityKind.Producer); messageScope.AddAttribute(DiagnosticProperty.EventHubAttribute, eventHubName); messageScope.AddAttribute(DiagnosticProperty.EndpointAttribute, fullyQualifiedNamespace); messageScope.Start(); Activity activity = Activity.Current; if (activity != null) { eventData.Properties[DiagnosticProperty.DiagnosticIdAttribute] = activity.Id; return(true); } } return(false); }
/// <summary>Analyzes a conversational utterance.</summary> /// <param name="utterance">The conversation utterance to be analyzed.</param> /// <param name="project">The <see cref="ConversationsProject"/> used for conversation analysis.</param> /// <param name="options">Optional <see cref="AnalyzeConversationOptions"/> with additional query options.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> to cancel the request.</param> /// <exception cref="ArgumentException"><paramref name="utterance"/> is an empty string.</exception> /// <exception cref="ArgumentNullException"><paramref name="utterance"/> or <paramref name="project"/> or is null.</exception> /// <exception cref="RequestFailedException">The service returned an error. The exception contains details of the service error.</exception> public virtual async Task <Response <AnalyzeConversationTaskResult> > AnalyzeConversationAsync(string utterance, ConversationsProject project, AnalyzeConversationOptions options = null, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(utterance, nameof(utterance)); Argument.AssertNotNull(project, nameof(project)); CustomConversationTaskParameters customConversationTaskParameters = new CustomConversationTaskParameters(project.ProjectName, project.DeploymentName) { Verbose = options?.Verbose, }; TextConversationItem textConversationItem = new TextConversationItem("1", "1", utterance); options ??= new AnalyzeConversationOptions(textConversationItem); CustomConversationalTask customConversationalTask = new CustomConversationalTask(options, customConversationTaskParameters); using DiagnosticScope scope = ClientDiagnostics.CreateScope($"{nameof(ConversationAnalysisClient)}.{nameof(AnalyzeConversation)}External"); scope.AddAttribute("projectName", project.ProjectName); scope.AddAttribute("deploymentName", project.DeploymentName); scope.Start(); try { Utf8JsonRequestContent content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(customConversationalTask); Response response = await AnalyzeConversationAsync(content, new RequestContext() { CancellationToken = cancellationToken }).ConfigureAwait(false); switch (response.Status) { case 200: { AnalyzeConversationTaskResult value = default; using JsonDocument document = await JsonDocument.ParseAsync(response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = AnalyzeConversationTaskResult.DeserializeAnalyzeConversationTaskResult(document.RootElement); return(Response.FromValue(value, response)); }