/// <summary> /// Creates an Azure SQL Database Agent Target Group /// </summary> /// <param name="resourceGroupName">The resource group name</param> /// <param name="serverName">The server name</param> /// <param name="agentName">The agent name</param> /// <param name="targetGroupName">The target groups name</param> /// <param name="parameters">The target group's create parameters</param> /// <returns>The created target group</returns> public JobTargetGroup CreateOrUpdateTargetGroup( string resourceGroupName, string serverName, string agentName, string targetGroupName, JobTargetGroup parameters) { return(GetCurrentSqlClient().JobTargetGroups.CreateOrUpdate(resourceGroupName, serverName, agentName, targetGroupName, parameters)); }
/// <summary> /// Uperts a target group to the control database /// </summary> /// <param name="model">The target group model</param> /// <returns>The upserted target group model</returns> public AzureSqlElasticJobTargetGroupModel UpsertTargetGroup(AzureSqlElasticJobTargetGroupModel model) { var param = new JobTargetGroup { Members = model.Targets.Select((target) => CreateJobTargetModel(target)).ToList() }; var resp = Communicator.CreateOrUpdateTargetGroup(model.ResourceGroupName, model.ServerName, model.AgentName, model.TargetGroupName, param); return(CreateTargetGroupModelFromResponse(model.ResourceGroupName, model.ServerName, model.AgentName, resp)); }
public void TestStartStopGetJobExecution() { using (SqlManagementTestContext context = new SqlManagementTestContext(this)) { ResourceGroup resourceGroup = context.CreateResourceGroup(); Server server = context.CreateServer(resourceGroup); SqlManagementClient sqlClient = context.GetClient <SqlManagementClient>(); try { // Allow all conenctions for test sqlClient.FirewallRules.CreateOrUpdate(resourceGroup.Name, server.Name, "allowAll", new FirewallRule { StartIpAddress = "0.0.0.0", EndIpAddress = "255.255.255.255", }); // Create database only required parameters string dbName = SqlManagementTestUtilities.GenerateName(); var db1 = sqlClient.Databases.CreateOrUpdate(resourceGroup.Name, server.Name, dbName, new Database() { Location = server.Location, }); Assert.NotNull(db1); // Create agent string agentName = "agent"; JobAgent agent = sqlClient.JobAgents.CreateOrUpdate(resourceGroup.Name, server.Name, agentName, new JobAgent { Location = server.Location, DatabaseId = db1.Id }); // Create credential JobCredential credential = sqlClient.JobCredentials.CreateOrUpdate(resourceGroup.Name, server.Name, agent.Name, SqlManagementTestUtilities.DefaultLogin, new JobCredential { Username = SqlManagementTestUtilities.DefaultLogin, Password = SqlManagementTestUtilities.DefaultPassword }); // Create target group JobTargetGroup targetGroup = sqlClient.JobTargetGroups.CreateOrUpdate(resourceGroup.Name, server.Name, agent.Name, "tg1", new JobTargetGroup { Members = new List <JobTarget> { // server target new JobTarget { ServerName = server.Name, DatabaseName = db1.Name, Type = JobTargetType.SqlDatabase, MembershipType = JobTargetGroupMembershipType.Include, } } }); // Create job that runs once Job job1 = sqlClient.Jobs.CreateOrUpdate(resourceGroup.Name, server.Name, agent.Name, "job1", new Job { Description = "Test description", Schedule = new JobSchedule { Enabled = true, Type = JobScheduleType.Once, } }); // Create job step JobStep step1 = sqlClient.JobSteps.CreateOrUpdate(resourceGroup.Name, server.Name, agent.Name, job1.Name, "step1", new JobStep { Credential = credential.Id, Action = new JobStepAction { Value = "SELECT 1" }, TargetGroup = targetGroup.Id }); // Create job execution from job1 - do sync so we can be sure a step execution succeeds JobExecution jobExecution = sqlClient.JobExecutions.Create(resourceGroup.Name, server.Name, agent.Name, job1.Name); // List executions by agent sqlClient.JobExecutions.ListByAgent(resourceGroup.Name, server.Name, agent.Name); // List executions by job sqlClient.JobExecutions.ListByJob(resourceGroup.Name, server.Name, agent.Name, job1.Name); // Get root job execution jobExecution = sqlClient.JobExecutions.Get(resourceGroup.Name, server.Name, agent.Name, job1.Name, jobExecution.JobExecutionId.Value); // List step executions by root execution sqlClient.JobStepExecutions.ListByJobExecution(resourceGroup.Name, server.Name, agent.Name, job1.Name, jobExecution.JobExecutionId.Value); // Get step1 execution sqlClient.JobStepExecutions.Get(resourceGroup.Name, server.Name, agent.Name, job1.Name, jobExecution.JobExecutionId.Value, step1.Name); // List target executions by root job execution sqlClient.JobTargetExecutions.ListByJobExecution(resourceGroup.Name, server.Name, agent.Name, job1.Name, jobExecution.JobExecutionId.Value); // List target executions by job step IPage <JobExecution> targetStepExecutions = sqlClient.JobTargetExecutions.ListByStep(resourceGroup.Name, server.Name, agent.Name, job1.Name, jobExecution.JobExecutionId.Value, step1.Name); Assert.Single(targetStepExecutions); // Get target execution sqlClient.JobTargetExecutions.Get(resourceGroup.Name, server.Name, agent.Name, job1.Name, jobExecution.JobExecutionId.Value, step1.Name, Guid.Parse(targetStepExecutions.FirstOrDefault().Name)); // Cancel the job execution sqlClient.JobExecutions.Cancel(resourceGroup.Name, server.Name, agent.Name, job1.Name, jobExecution.JobExecutionId.Value); } finally { context.DeleteResourceGroup(resourceGroup.Name); } } }
public void TestCreateUpdateDropJobStep() { using (SqlManagementTestContext context = new SqlManagementTestContext(this)) { ResourceGroup resourceGroup = context.CreateResourceGroup(); Server server = context.CreateServer(resourceGroup); SqlManagementClient sqlClient = context.GetClient <SqlManagementClient>(); try { // Create database only required parameters string dbName = SqlManagementTestUtilities.GenerateName(); var db1 = sqlClient.Databases.CreateOrUpdate(resourceGroup.Name, server.Name, dbName, new Database() { Location = server.Location, }); Assert.NotNull(db1); // Create agent string agentName = "agent"; JobAgent agent = sqlClient.JobAgents.CreateOrUpdate(resourceGroup.Name, server.Name, agentName, new JobAgent { Location = server.Location, DatabaseId = db1.Id }); // Create credential JobCredential credential = sqlClient.JobCredentials.CreateOrUpdate(resourceGroup.Name, server.Name, agent.Name, SqlManagementTestUtilities.DefaultLogin, new JobCredential { Username = SqlManagementTestUtilities.DefaultLogin, Password = SqlManagementTestUtilities.DefaultPassword }); // Create target group JobTargetGroup targetGroup = sqlClient.JobTargetGroups.CreateOrUpdate(resourceGroup.Name, server.Name, agent.Name, "tg1", new JobTargetGroup { Members = new List <JobTarget> { // server target new JobTarget { ServerName = server.Name, Type = JobTargetType.SqlServer, RefreshCredential = credential.Id, MembershipType = JobTargetGroupMembershipType.Include, } } }); // Create job that runs once Job job1 = sqlClient.Jobs.CreateOrUpdate(resourceGroup.Name, server.Name, agent.Name, "job1", new Job { Description = "Test description", Schedule = new JobSchedule { Enabled = true, Type = JobScheduleType.Once, } }); // Create step with min params JobStep step1 = sqlClient.JobSteps.CreateOrUpdate(resourceGroup.Name, server.Name, agent.Name, job1.Name, "step1", new JobStep { Credential = credential.Id, Action = new JobStepAction { Value = "SELECT 1" }, TargetGroup = targetGroup.Id }); // Update step with max params step1 = sqlClient.JobSteps.CreateOrUpdate(resourceGroup.Name, server.Name, agent.Name, job1.Name, "step1", new JobStep { Credential = credential.Id, Action = new JobStepAction { Value = "SELECT 1", Source = "Inline", Type = "TSql" }, TargetGroup = targetGroup.Id, ExecutionOptions = new JobStepExecutionOptions { InitialRetryIntervalSeconds = 100, MaximumRetryIntervalSeconds = 1000, RetryAttempts = 1000, RetryIntervalBackoffMultiplier = 1.5, TimeoutSeconds = 10000 }, Output = new JobStepOutput { ResourceGroupName = "rg1", ServerName = "s1", DatabaseName = "db1", SchemaName = "dbo", TableName = "tbl", SubscriptionId = new Guid(), Credential = credential.Id, Type = JobStepOutputType.SqlDatabase } }); // List steps by job sqlClient.JobSteps.ListByJob(resourceGroup.Name, server.Name, agent.Name, job1.Name); // Delete job step sqlClient.JobSteps.Delete(resourceGroup.Name, server.Name, agent.Name, job1.Name, step1.Name); } finally { context.DeleteResourceGroup(resourceGroup.Name); } } }
public void TestCreateUpdateDropTargetGroup() { using (SqlManagementTestContext context = new SqlManagementTestContext(this)) { ResourceGroup resourceGroup = context.CreateResourceGroup(); Server server = context.CreateServer(resourceGroup); SqlManagementClient sqlClient = context.GetClient <SqlManagementClient>(); try { // Create database only required parameters string dbName = SqlManagementTestUtilities.GenerateName(); var db1 = sqlClient.Databases.CreateOrUpdate(resourceGroup.Name, server.Name, dbName, new Database() { Location = server.Location, }); Assert.NotNull(db1); // Create agent string agentName = "agent"; JobAgent agent = sqlClient.JobAgents.CreateOrUpdate(resourceGroup.Name, server.Name, agentName, new JobAgent { Location = server.Location, DatabaseId = db1.Id }); // Create credential JobCredential credential = sqlClient.JobCredentials.CreateOrUpdate(resourceGroup.Name, server.Name, agent.Name, SqlManagementTestUtilities.DefaultLogin, new JobCredential { Username = SqlManagementTestUtilities.DefaultLogin, Password = SqlManagementTestUtilities.DefaultPassword }); // Create target group JobTargetGroup targetGroup = sqlClient.JobTargetGroups.CreateOrUpdate(resourceGroup.Name, server.Name, agent.Name, "tg1", new JobTargetGroup { Members = new List <JobTarget> { // server target new JobTarget { ServerName = "s1", Type = JobTargetType.SqlServer, RefreshCredential = credential.Id, MembershipType = JobTargetGroupMembershipType.Include, } } }); // Update target group with each type of target targetGroup = sqlClient.JobTargetGroups.CreateOrUpdate(resourceGroup.Name, server.Name, agent.Name, "tg1", new JobTargetGroup { Members = new List <JobTarget> { // server target new JobTarget { ServerName = "s1", Type = JobTargetType.SqlServer, RefreshCredential = credential.Id, MembershipType = JobTargetGroupMembershipType.Include, }, // db target new JobTarget { DatabaseName = "db1", ServerName = "s1", Type = JobTargetType.SqlDatabase, MembershipType = JobTargetGroupMembershipType.Include, }, // shard map target new JobTarget { ShardMapName = "sm1", DatabaseName = "db1", ServerName = "s1", RefreshCredential = credential.Id, Type = JobTargetType.SqlShardMap, MembershipType = JobTargetGroupMembershipType.Exclude, }, // elastic pool target new JobTarget { ElasticPoolName = "ep1", ServerName = "s1", RefreshCredential = credential.Id, Type = JobTargetType.SqlElasticPool, MembershipType = JobTargetGroupMembershipType.Exclude, }, } }); // List target groups sqlClient.JobTargetGroups.ListByAgent(resourceGroup.Name, server.Name, agent.Name); // Delete target group sqlClient.JobTargetGroups.Delete(resourceGroup.Name, server.Name, agent.Name, targetGroup.Name); } finally { context.DeleteResourceGroup(resourceGroup.Name); } } }
/// <summary> /// Creates or updates a target group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='jobAgentName'> /// The name of the job agent. /// </param> /// <param name='targetGroupName'> /// The name of the target group. /// </param> /// <param name='parameters'> /// The requested state of the target group. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <AzureOperationResponse <JobTargetGroup> > CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serverName, string jobAgentName, string targetGroupName, JobTargetGroup parameters, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (serverName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "serverName"); } if (jobAgentName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "jobAgentName"); } if (targetGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "targetGroupName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-03-01-preview"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("jobAgentName", jobAgentName); tracingParameters.Add("targetGroupName", targetGroupName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/jobAgents/{jobAgentName}/targetGroups/{targetGroupName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{serverName}", System.Uri.EscapeDataString(serverName)); _url = _url.Replace("{jobAgentName}", System.Uri.EscapeDataString(jobAgentName)); _url = _url.Replace("{targetGroupName}", System.Uri.EscapeDataString(targetGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List <string> _queryParameters = new List <string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if (parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse <JobTargetGroup>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <JobTargetGroup>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <JobTargetGroup>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
/// <summary> /// Converts a JobTargetGroup model to an AzureSqlElasticJobTargetGroupModel /// </summary> /// <param name="resourceGroupName">The resource group name</param> /// <param name="serverName">The server name</param> /// <param name="agentName">The agent name</param> /// <param name="resp">The JobTargetGroup model</param> /// <returns></returns> private AzureSqlElasticJobTargetGroupModel CreateTargetGroupModelFromResponse(string resourceGroupName, string serverName, string agentName, JobTargetGroup resp) { AzureSqlElasticJobTargetGroupModel targetGroup = new AzureSqlElasticJobTargetGroupModel { ResourceGroupName = resourceGroupName, ServerName = serverName, AgentName = agentName, TargetGroupName = resp.Name, Targets = resp.Members.Select((target) => CreateAzureSqlElasticJobTargetModel(resourceGroupName, serverName, agentName, resp.Name, target)).ToList(), ResourceId = resp.Id, Type = resp.Type }; return(targetGroup); }
/// <summary> /// Creates or updates a target group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='jobAgentName'> /// The name of the job agent. /// </param> /// <param name='targetGroupName'> /// The name of the target group. /// </param> /// <param name='parameters'> /// The requested state of the target group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task <JobTargetGroup> CreateOrUpdateAsync(this IJobTargetGroupsOperations operations, string resourceGroupName, string serverName, string jobAgentName, string targetGroupName, JobTargetGroup parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, serverName, jobAgentName, targetGroupName, parameters, null, cancellationToken).ConfigureAwait(false)) { return(_result.Body); } }
/// <summary> /// Creates or updates a target group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='jobAgentName'> /// The name of the job agent. /// </param> /// <param name='targetGroupName'> /// The name of the target group. /// </param> /// <param name='parameters'> /// The requested state of the target group. /// </param> public static JobTargetGroup CreateOrUpdate(this IJobTargetGroupsOperations operations, string resourceGroupName, string serverName, string jobAgentName, string targetGroupName, JobTargetGroup parameters) { return(operations.CreateOrUpdateAsync(resourceGroupName, serverName, jobAgentName, targetGroupName, parameters).GetAwaiter().GetResult()); }