/*
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for
 * license information.
 *
 * Code generated by Microsoft (R) AutoRest Code Generator.
 * Changes may cause incorrect behavior and will be lost if the code is
 * regenerated.
 */

'use strict';

const msRest = require('ms-rest');
const msRestAzure = require('ms-rest-azure');
const WebResource = msRest.WebResource;

/**
 * Lists all executions in a job agent.
 *
 * @param {string} 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 {string} serverName The name of the server.
 *
 * @param {string} jobAgentName The name of the job agent.
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {date} [options.createTimeMin] If specified, only job executions
 * created at or after the specified time are included.
 *
 * @param {date} [options.createTimeMax] If specified, only job executions
 * created before the specified time are included.
 *
 * @param {date} [options.endTimeMin] If specified, only job executions
 * completed at or after the specified time are included.
 *
 * @param {date} [options.endTimeMax] If specified, only job executions
 * completed before the specified time are included.
 *
 * @param {boolean} [options.isActive] If specified, only active or only
 * completed job executions are included.
 *
 * @param {number} [options.skip] The number of elements in the collection to
 * skip.
 *
 * @param {number} [options.top] The number of elements to return from the
 * collection.
 *
 * @param {object} [options.customHeaders] Headers that will be added to the
 * request
 *
 * @param {function} callback - The callback.
 *
 * @returns {function} callback(err, result, request, response)
 *
 *                      {Error}  err        - The Error object if an error occurred, null otherwise.
 *
 *                      {object} [result]   - The deserialized result object if an error did not occur.
 *                      See {@link JobExecutionListResult} for more
 *                      information.
 *
 *                      {object} [request]  - The HTTP Request object if an error did not occur.
 *
 *                      {stream} [response] - The HTTP Response stream if an error did not occur.
 */
function _listByAgent(resourceGroupName, serverName, jobAgentName, options, callback) {
   /* jshint validthis: true */
  let client = this.client;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }
  if (!callback) {
    throw new Error('callback cannot be null.');
  }
  let createTimeMin = (options && options.createTimeMin !== undefined) ? options.createTimeMin : undefined;
  let createTimeMax = (options && options.createTimeMax !== undefined) ? options.createTimeMax : undefined;
  let endTimeMin = (options && options.endTimeMin !== undefined) ? options.endTimeMin : undefined;
  let endTimeMax = (options && options.endTimeMax !== undefined) ? options.endTimeMax : undefined;
  let isActive = (options && options.isActive !== undefined) ? options.isActive : undefined;
  let skip = (options && options.skip !== undefined) ? options.skip : undefined;
  let top = (options && options.top !== undefined) ? options.top : undefined;
  let apiVersion = '2017-03-01-preview';
  // Validate
  try {
    if (resourceGroupName === null || resourceGroupName === undefined || typeof resourceGroupName.valueOf() !== 'string') {
      throw new Error('resourceGroupName cannot be null or undefined and it must be of type string.');
    }
    if (serverName === null || serverName === undefined || typeof serverName.valueOf() !== 'string') {
      throw new Error('serverName cannot be null or undefined and it must be of type string.');
    }
    if (jobAgentName === null || jobAgentName === undefined || typeof jobAgentName.valueOf() !== 'string') {
      throw new Error('jobAgentName cannot be null or undefined and it must be of type string.');
    }
    if (createTimeMin && !(createTimeMin instanceof Date ||
        (typeof createTimeMin.valueOf() === 'string' && !isNaN(Date.parse(createTimeMin))))) {
          throw new Error('createTimeMin must be of type date.');
        }
    if (createTimeMax && !(createTimeMax instanceof Date ||
        (typeof createTimeMax.valueOf() === 'string' && !isNaN(Date.parse(createTimeMax))))) {
          throw new Error('createTimeMax must be of type date.');
        }
    if (endTimeMin && !(endTimeMin instanceof Date ||
        (typeof endTimeMin.valueOf() === 'string' && !isNaN(Date.parse(endTimeMin))))) {
          throw new Error('endTimeMin must be of type date.');
        }
    if (endTimeMax && !(endTimeMax instanceof Date ||
        (typeof endTimeMax.valueOf() === 'string' && !isNaN(Date.parse(endTimeMax))))) {
          throw new Error('endTimeMax must be of type date.');
        }
    if (isActive !== null && isActive !== undefined && typeof isActive !== 'boolean') {
      throw new Error('isActive must be of type boolean.');
    }
    if (skip !== null && skip !== undefined && typeof skip !== 'number') {
      throw new Error('skip must be of type number.');
    }
    if (top !== null && top !== undefined && typeof top !== 'number') {
      throw new Error('top must be of type number.');
    }
    if (this.client.subscriptionId === null || this.client.subscriptionId === undefined || typeof this.client.subscriptionId.valueOf() !== 'string') {
      throw new Error('this.client.subscriptionId cannot be null or undefined and it must be of type string.');
    }
    if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
      throw new Error('this.client.acceptLanguage must be of type string.');
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  let baseUrl = this.client.baseUri;
  let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/jobAgents/{jobAgentName}/executions';
  requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
  requestUrl = requestUrl.replace('{serverName}', encodeURIComponent(serverName));
  requestUrl = requestUrl.replace('{jobAgentName}', encodeURIComponent(jobAgentName));
  requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId));
  let queryParameters = [];
  if (createTimeMin !== null && createTimeMin !== undefined) {
    queryParameters.push('createTimeMin=' + encodeURIComponent(client.serializeObject(createTimeMin)));
  }
  if (createTimeMax !== null && createTimeMax !== undefined) {
    queryParameters.push('createTimeMax=' + encodeURIComponent(client.serializeObject(createTimeMax)));
  }
  if (endTimeMin !== null && endTimeMin !== undefined) {
    queryParameters.push('endTimeMin=' + encodeURIComponent(client.serializeObject(endTimeMin)));
  }
  if (endTimeMax !== null && endTimeMax !== undefined) {
    queryParameters.push('endTimeMax=' + encodeURIComponent(client.serializeObject(endTimeMax)));
  }
  if (isActive !== null && isActive !== undefined) {
    queryParameters.push('isActive=' + encodeURIComponent(isActive.toString()));
  }
  if (skip !== null && skip !== undefined) {
    queryParameters.push('$skip=' + encodeURIComponent(skip.toString()));
  }
  if (top !== null && top !== undefined) {
    queryParameters.push('$top=' + encodeURIComponent(top.toString()));
  }
  queryParameters.push('api-version=' + encodeURIComponent(apiVersion));
  if (queryParameters.length > 0) {
    requestUrl += '?' + queryParameters.join('&');
  }

  // Create HTTP transport objects
  let httpRequest = new WebResource();
  httpRequest.method = 'GET';
  httpRequest.url = requestUrl;
  httpRequest.headers = {};
  // Set Headers
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  if (this.client.generateClientRequestId) {
      httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
  }
  if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
    httpRequest.headers['accept-language'] = this.client.acceptLanguage;
  }
  if(options) {
    for(let headerName in options['customHeaders']) {
      if (options['customHeaders'].hasOwnProperty(headerName)) {
        httpRequest.headers[headerName] = options['customHeaders'][headerName];
      }
    }
  }
  httpRequest.body = null;
  // Send Request
  return client.pipeline(httpRequest, (err, response, responseBody) => {
    if (err) {
      return callback(err);
    }
    let statusCode = response.statusCode;
    if (statusCode !== 200) {
      let error = new Error(responseBody);
      error.statusCode = response.statusCode;
      error.request = msRest.stripRequest(httpRequest);
      error.response = msRest.stripResponse(response);
      if (responseBody === '') responseBody = null;
      let parsedErrorResponse;
      try {
        parsedErrorResponse = JSON.parse(responseBody);
        if (parsedErrorResponse) {
          if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
          if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
          if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          let resultMapper = new client.models['CloudError']().mapper();
          error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
        }
      } catch (defaultError) {
        error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
                         `- "${responseBody}" for the default response.`;
        return callback(error);
      }
      return callback(error);
    }
    // Create Result
    let result = null;
    if (responseBody === '') responseBody = null;
    // Deserialize Response
    if (statusCode === 200) {
      let parsedResponse = null;
      try {
        parsedResponse = JSON.parse(responseBody);
        result = JSON.parse(responseBody);
        if (parsedResponse !== null && parsedResponse !== undefined) {
          let resultMapper = new client.models['JobExecutionListResult']().mapper();
          result = client.deserialize(resultMapper, parsedResponse, 'result');
        }
      } catch (error) {
        let deserializationError = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`);
        deserializationError.request = msRest.stripRequest(httpRequest);
        deserializationError.response = msRest.stripResponse(response);
        return callback(deserializationError);
      }
    }

    return callback(null, result, httpRequest, response);
  });
}

/**
 * Requests cancellation of a job execution.
 *
 * @param {string} 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 {string} serverName The name of the server.
 *
 * @param {string} jobAgentName The name of the job agent.
 *
 * @param {string} jobName The name of the job.
 *
 * @param {uuid} jobExecutionId The id of the job execution to cancel.
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {object} [options.customHeaders] Headers that will be added to the
 * request
 *
 * @param {function} callback - The callback.
 *
 * @returns {function} callback(err, result, request, response)
 *
 *                      {Error}  err        - The Error object if an error occurred, null otherwise.
 *
 *                      {null} [result]   - The deserialized result object if an error did not occur.
 *
 *                      {object} [request]  - The HTTP Request object if an error did not occur.
 *
 *                      {stream} [response] - The HTTP Response stream if an error did not occur.
 */
function _cancel(resourceGroupName, serverName, jobAgentName, jobName, jobExecutionId, options, callback) {
   /* jshint validthis: true */
  let client = this.client;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }
  if (!callback) {
    throw new Error('callback cannot be null.');
  }
  let apiVersion = '2017-03-01-preview';
  // Validate
  try {
    if (resourceGroupName === null || resourceGroupName === undefined || typeof resourceGroupName.valueOf() !== 'string') {
      throw new Error('resourceGroupName cannot be null or undefined and it must be of type string.');
    }
    if (serverName === null || serverName === undefined || typeof serverName.valueOf() !== 'string') {
      throw new Error('serverName cannot be null or undefined and it must be of type string.');
    }
    if (jobAgentName === null || jobAgentName === undefined || typeof jobAgentName.valueOf() !== 'string') {
      throw new Error('jobAgentName cannot be null or undefined and it must be of type string.');
    }
    if (jobName === null || jobName === undefined || typeof jobName.valueOf() !== 'string') {
      throw new Error('jobName cannot be null or undefined and it must be of type string.');
    }
    if (jobExecutionId === null || jobExecutionId === undefined || typeof jobExecutionId.valueOf() !== 'string' || !msRest.isValidUuid(jobExecutionId)) {
      throw new Error('jobExecutionId cannot be null or undefined and it must be of type string and must be a valid uuid.');
    }
    if (this.client.subscriptionId === null || this.client.subscriptionId === undefined || typeof this.client.subscriptionId.valueOf() !== 'string') {
      throw new Error('this.client.subscriptionId cannot be null or undefined and it must be of type string.');
    }
    if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
      throw new Error('this.client.acceptLanguage must be of type string.');
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  let baseUrl = this.client.baseUri;
  let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/jobAgents/{jobAgentName}/jobs/{jobName}/executions/{jobExecutionId}/cancel';
  requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
  requestUrl = requestUrl.replace('{serverName}', encodeURIComponent(serverName));
  requestUrl = requestUrl.replace('{jobAgentName}', encodeURIComponent(jobAgentName));
  requestUrl = requestUrl.replace('{jobName}', encodeURIComponent(jobName));
  requestUrl = requestUrl.replace('{jobExecutionId}', encodeURIComponent(jobExecutionId.toString()));
  requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId));
  let queryParameters = [];
  queryParameters.push('api-version=' + encodeURIComponent(apiVersion));
  if (queryParameters.length > 0) {
    requestUrl += '?' + queryParameters.join('&');
  }

  // Create HTTP transport objects
  let httpRequest = new WebResource();
  httpRequest.method = 'POST';
  httpRequest.url = requestUrl;
  httpRequest.headers = {};
  // Set Headers
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  if (this.client.generateClientRequestId) {
      httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
  }
  if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
    httpRequest.headers['accept-language'] = this.client.acceptLanguage;
  }
  if(options) {
    for(let headerName in options['customHeaders']) {
      if (options['customHeaders'].hasOwnProperty(headerName)) {
        httpRequest.headers[headerName] = options['customHeaders'][headerName];
      }
    }
  }
  httpRequest.body = null;
  // Send Request
  return client.pipeline(httpRequest, (err, response, responseBody) => {
    if (err) {
      return callback(err);
    }
    let statusCode = response.statusCode;
    if (statusCode !== 200) {
      let error = new Error(responseBody);
      error.statusCode = response.statusCode;
      error.request = msRest.stripRequest(httpRequest);
      error.response = msRest.stripResponse(response);
      if (responseBody === '') responseBody = null;
      let parsedErrorResponse;
      try {
        parsedErrorResponse = JSON.parse(responseBody);
        if (parsedErrorResponse) {
          if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
          if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
          if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          let resultMapper = new client.models['CloudError']().mapper();
          error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
        }
      } catch (defaultError) {
        error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
                         `- "${responseBody}" for the default response.`;
        return callback(error);
      }
      return callback(error);
    }
    // Create Result
    let result = null;
    if (responseBody === '') responseBody = null;

    return callback(null, result, httpRequest, response);
  });
}


/**
 * Starts an elastic job execution.
 *
 * @param {string} 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 {string} serverName The name of the server.
 *
 * @param {string} jobAgentName The name of the job agent.
 *
 * @param {string} jobName The name of the job to get.
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {object} [options.customHeaders] Headers that will be added to the
 * request
 *
 * @param {function} callback - The callback.
 *
 * @returns {function} callback(err, result, request, response)
 *
 *                      {Error}  err        - The Error object if an error occurred, null otherwise.
 *
 *                      {object} [result]   - The deserialized result object if an error did not occur.
 *                      See {@link JobExecution} for more information.
 *
 *                      {object} [request]  - The HTTP Request object if an error did not occur.
 *
 *                      {stream} [response] - The HTTP Response stream if an error did not occur.
 */
function _create(resourceGroupName, serverName, jobAgentName, jobName, options, callback) {
   /* jshint validthis: true */
  let client = this.client;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }

  if (!callback) {
    throw new Error('callback cannot be null.');
  }

  // Send request
  this.beginCreate(resourceGroupName, serverName, jobAgentName, jobName, options, (err, parsedResult, httpRequest, response) => {
    if (err) return callback(err);

    let initialResult = new msRest.HttpOperationResponse();
    initialResult.request = httpRequest;
    initialResult.response = response;
    initialResult.body = response.body;
    client.getLongRunningOperationResult(initialResult, options, (err, pollingResult) => {
      if (err) return callback(err);

      // Create Result
      let result = null;

      httpRequest = pollingResult.request;
      response = pollingResult.response;
      let responseBody = pollingResult.body;
      if (responseBody === '') responseBody = null;

      // Deserialize Response
      let parsedResponse = null;
      try {
        parsedResponse = JSON.parse(responseBody);
        result = JSON.parse(responseBody);
        if (parsedResponse !== null && parsedResponse !== undefined) {
          let resultMapper = new client.models['JobExecution']().mapper();
          result = client.deserialize(resultMapper, parsedResponse, 'result');
        }
      } catch (error) {
        let deserializationError = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`);
        deserializationError.request = msRest.stripRequest(httpRequest);
        deserializationError.response = msRest.stripResponse(response);
        return callback(deserializationError);
      }

      return callback(null, result, httpRequest, response);
    });
  });
}

/**
 * Lists a job's executions.
 *
 * @param {string} 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 {string} serverName The name of the server.
 *
 * @param {string} jobAgentName The name of the job agent.
 *
 * @param {string} jobName The name of the job to get.
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {date} [options.createTimeMin] If specified, only job executions
 * created at or after the specified time are included.
 *
 * @param {date} [options.createTimeMax] If specified, only job executions
 * created before the specified time are included.
 *
 * @param {date} [options.endTimeMin] If specified, only job executions
 * completed at or after the specified time are included.
 *
 * @param {date} [options.endTimeMax] If specified, only job executions
 * completed before the specified time are included.
 *
 * @param {boolean} [options.isActive] If specified, only active or only
 * completed job executions are included.
 *
 * @param {number} [options.skip] The number of elements in the collection to
 * skip.
 *
 * @param {number} [options.top] The number of elements to return from the
 * collection.
 *
 * @param {object} [options.customHeaders] Headers that will be added to the
 * request
 *
 * @param {function} callback - The callback.
 *
 * @returns {function} callback(err, result, request, response)
 *
 *                      {Error}  err        - The Error object if an error occurred, null otherwise.
 *
 *                      {object} [result]   - The deserialized result object if an error did not occur.
 *                      See {@link JobExecutionListResult} for more
 *                      information.
 *
 *                      {object} [request]  - The HTTP Request object if an error did not occur.
 *
 *                      {stream} [response] - The HTTP Response stream if an error did not occur.
 */
function _listByJob(resourceGroupName, serverName, jobAgentName, jobName, options, callback) {
   /* jshint validthis: true */
  let client = this.client;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }
  if (!callback) {
    throw new Error('callback cannot be null.');
  }
  let createTimeMin = (options && options.createTimeMin !== undefined) ? options.createTimeMin : undefined;
  let createTimeMax = (options && options.createTimeMax !== undefined) ? options.createTimeMax : undefined;
  let endTimeMin = (options && options.endTimeMin !== undefined) ? options.endTimeMin : undefined;
  let endTimeMax = (options && options.endTimeMax !== undefined) ? options.endTimeMax : undefined;
  let isActive = (options && options.isActive !== undefined) ? options.isActive : undefined;
  let skip = (options && options.skip !== undefined) ? options.skip : undefined;
  let top = (options && options.top !== undefined) ? options.top : undefined;
  let apiVersion = '2017-03-01-preview';
  // Validate
  try {
    if (resourceGroupName === null || resourceGroupName === undefined || typeof resourceGroupName.valueOf() !== 'string') {
      throw new Error('resourceGroupName cannot be null or undefined and it must be of type string.');
    }
    if (serverName === null || serverName === undefined || typeof serverName.valueOf() !== 'string') {
      throw new Error('serverName cannot be null or undefined and it must be of type string.');
    }
    if (jobAgentName === null || jobAgentName === undefined || typeof jobAgentName.valueOf() !== 'string') {
      throw new Error('jobAgentName cannot be null or undefined and it must be of type string.');
    }
    if (jobName === null || jobName === undefined || typeof jobName.valueOf() !== 'string') {
      throw new Error('jobName cannot be null or undefined and it must be of type string.');
    }
    if (createTimeMin && !(createTimeMin instanceof Date ||
        (typeof createTimeMin.valueOf() === 'string' && !isNaN(Date.parse(createTimeMin))))) {
          throw new Error('createTimeMin must be of type date.');
        }
    if (createTimeMax && !(createTimeMax instanceof Date ||
        (typeof createTimeMax.valueOf() === 'string' && !isNaN(Date.parse(createTimeMax))))) {
          throw new Error('createTimeMax must be of type date.');
        }
    if (endTimeMin && !(endTimeMin instanceof Date ||
        (typeof endTimeMin.valueOf() === 'string' && !isNaN(Date.parse(endTimeMin))))) {
          throw new Error('endTimeMin must be of type date.');
        }
    if (endTimeMax && !(endTimeMax instanceof Date ||
        (typeof endTimeMax.valueOf() === 'string' && !isNaN(Date.parse(endTimeMax))))) {
          throw new Error('endTimeMax must be of type date.');
        }
    if (isActive !== null && isActive !== undefined && typeof isActive !== 'boolean') {
      throw new Error('isActive must be of type boolean.');
    }
    if (skip !== null && skip !== undefined && typeof skip !== 'number') {
      throw new Error('skip must be of type number.');
    }
    if (top !== null && top !== undefined && typeof top !== 'number') {
      throw new Error('top must be of type number.');
    }
    if (this.client.subscriptionId === null || this.client.subscriptionId === undefined || typeof this.client.subscriptionId.valueOf() !== 'string') {
      throw new Error('this.client.subscriptionId cannot be null or undefined and it must be of type string.');
    }
    if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
      throw new Error('this.client.acceptLanguage must be of type string.');
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  let baseUrl = this.client.baseUri;
  let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/jobAgents/{jobAgentName}/jobs/{jobName}/executions';
  requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
  requestUrl = requestUrl.replace('{serverName}', encodeURIComponent(serverName));
  requestUrl = requestUrl.replace('{jobAgentName}', encodeURIComponent(jobAgentName));
  requestUrl = requestUrl.replace('{jobName}', encodeURIComponent(jobName));
  requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId));
  let queryParameters = [];
  if (createTimeMin !== null && createTimeMin !== undefined) {
    queryParameters.push('createTimeMin=' + encodeURIComponent(client.serializeObject(createTimeMin)));
  }
  if (createTimeMax !== null && createTimeMax !== undefined) {
    queryParameters.push('createTimeMax=' + encodeURIComponent(client.serializeObject(createTimeMax)));
  }
  if (endTimeMin !== null && endTimeMin !== undefined) {
    queryParameters.push('endTimeMin=' + encodeURIComponent(client.serializeObject(endTimeMin)));
  }
  if (endTimeMax !== null && endTimeMax !== undefined) {
    queryParameters.push('endTimeMax=' + encodeURIComponent(client.serializeObject(endTimeMax)));
  }
  if (isActive !== null && isActive !== undefined) {
    queryParameters.push('isActive=' + encodeURIComponent(isActive.toString()));
  }
  if (skip !== null && skip !== undefined) {
    queryParameters.push('$skip=' + encodeURIComponent(skip.toString()));
  }
  if (top !== null && top !== undefined) {
    queryParameters.push('$top=' + encodeURIComponent(top.toString()));
  }
  queryParameters.push('api-version=' + encodeURIComponent(apiVersion));
  if (queryParameters.length > 0) {
    requestUrl += '?' + queryParameters.join('&');
  }

  // Create HTTP transport objects
  let httpRequest = new WebResource();
  httpRequest.method = 'GET';
  httpRequest.url = requestUrl;
  httpRequest.headers = {};
  // Set Headers
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  if (this.client.generateClientRequestId) {
      httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
  }
  if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
    httpRequest.headers['accept-language'] = this.client.acceptLanguage;
  }
  if(options) {
    for(let headerName in options['customHeaders']) {
      if (options['customHeaders'].hasOwnProperty(headerName)) {
        httpRequest.headers[headerName] = options['customHeaders'][headerName];
      }
    }
  }
  httpRequest.body = null;
  // Send Request
  return client.pipeline(httpRequest, (err, response, responseBody) => {
    if (err) {
      return callback(err);
    }
    let statusCode = response.statusCode;
    if (statusCode !== 200) {
      let error = new Error(responseBody);
      error.statusCode = response.statusCode;
      error.request = msRest.stripRequest(httpRequest);
      error.response = msRest.stripResponse(response);
      if (responseBody === '') responseBody = null;
      let parsedErrorResponse;
      try {
        parsedErrorResponse = JSON.parse(responseBody);
        if (parsedErrorResponse) {
          if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
          if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
          if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          let resultMapper = new client.models['CloudError']().mapper();
          error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
        }
      } catch (defaultError) {
        error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
                         `- "${responseBody}" for the default response.`;
        return callback(error);
      }
      return callback(error);
    }
    // Create Result
    let result = null;
    if (responseBody === '') responseBody = null;
    // Deserialize Response
    if (statusCode === 200) {
      let parsedResponse = null;
      try {
        parsedResponse = JSON.parse(responseBody);
        result = JSON.parse(responseBody);
        if (parsedResponse !== null && parsedResponse !== undefined) {
          let resultMapper = new client.models['JobExecutionListResult']().mapper();
          result = client.deserialize(resultMapper, parsedResponse, 'result');
        }
      } catch (error) {
        let deserializationError = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`);
        deserializationError.request = msRest.stripRequest(httpRequest);
        deserializationError.response = msRest.stripResponse(response);
        return callback(deserializationError);
      }
    }

    return callback(null, result, httpRequest, response);
  });
}

/**
 * Gets a job execution.
 *
 * @param {string} 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 {string} serverName The name of the server.
 *
 * @param {string} jobAgentName The name of the job agent.
 *
 * @param {string} jobName The name of the job.
 *
 * @param {uuid} jobExecutionId The id of the job execution
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {object} [options.customHeaders] Headers that will be added to the
 * request
 *
 * @param {function} callback - The callback.
 *
 * @returns {function} callback(err, result, request, response)
 *
 *                      {Error}  err        - The Error object if an error occurred, null otherwise.
 *
 *                      {object} [result]   - The deserialized result object if an error did not occur.
 *                      See {@link JobExecution} for more information.
 *
 *                      {object} [request]  - The HTTP Request object if an error did not occur.
 *
 *                      {stream} [response] - The HTTP Response stream if an error did not occur.
 */
function _get(resourceGroupName, serverName, jobAgentName, jobName, jobExecutionId, options, callback) {
   /* jshint validthis: true */
  let client = this.client;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }
  if (!callback) {
    throw new Error('callback cannot be null.');
  }
  let apiVersion = '2017-03-01-preview';
  // Validate
  try {
    if (resourceGroupName === null || resourceGroupName === undefined || typeof resourceGroupName.valueOf() !== 'string') {
      throw new Error('resourceGroupName cannot be null or undefined and it must be of type string.');
    }
    if (serverName === null || serverName === undefined || typeof serverName.valueOf() !== 'string') {
      throw new Error('serverName cannot be null or undefined and it must be of type string.');
    }
    if (jobAgentName === null || jobAgentName === undefined || typeof jobAgentName.valueOf() !== 'string') {
      throw new Error('jobAgentName cannot be null or undefined and it must be of type string.');
    }
    if (jobName === null || jobName === undefined || typeof jobName.valueOf() !== 'string') {
      throw new Error('jobName cannot be null or undefined and it must be of type string.');
    }
    if (jobExecutionId === null || jobExecutionId === undefined || typeof jobExecutionId.valueOf() !== 'string' || !msRest.isValidUuid(jobExecutionId)) {
      throw new Error('jobExecutionId cannot be null or undefined and it must be of type string and must be a valid uuid.');
    }
    if (this.client.subscriptionId === null || this.client.subscriptionId === undefined || typeof this.client.subscriptionId.valueOf() !== 'string') {
      throw new Error('this.client.subscriptionId cannot be null or undefined and it must be of type string.');
    }
    if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
      throw new Error('this.client.acceptLanguage must be of type string.');
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  let baseUrl = this.client.baseUri;
  let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/jobAgents/{jobAgentName}/jobs/{jobName}/executions/{jobExecutionId}';
  requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
  requestUrl = requestUrl.replace('{serverName}', encodeURIComponent(serverName));
  requestUrl = requestUrl.replace('{jobAgentName}', encodeURIComponent(jobAgentName));
  requestUrl = requestUrl.replace('{jobName}', encodeURIComponent(jobName));
  requestUrl = requestUrl.replace('{jobExecutionId}', encodeURIComponent(jobExecutionId.toString()));
  requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId));
  let queryParameters = [];
  queryParameters.push('api-version=' + encodeURIComponent(apiVersion));
  if (queryParameters.length > 0) {
    requestUrl += '?' + queryParameters.join('&');
  }

  // Create HTTP transport objects
  let httpRequest = new WebResource();
  httpRequest.method = 'GET';
  httpRequest.url = requestUrl;
  httpRequest.headers = {};
  // Set Headers
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  if (this.client.generateClientRequestId) {
      httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
  }
  if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
    httpRequest.headers['accept-language'] = this.client.acceptLanguage;
  }
  if(options) {
    for(let headerName in options['customHeaders']) {
      if (options['customHeaders'].hasOwnProperty(headerName)) {
        httpRequest.headers[headerName] = options['customHeaders'][headerName];
      }
    }
  }
  httpRequest.body = null;
  // Send Request
  return client.pipeline(httpRequest, (err, response, responseBody) => {
    if (err) {
      return callback(err);
    }
    let statusCode = response.statusCode;
    if (statusCode !== 200) {
      let error = new Error(responseBody);
      error.statusCode = response.statusCode;
      error.request = msRest.stripRequest(httpRequest);
      error.response = msRest.stripResponse(response);
      if (responseBody === '') responseBody = null;
      let parsedErrorResponse;
      try {
        parsedErrorResponse = JSON.parse(responseBody);
        if (parsedErrorResponse) {
          if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
          if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
          if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          let resultMapper = new client.models['CloudError']().mapper();
          error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
        }
      } catch (defaultError) {
        error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
                         `- "${responseBody}" for the default response.`;
        return callback(error);
      }
      return callback(error);
    }
    // Create Result
    let result = null;
    if (responseBody === '') responseBody = null;
    // Deserialize Response
    if (statusCode === 200) {
      let parsedResponse = null;
      try {
        parsedResponse = JSON.parse(responseBody);
        result = JSON.parse(responseBody);
        if (parsedResponse !== null && parsedResponse !== undefined) {
          let resultMapper = new client.models['JobExecution']().mapper();
          result = client.deserialize(resultMapper, parsedResponse, 'result');
        }
      } catch (error) {
        let deserializationError = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`);
        deserializationError.request = msRest.stripRequest(httpRequest);
        deserializationError.response = msRest.stripResponse(response);
        return callback(deserializationError);
      }
    }

    return callback(null, result, httpRequest, response);
  });
}


/**
 * Creates or updates a job execution.
 *
 * @param {string} 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 {string} serverName The name of the server.
 *
 * @param {string} jobAgentName The name of the job agent.
 *
 * @param {string} jobName The name of the job to get.
 *
 * @param {uuid} jobExecutionId The job execution id to create the job
 * execution under.
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {object} [options.customHeaders] Headers that will be added to the
 * request
 *
 * @param {function} callback - The callback.
 *
 * @returns {function} callback(err, result, request, response)
 *
 *                      {Error}  err        - The Error object if an error occurred, null otherwise.
 *
 *                      {object} [result]   - The deserialized result object if an error did not occur.
 *                      See {@link JobExecution} for more information.
 *
 *                      {object} [request]  - The HTTP Request object if an error did not occur.
 *
 *                      {stream} [response] - The HTTP Response stream if an error did not occur.
 */
function _createOrUpdate(resourceGroupName, serverName, jobAgentName, jobName, jobExecutionId, options, callback) {
   /* jshint validthis: true */
  let client = this.client;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }

  if (!callback) {
    throw new Error('callback cannot be null.');
  }

  // Send request
  this.beginCreateOrUpdate(resourceGroupName, serverName, jobAgentName, jobName, jobExecutionId, options, (err, parsedResult, httpRequest, response) => {
    if (err) return callback(err);

    let initialResult = new msRest.HttpOperationResponse();
    initialResult.request = httpRequest;
    initialResult.response = response;
    initialResult.body = response.body;
    client.getLongRunningOperationResult(initialResult, options, (err, pollingResult) => {
      if (err) return callback(err);

      // Create Result
      let result = null;

      httpRequest = pollingResult.request;
      response = pollingResult.response;
      let responseBody = pollingResult.body;
      if (responseBody === '') responseBody = null;

      // Deserialize Response
      let parsedResponse = null;
      try {
        parsedResponse = JSON.parse(responseBody);
        result = JSON.parse(responseBody);
        if (parsedResponse !== null && parsedResponse !== undefined) {
          let resultMapper = new client.models['JobExecution']().mapper();
          result = client.deserialize(resultMapper, parsedResponse, 'result');
        }
      } catch (error) {
        let deserializationError = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`);
        deserializationError.request = msRest.stripRequest(httpRequest);
        deserializationError.response = msRest.stripResponse(response);
        return callback(deserializationError);
      }

      return callback(null, result, httpRequest, response);
    });
  });
}

/**
 * Starts an elastic job execution.
 *
 * @param {string} 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 {string} serverName The name of the server.
 *
 * @param {string} jobAgentName The name of the job agent.
 *
 * @param {string} jobName The name of the job to get.
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {object} [options.customHeaders] Headers that will be added to the
 * request
 *
 * @param {function} callback - The callback.
 *
 * @returns {function} callback(err, result, request, response)
 *
 *                      {Error}  err        - The Error object if an error occurred, null otherwise.
 *
 *                      {object} [result]   - The deserialized result object if an error did not occur.
 *                      See {@link JobExecution} for more information.
 *
 *                      {object} [request]  - The HTTP Request object if an error did not occur.
 *
 *                      {stream} [response] - The HTTP Response stream if an error did not occur.
 */
function _beginCreate(resourceGroupName, serverName, jobAgentName, jobName, options, callback) {
   /* jshint validthis: true */
  let client = this.client;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }
  if (!callback) {
    throw new Error('callback cannot be null.');
  }
  let apiVersion = '2017-03-01-preview';
  // Validate
  try {
    if (resourceGroupName === null || resourceGroupName === undefined || typeof resourceGroupName.valueOf() !== 'string') {
      throw new Error('resourceGroupName cannot be null or undefined and it must be of type string.');
    }
    if (serverName === null || serverName === undefined || typeof serverName.valueOf() !== 'string') {
      throw new Error('serverName cannot be null or undefined and it must be of type string.');
    }
    if (jobAgentName === null || jobAgentName === undefined || typeof jobAgentName.valueOf() !== 'string') {
      throw new Error('jobAgentName cannot be null or undefined and it must be of type string.');
    }
    if (jobName === null || jobName === undefined || typeof jobName.valueOf() !== 'string') {
      throw new Error('jobName cannot be null or undefined and it must be of type string.');
    }
    if (this.client.subscriptionId === null || this.client.subscriptionId === undefined || typeof this.client.subscriptionId.valueOf() !== 'string') {
      throw new Error('this.client.subscriptionId cannot be null or undefined and it must be of type string.');
    }
    if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
      throw new Error('this.client.acceptLanguage must be of type string.');
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  let baseUrl = this.client.baseUri;
  let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/jobAgents/{jobAgentName}/jobs/{jobName}/start';
  requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
  requestUrl = requestUrl.replace('{serverName}', encodeURIComponent(serverName));
  requestUrl = requestUrl.replace('{jobAgentName}', encodeURIComponent(jobAgentName));
  requestUrl = requestUrl.replace('{jobName}', encodeURIComponent(jobName));
  requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId));
  let queryParameters = [];
  queryParameters.push('api-version=' + encodeURIComponent(apiVersion));
  if (queryParameters.length > 0) {
    requestUrl += '?' + queryParameters.join('&');
  }

  // Create HTTP transport objects
  let httpRequest = new WebResource();
  httpRequest.method = 'POST';
  httpRequest.url = requestUrl;
  httpRequest.headers = {};
  // Set Headers
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  if (this.client.generateClientRequestId) {
      httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
  }
  if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
    httpRequest.headers['accept-language'] = this.client.acceptLanguage;
  }
  if(options) {
    for(let headerName in options['customHeaders']) {
      if (options['customHeaders'].hasOwnProperty(headerName)) {
        httpRequest.headers[headerName] = options['customHeaders'][headerName];
      }
    }
  }
  httpRequest.body = null;
  // Send Request
  return client.pipeline(httpRequest, (err, response, responseBody) => {
    if (err) {
      return callback(err);
    }
    let statusCode = response.statusCode;
    if (statusCode !== 200 && statusCode !== 202) {
      let error = new Error(responseBody);
      error.statusCode = response.statusCode;
      error.request = msRest.stripRequest(httpRequest);
      error.response = msRest.stripResponse(response);
      if (responseBody === '') responseBody = null;
      let parsedErrorResponse;
      try {
        parsedErrorResponse = JSON.parse(responseBody);
        if (parsedErrorResponse) {
          if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
          if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
          if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          let resultMapper = new client.models['CloudError']().mapper();
          error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
        }
      } catch (defaultError) {
        error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
                         `- "${responseBody}" for the default response.`;
        return callback(error);
      }
      return callback(error);
    }
    // Create Result
    let result = null;
    if (responseBody === '') responseBody = null;
    // Deserialize Response
    if (statusCode === 200) {
      let parsedResponse = null;
      try {
        parsedResponse = JSON.parse(responseBody);
        result = JSON.parse(responseBody);
        if (parsedResponse !== null && parsedResponse !== undefined) {
          let resultMapper = new client.models['JobExecution']().mapper();
          result = client.deserialize(resultMapper, parsedResponse, 'result');
        }
      } catch (error) {
        let deserializationError = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`);
        deserializationError.request = msRest.stripRequest(httpRequest);
        deserializationError.response = msRest.stripResponse(response);
        return callback(deserializationError);
      }
    }

    return callback(null, result, httpRequest, response);
  });
}

/**
 * Creates or updates a job execution.
 *
 * @param {string} 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 {string} serverName The name of the server.
 *
 * @param {string} jobAgentName The name of the job agent.
 *
 * @param {string} jobName The name of the job to get.
 *
 * @param {uuid} jobExecutionId The job execution id to create the job
 * execution under.
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {object} [options.customHeaders] Headers that will be added to the
 * request
 *
 * @param {function} callback - The callback.
 *
 * @returns {function} callback(err, result, request, response)
 *
 *                      {Error}  err        - The Error object if an error occurred, null otherwise.
 *
 *                      {object} [result]   - The deserialized result object if an error did not occur.
 *                      See {@link JobExecution} for more information.
 *
 *                      {object} [request]  - The HTTP Request object if an error did not occur.
 *
 *                      {stream} [response] - The HTTP Response stream if an error did not occur.
 */
function _beginCreateOrUpdate(resourceGroupName, serverName, jobAgentName, jobName, jobExecutionId, options, callback) {
   /* jshint validthis: true */
  let client = this.client;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }
  if (!callback) {
    throw new Error('callback cannot be null.');
  }
  let apiVersion = '2017-03-01-preview';
  // Validate
  try {
    if (resourceGroupName === null || resourceGroupName === undefined || typeof resourceGroupName.valueOf() !== 'string') {
      throw new Error('resourceGroupName cannot be null or undefined and it must be of type string.');
    }
    if (serverName === null || serverName === undefined || typeof serverName.valueOf() !== 'string') {
      throw new Error('serverName cannot be null or undefined and it must be of type string.');
    }
    if (jobAgentName === null || jobAgentName === undefined || typeof jobAgentName.valueOf() !== 'string') {
      throw new Error('jobAgentName cannot be null or undefined and it must be of type string.');
    }
    if (jobName === null || jobName === undefined || typeof jobName.valueOf() !== 'string') {
      throw new Error('jobName cannot be null or undefined and it must be of type string.');
    }
    if (jobExecutionId === null || jobExecutionId === undefined || typeof jobExecutionId.valueOf() !== 'string' || !msRest.isValidUuid(jobExecutionId)) {
      throw new Error('jobExecutionId cannot be null or undefined and it must be of type string and must be a valid uuid.');
    }
    if (this.client.subscriptionId === null || this.client.subscriptionId === undefined || typeof this.client.subscriptionId.valueOf() !== 'string') {
      throw new Error('this.client.subscriptionId cannot be null or undefined and it must be of type string.');
    }
    if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
      throw new Error('this.client.acceptLanguage must be of type string.');
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  let baseUrl = this.client.baseUri;
  let requestUrl = baseUrl + (baseUrl.endsWith('/') ? '' : '/') + 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/jobAgents/{jobAgentName}/jobs/{jobName}/executions/{jobExecutionId}';
  requestUrl = requestUrl.replace('{resourceGroupName}', encodeURIComponent(resourceGroupName));
  requestUrl = requestUrl.replace('{serverName}', encodeURIComponent(serverName));
  requestUrl = requestUrl.replace('{jobAgentName}', encodeURIComponent(jobAgentName));
  requestUrl = requestUrl.replace('{jobName}', encodeURIComponent(jobName));
  requestUrl = requestUrl.replace('{jobExecutionId}', encodeURIComponent(jobExecutionId.toString()));
  requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId));
  let queryParameters = [];
  queryParameters.push('api-version=' + encodeURIComponent(apiVersion));
  if (queryParameters.length > 0) {
    requestUrl += '?' + queryParameters.join('&');
  }

  // Create HTTP transport objects
  let httpRequest = new WebResource();
  httpRequest.method = 'PUT';
  httpRequest.url = requestUrl;
  httpRequest.headers = {};
  // Set Headers
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  if (this.client.generateClientRequestId) {
      httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
  }
  if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
    httpRequest.headers['accept-language'] = this.client.acceptLanguage;
  }
  if(options) {
    for(let headerName in options['customHeaders']) {
      if (options['customHeaders'].hasOwnProperty(headerName)) {
        httpRequest.headers[headerName] = options['customHeaders'][headerName];
      }
    }
  }
  httpRequest.body = null;
  // Send Request
  return client.pipeline(httpRequest, (err, response, responseBody) => {
    if (err) {
      return callback(err);
    }
    let statusCode = response.statusCode;
    if (statusCode !== 200 && statusCode !== 201 && statusCode !== 202) {
      let error = new Error(responseBody);
      error.statusCode = response.statusCode;
      error.request = msRest.stripRequest(httpRequest);
      error.response = msRest.stripResponse(response);
      if (responseBody === '') responseBody = null;
      let parsedErrorResponse;
      try {
        parsedErrorResponse = JSON.parse(responseBody);
        if (parsedErrorResponse) {
          if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
          if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
          if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          let resultMapper = new client.models['CloudError']().mapper();
          error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
        }
      } catch (defaultError) {
        error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
                         `- "${responseBody}" for the default response.`;
        return callback(error);
      }
      return callback(error);
    }
    // Create Result
    let result = null;
    if (responseBody === '') responseBody = null;
    // Deserialize Response
    if (statusCode === 200) {
      let parsedResponse = null;
      try {
        parsedResponse = JSON.parse(responseBody);
        result = JSON.parse(responseBody);
        if (parsedResponse !== null && parsedResponse !== undefined) {
          let resultMapper = new client.models['JobExecution']().mapper();
          result = client.deserialize(resultMapper, parsedResponse, 'result');
        }
      } catch (error) {
        let deserializationError = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`);
        deserializationError.request = msRest.stripRequest(httpRequest);
        deserializationError.response = msRest.stripResponse(response);
        return callback(deserializationError);
      }
    }
    // Deserialize Response
    if (statusCode === 201) {
      let parsedResponse = null;
      try {
        parsedResponse = JSON.parse(responseBody);
        result = JSON.parse(responseBody);
        if (parsedResponse !== null && parsedResponse !== undefined) {
          let resultMapper = new client.models['JobExecution']().mapper();
          result = client.deserialize(resultMapper, parsedResponse, 'result');
        }
      } catch (error) {
        let deserializationError1 = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`);
        deserializationError1.request = msRest.stripRequest(httpRequest);
        deserializationError1.response = msRest.stripResponse(response);
        return callback(deserializationError1);
      }
    }

    return callback(null, result, httpRequest, response);
  });
}

/**
 * Lists all executions in a job agent.
 *
 * @param {string} nextPageLink The NextLink from the previous successful call
 * to List operation.
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {object} [options.customHeaders] Headers that will be added to the
 * request
 *
 * @param {function} callback - The callback.
 *
 * @returns {function} callback(err, result, request, response)
 *
 *                      {Error}  err        - The Error object if an error occurred, null otherwise.
 *
 *                      {object} [result]   - The deserialized result object if an error did not occur.
 *                      See {@link JobExecutionListResult} for more
 *                      information.
 *
 *                      {object} [request]  - The HTTP Request object if an error did not occur.
 *
 *                      {stream} [response] - The HTTP Response stream if an error did not occur.
 */
function _listByAgentNext(nextPageLink, options, callback) {
   /* jshint validthis: true */
  let client = this.client;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }
  if (!callback) {
    throw new Error('callback cannot be null.');
  }
  // Validate
  try {
    if (nextPageLink === null || nextPageLink === undefined || typeof nextPageLink.valueOf() !== 'string') {
      throw new Error('nextPageLink cannot be null or undefined and it must be of type string.');
    }
    if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
      throw new Error('this.client.acceptLanguage must be of type string.');
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  let requestUrl = '{nextLink}';
  requestUrl = requestUrl.replace('{nextLink}', nextPageLink);

  // Create HTTP transport objects
  let httpRequest = new WebResource();
  httpRequest.method = 'GET';
  httpRequest.url = requestUrl;
  httpRequest.headers = {};
  // Set Headers
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  if (this.client.generateClientRequestId) {
      httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
  }
  if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
    httpRequest.headers['accept-language'] = this.client.acceptLanguage;
  }
  if(options) {
    for(let headerName in options['customHeaders']) {
      if (options['customHeaders'].hasOwnProperty(headerName)) {
        httpRequest.headers[headerName] = options['customHeaders'][headerName];
      }
    }
  }
  httpRequest.body = null;
  // Send Request
  return client.pipeline(httpRequest, (err, response, responseBody) => {
    if (err) {
      return callback(err);
    }
    let statusCode = response.statusCode;
    if (statusCode !== 200) {
      let error = new Error(responseBody);
      error.statusCode = response.statusCode;
      error.request = msRest.stripRequest(httpRequest);
      error.response = msRest.stripResponse(response);
      if (responseBody === '') responseBody = null;
      let parsedErrorResponse;
      try {
        parsedErrorResponse = JSON.parse(responseBody);
        if (parsedErrorResponse) {
          if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
          if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
          if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          let resultMapper = new client.models['CloudError']().mapper();
          error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
        }
      } catch (defaultError) {
        error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
                         `- "${responseBody}" for the default response.`;
        return callback(error);
      }
      return callback(error);
    }
    // Create Result
    let result = null;
    if (responseBody === '') responseBody = null;
    // Deserialize Response
    if (statusCode === 200) {
      let parsedResponse = null;
      try {
        parsedResponse = JSON.parse(responseBody);
        result = JSON.parse(responseBody);
        if (parsedResponse !== null && parsedResponse !== undefined) {
          let resultMapper = new client.models['JobExecutionListResult']().mapper();
          result = client.deserialize(resultMapper, parsedResponse, 'result');
        }
      } catch (error) {
        let deserializationError = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`);
        deserializationError.request = msRest.stripRequest(httpRequest);
        deserializationError.response = msRest.stripResponse(response);
        return callback(deserializationError);
      }
    }

    return callback(null, result, httpRequest, response);
  });
}

/**
 * Lists a job's executions.
 *
 * @param {string} nextPageLink The NextLink from the previous successful call
 * to List operation.
 *
 * @param {object} [options] Optional Parameters.
 *
 * @param {object} [options.customHeaders] Headers that will be added to the
 * request
 *
 * @param {function} callback - The callback.
 *
 * @returns {function} callback(err, result, request, response)
 *
 *                      {Error}  err        - The Error object if an error occurred, null otherwise.
 *
 *                      {object} [result]   - The deserialized result object if an error did not occur.
 *                      See {@link JobExecutionListResult} for more
 *                      information.
 *
 *                      {object} [request]  - The HTTP Request object if an error did not occur.
 *
 *                      {stream} [response] - The HTTP Response stream if an error did not occur.
 */
function _listByJobNext(nextPageLink, options, callback) {
   /* jshint validthis: true */
  let client = this.client;
  if(!callback && typeof options === 'function') {
    callback = options;
    options = null;
  }
  if (!callback) {
    throw new Error('callback cannot be null.');
  }
  // Validate
  try {
    if (nextPageLink === null || nextPageLink === undefined || typeof nextPageLink.valueOf() !== 'string') {
      throw new Error('nextPageLink cannot be null or undefined and it must be of type string.');
    }
    if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') {
      throw new Error('this.client.acceptLanguage must be of type string.');
    }
  } catch (error) {
    return callback(error);
  }

  // Construct URL
  let requestUrl = '{nextLink}';
  requestUrl = requestUrl.replace('{nextLink}', nextPageLink);

  // Create HTTP transport objects
  let httpRequest = new WebResource();
  httpRequest.method = 'GET';
  httpRequest.url = requestUrl;
  httpRequest.headers = {};
  // Set Headers
  httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8';
  if (this.client.generateClientRequestId) {
      httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid();
  }
  if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) {
    httpRequest.headers['accept-language'] = this.client.acceptLanguage;
  }
  if(options) {
    for(let headerName in options['customHeaders']) {
      if (options['customHeaders'].hasOwnProperty(headerName)) {
        httpRequest.headers[headerName] = options['customHeaders'][headerName];
      }
    }
  }
  httpRequest.body = null;
  // Send Request
  return client.pipeline(httpRequest, (err, response, responseBody) => {
    if (err) {
      return callback(err);
    }
    let statusCode = response.statusCode;
    if (statusCode !== 200) {
      let error = new Error(responseBody);
      error.statusCode = response.statusCode;
      error.request = msRest.stripRequest(httpRequest);
      error.response = msRest.stripResponse(response);
      if (responseBody === '') responseBody = null;
      let parsedErrorResponse;
      try {
        parsedErrorResponse = JSON.parse(responseBody);
        if (parsedErrorResponse) {
          if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error;
          if (parsedErrorResponse.code) error.code = parsedErrorResponse.code;
          if (parsedErrorResponse.message) error.message = parsedErrorResponse.message;
        }
        if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) {
          let resultMapper = new client.models['CloudError']().mapper();
          error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body');
        }
      } catch (defaultError) {
        error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody ` +
                         `- "${responseBody}" for the default response.`;
        return callback(error);
      }
      return callback(error);
    }
    // Create Result
    let result = null;
    if (responseBody === '') responseBody = null;
    // Deserialize Response
    if (statusCode === 200) {
      let parsedResponse = null;
      try {
        parsedResponse = JSON.parse(responseBody);
        result = JSON.parse(responseBody);
        if (parsedResponse !== null && parsedResponse !== undefined) {
          let resultMapper = new client.models['JobExecutionListResult']().mapper();
          result = client.deserialize(resultMapper, parsedResponse, 'result');
        }
      } catch (error) {
        let deserializationError = new Error(`Error ${error} occurred in deserializing the responseBody - ${responseBody}`);
        deserializationError.request = msRest.stripRequest(httpRequest);
        deserializationError.response = msRest.stripResponse(response);
        return callback(deserializationError);
      }
    }

    return callback(null, result, httpRequest, response);
  });
}

/** Class representing a JobExecutions. */
class JobExecutions {
  /**
   * Create a JobExecutions.
   * @param {SqlManagementClient} client Reference to the service client.
   */
  constructor(client) {
    this.client = client;
    this._listByAgent = _listByAgent;
    this._cancel = _cancel;
    this._create = _create;
    this._listByJob = _listByJob;
    this._get = _get;
    this._createOrUpdate = _createOrUpdate;
    this._beginCreate = _beginCreate;
    this._beginCreateOrUpdate = _beginCreateOrUpdate;
    this._listByAgentNext = _listByAgentNext;
    this._listByJobNext = _listByJobNext;
  }

  /**
   * Lists all executions in a job agent.
   *
   * @param {string} 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 {string} serverName The name of the server.
   *
   * @param {string} jobAgentName The name of the job agent.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {date} [options.createTimeMin] If specified, only job executions
   * created at or after the specified time are included.
   *
   * @param {date} [options.createTimeMax] If specified, only job executions
   * created before the specified time are included.
   *
   * @param {date} [options.endTimeMin] If specified, only job executions
   * completed at or after the specified time are included.
   *
   * @param {date} [options.endTimeMax] If specified, only job executions
   * completed before the specified time are included.
   *
   * @param {boolean} [options.isActive] If specified, only active or only
   * completed job executions are included.
   *
   * @param {number} [options.skip] The number of elements in the collection to
   * skip.
   *
   * @param {number} [options.top] The number of elements to return from the
   * collection.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<JobExecutionListResult>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  listByAgentWithHttpOperationResponse(resourceGroupName, serverName, jobAgentName, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._listByAgent(resourceGroupName, serverName, jobAgentName, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Lists all executions in a job agent.
   *
   * @param {string} 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 {string} serverName The name of the server.
   *
   * @param {string} jobAgentName The name of the job agent.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {date} [options.createTimeMin] If specified, only job executions
   * created at or after the specified time are included.
   *
   * @param {date} [options.createTimeMax] If specified, only job executions
   * created before the specified time are included.
   *
   * @param {date} [options.endTimeMin] If specified, only job executions
   * completed at or after the specified time are included.
   *
   * @param {date} [options.endTimeMax] If specified, only job executions
   * completed before the specified time are included.
   *
   * @param {boolean} [options.isActive] If specified, only active or only
   * completed job executions are included.
   *
   * @param {number} [options.skip] The number of elements in the collection to
   * skip.
   *
   * @param {number} [options.top] The number of elements to return from the
   * collection.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @param {function} [optionalCallback] - The optional callback.
   *
   * @returns {function|Promise} If a callback was passed as the last parameter
   * then it returns the callback else returns a Promise.
   *
   * {Promise} A promise is returned
   *
   *                      @resolve {JobExecutionListResult} - The deserialized result object.
   *
   *                      @reject {Error} - The error object.
   *
   * {function} optionalCallback(err, result, request, response)
   *
   *                      {Error}  err        - The Error object if an error occurred, null otherwise.
   *
   *                      {object} [result]   - The deserialized result object if an error did not occur.
   *                      See {@link JobExecutionListResult} for more
   *                      information.
   *
   *                      {object} [request]  - The HTTP Request object if an error did not occur.
   *
   *                      {stream} [response] - The HTTP Response stream if an error did not occur.
   */
  listByAgent(resourceGroupName, serverName, jobAgentName, options, optionalCallback) {
    let client = this.client;
    let self = this;
    if (!optionalCallback && typeof options === 'function') {
      optionalCallback = options;
      options = null;
    }
    if (!optionalCallback) {
      return new Promise((resolve, reject) => {
        self._listByAgent(resourceGroupName, serverName, jobAgentName, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._listByAgent(resourceGroupName, serverName, jobAgentName, options, optionalCallback);
    }
  }

  /**
   * Requests cancellation of a job execution.
   *
   * @param {string} 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 {string} serverName The name of the server.
   *
   * @param {string} jobAgentName The name of the job agent.
   *
   * @param {string} jobName The name of the job.
   *
   * @param {uuid} jobExecutionId The id of the job execution to cancel.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<null>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  cancelWithHttpOperationResponse(resourceGroupName, serverName, jobAgentName, jobName, jobExecutionId, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._cancel(resourceGroupName, serverName, jobAgentName, jobName, jobExecutionId, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Requests cancellation of a job execution.
   *
   * @param {string} 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 {string} serverName The name of the server.
   *
   * @param {string} jobAgentName The name of the job agent.
   *
   * @param {string} jobName The name of the job.
   *
   * @param {uuid} jobExecutionId The id of the job execution to cancel.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @param {function} [optionalCallback] - The optional callback.
   *
   * @returns {function|Promise} If a callback was passed as the last parameter
   * then it returns the callback else returns a Promise.
   *
   * {Promise} A promise is returned
   *
   *                      @resolve {null} - The deserialized result object.
   *
   *                      @reject {Error} - The error object.
   *
   * {function} optionalCallback(err, result, request, response)
   *
   *                      {Error}  err        - The Error object if an error occurred, null otherwise.
   *
   *                      {null} [result]   - The deserialized result object if an error did not occur.
   *
   *                      {object} [request]  - The HTTP Request object if an error did not occur.
   *
   *                      {stream} [response] - The HTTP Response stream if an error did not occur.
   */
  cancel(resourceGroupName, serverName, jobAgentName, jobName, jobExecutionId, options, optionalCallback) {
    let client = this.client;
    let self = this;
    if (!optionalCallback && typeof options === 'function') {
      optionalCallback = options;
      options = null;
    }
    if (!optionalCallback) {
      return new Promise((resolve, reject) => {
        self._cancel(resourceGroupName, serverName, jobAgentName, jobName, jobExecutionId, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._cancel(resourceGroupName, serverName, jobAgentName, jobName, jobExecutionId, options, optionalCallback);
    }
  }

  /**
   * Starts an elastic job execution.
   *
   * @param {string} 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 {string} serverName The name of the server.
   *
   * @param {string} jobAgentName The name of the job agent.
   *
   * @param {string} jobName The name of the job to get.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<JobExecution>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  createWithHttpOperationResponse(resourceGroupName, serverName, jobAgentName, jobName, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._create(resourceGroupName, serverName, jobAgentName, jobName, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Starts an elastic job execution.
   *
   * @param {string} 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 {string} serverName The name of the server.
   *
   * @param {string} jobAgentName The name of the job agent.
   *
   * @param {string} jobName The name of the job to get.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @param {function} [optionalCallback] - The optional callback.
   *
   * @returns {function|Promise} If a callback was passed as the last parameter
   * then it returns the callback else returns a Promise.
   *
   * {Promise} A promise is returned
   *
   *                      @resolve {JobExecution} - The deserialized result object.
   *
   *                      @reject {Error} - The error object.
   *
   * {function} optionalCallback(err, result, request, response)
   *
   *                      {Error}  err        - The Error object if an error occurred, null otherwise.
   *
   *                      {object} [result]   - The deserialized result object if an error did not occur.
   *                      See {@link JobExecution} for more information.
   *
   *                      {object} [request]  - The HTTP Request object if an error did not occur.
   *
   *                      {stream} [response] - The HTTP Response stream if an error did not occur.
   */
  create(resourceGroupName, serverName, jobAgentName, jobName, options, optionalCallback) {
    let client = this.client;
    let self = this;
    if (!optionalCallback && typeof options === 'function') {
      optionalCallback = options;
      options = null;
    }
    if (!optionalCallback) {
      return new Promise((resolve, reject) => {
        self._create(resourceGroupName, serverName, jobAgentName, jobName, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._create(resourceGroupName, serverName, jobAgentName, jobName, options, optionalCallback);
    }
  }

  /**
   * Lists a job's executions.
   *
   * @param {string} 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 {string} serverName The name of the server.
   *
   * @param {string} jobAgentName The name of the job agent.
   *
   * @param {string} jobName The name of the job to get.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {date} [options.createTimeMin] If specified, only job executions
   * created at or after the specified time are included.
   *
   * @param {date} [options.createTimeMax] If specified, only job executions
   * created before the specified time are included.
   *
   * @param {date} [options.endTimeMin] If specified, only job executions
   * completed at or after the specified time are included.
   *
   * @param {date} [options.endTimeMax] If specified, only job executions
   * completed before the specified time are included.
   *
   * @param {boolean} [options.isActive] If specified, only active or only
   * completed job executions are included.
   *
   * @param {number} [options.skip] The number of elements in the collection to
   * skip.
   *
   * @param {number} [options.top] The number of elements to return from the
   * collection.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<JobExecutionListResult>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  listByJobWithHttpOperationResponse(resourceGroupName, serverName, jobAgentName, jobName, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._listByJob(resourceGroupName, serverName, jobAgentName, jobName, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Lists a job's executions.
   *
   * @param {string} 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 {string} serverName The name of the server.
   *
   * @param {string} jobAgentName The name of the job agent.
   *
   * @param {string} jobName The name of the job to get.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {date} [options.createTimeMin] If specified, only job executions
   * created at or after the specified time are included.
   *
   * @param {date} [options.createTimeMax] If specified, only job executions
   * created before the specified time are included.
   *
   * @param {date} [options.endTimeMin] If specified, only job executions
   * completed at or after the specified time are included.
   *
   * @param {date} [options.endTimeMax] If specified, only job executions
   * completed before the specified time are included.
   *
   * @param {boolean} [options.isActive] If specified, only active or only
   * completed job executions are included.
   *
   * @param {number} [options.skip] The number of elements in the collection to
   * skip.
   *
   * @param {number} [options.top] The number of elements to return from the
   * collection.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @param {function} [optionalCallback] - The optional callback.
   *
   * @returns {function|Promise} If a callback was passed as the last parameter
   * then it returns the callback else returns a Promise.
   *
   * {Promise} A promise is returned
   *
   *                      @resolve {JobExecutionListResult} - The deserialized result object.
   *
   *                      @reject {Error} - The error object.
   *
   * {function} optionalCallback(err, result, request, response)
   *
   *                      {Error}  err        - The Error object if an error occurred, null otherwise.
   *
   *                      {object} [result]   - The deserialized result object if an error did not occur.
   *                      See {@link JobExecutionListResult} for more
   *                      information.
   *
   *                      {object} [request]  - The HTTP Request object if an error did not occur.
   *
   *                      {stream} [response] - The HTTP Response stream if an error did not occur.
   */
  listByJob(resourceGroupName, serverName, jobAgentName, jobName, options, optionalCallback) {
    let client = this.client;
    let self = this;
    if (!optionalCallback && typeof options === 'function') {
      optionalCallback = options;
      options = null;
    }
    if (!optionalCallback) {
      return new Promise((resolve, reject) => {
        self._listByJob(resourceGroupName, serverName, jobAgentName, jobName, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._listByJob(resourceGroupName, serverName, jobAgentName, jobName, options, optionalCallback);
    }
  }

  /**
   * Gets a job execution.
   *
   * @param {string} 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 {string} serverName The name of the server.
   *
   * @param {string} jobAgentName The name of the job agent.
   *
   * @param {string} jobName The name of the job.
   *
   * @param {uuid} jobExecutionId The id of the job execution
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<JobExecution>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  getWithHttpOperationResponse(resourceGroupName, serverName, jobAgentName, jobName, jobExecutionId, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._get(resourceGroupName, serverName, jobAgentName, jobName, jobExecutionId, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Gets a job execution.
   *
   * @param {string} 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 {string} serverName The name of the server.
   *
   * @param {string} jobAgentName The name of the job agent.
   *
   * @param {string} jobName The name of the job.
   *
   * @param {uuid} jobExecutionId The id of the job execution
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @param {function} [optionalCallback] - The optional callback.
   *
   * @returns {function|Promise} If a callback was passed as the last parameter
   * then it returns the callback else returns a Promise.
   *
   * {Promise} A promise is returned
   *
   *                      @resolve {JobExecution} - The deserialized result object.
   *
   *                      @reject {Error} - The error object.
   *
   * {function} optionalCallback(err, result, request, response)
   *
   *                      {Error}  err        - The Error object if an error occurred, null otherwise.
   *
   *                      {object} [result]   - The deserialized result object if an error did not occur.
   *                      See {@link JobExecution} for more information.
   *
   *                      {object} [request]  - The HTTP Request object if an error did not occur.
   *
   *                      {stream} [response] - The HTTP Response stream if an error did not occur.
   */
  get(resourceGroupName, serverName, jobAgentName, jobName, jobExecutionId, options, optionalCallback) {
    let client = this.client;
    let self = this;
    if (!optionalCallback && typeof options === 'function') {
      optionalCallback = options;
      options = null;
    }
    if (!optionalCallback) {
      return new Promise((resolve, reject) => {
        self._get(resourceGroupName, serverName, jobAgentName, jobName, jobExecutionId, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._get(resourceGroupName, serverName, jobAgentName, jobName, jobExecutionId, options, optionalCallback);
    }
  }

  /**
   * Creates or updates a job execution.
   *
   * @param {string} 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 {string} serverName The name of the server.
   *
   * @param {string} jobAgentName The name of the job agent.
   *
   * @param {string} jobName The name of the job to get.
   *
   * @param {uuid} jobExecutionId The job execution id to create the job
   * execution under.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<JobExecution>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  createOrUpdateWithHttpOperationResponse(resourceGroupName, serverName, jobAgentName, jobName, jobExecutionId, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._createOrUpdate(resourceGroupName, serverName, jobAgentName, jobName, jobExecutionId, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Creates or updates a job execution.
   *
   * @param {string} 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 {string} serverName The name of the server.
   *
   * @param {string} jobAgentName The name of the job agent.
   *
   * @param {string} jobName The name of the job to get.
   *
   * @param {uuid} jobExecutionId The job execution id to create the job
   * execution under.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @param {function} [optionalCallback] - The optional callback.
   *
   * @returns {function|Promise} If a callback was passed as the last parameter
   * then it returns the callback else returns a Promise.
   *
   * {Promise} A promise is returned
   *
   *                      @resolve {JobExecution} - The deserialized result object.
   *
   *                      @reject {Error} - The error object.
   *
   * {function} optionalCallback(err, result, request, response)
   *
   *                      {Error}  err        - The Error object if an error occurred, null otherwise.
   *
   *                      {object} [result]   - The deserialized result object if an error did not occur.
   *                      See {@link JobExecution} for more information.
   *
   *                      {object} [request]  - The HTTP Request object if an error did not occur.
   *
   *                      {stream} [response] - The HTTP Response stream if an error did not occur.
   */
  createOrUpdate(resourceGroupName, serverName, jobAgentName, jobName, jobExecutionId, options, optionalCallback) {
    let client = this.client;
    let self = this;
    if (!optionalCallback && typeof options === 'function') {
      optionalCallback = options;
      options = null;
    }
    if (!optionalCallback) {
      return new Promise((resolve, reject) => {
        self._createOrUpdate(resourceGroupName, serverName, jobAgentName, jobName, jobExecutionId, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._createOrUpdate(resourceGroupName, serverName, jobAgentName, jobName, jobExecutionId, options, optionalCallback);
    }
  }

  /**
   * Starts an elastic job execution.
   *
   * @param {string} 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 {string} serverName The name of the server.
   *
   * @param {string} jobAgentName The name of the job agent.
   *
   * @param {string} jobName The name of the job to get.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<JobExecution>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  beginCreateWithHttpOperationResponse(resourceGroupName, serverName, jobAgentName, jobName, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._beginCreate(resourceGroupName, serverName, jobAgentName, jobName, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Starts an elastic job execution.
   *
   * @param {string} 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 {string} serverName The name of the server.
   *
   * @param {string} jobAgentName The name of the job agent.
   *
   * @param {string} jobName The name of the job to get.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @param {function} [optionalCallback] - The optional callback.
   *
   * @returns {function|Promise} If a callback was passed as the last parameter
   * then it returns the callback else returns a Promise.
   *
   * {Promise} A promise is returned
   *
   *                      @resolve {JobExecution} - The deserialized result object.
   *
   *                      @reject {Error} - The error object.
   *
   * {function} optionalCallback(err, result, request, response)
   *
   *                      {Error}  err        - The Error object if an error occurred, null otherwise.
   *
   *                      {object} [result]   - The deserialized result object if an error did not occur.
   *                      See {@link JobExecution} for more information.
   *
   *                      {object} [request]  - The HTTP Request object if an error did not occur.
   *
   *                      {stream} [response] - The HTTP Response stream if an error did not occur.
   */
  beginCreate(resourceGroupName, serverName, jobAgentName, jobName, options, optionalCallback) {
    let client = this.client;
    let self = this;
    if (!optionalCallback && typeof options === 'function') {
      optionalCallback = options;
      options = null;
    }
    if (!optionalCallback) {
      return new Promise((resolve, reject) => {
        self._beginCreate(resourceGroupName, serverName, jobAgentName, jobName, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._beginCreate(resourceGroupName, serverName, jobAgentName, jobName, options, optionalCallback);
    }
  }

  /**
   * Creates or updates a job execution.
   *
   * @param {string} 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 {string} serverName The name of the server.
   *
   * @param {string} jobAgentName The name of the job agent.
   *
   * @param {string} jobName The name of the job to get.
   *
   * @param {uuid} jobExecutionId The job execution id to create the job
   * execution under.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<JobExecution>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  beginCreateOrUpdateWithHttpOperationResponse(resourceGroupName, serverName, jobAgentName, jobName, jobExecutionId, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._beginCreateOrUpdate(resourceGroupName, serverName, jobAgentName, jobName, jobExecutionId, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Creates or updates a job execution.
   *
   * @param {string} 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 {string} serverName The name of the server.
   *
   * @param {string} jobAgentName The name of the job agent.
   *
   * @param {string} jobName The name of the job to get.
   *
   * @param {uuid} jobExecutionId The job execution id to create the job
   * execution under.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @param {function} [optionalCallback] - The optional callback.
   *
   * @returns {function|Promise} If a callback was passed as the last parameter
   * then it returns the callback else returns a Promise.
   *
   * {Promise} A promise is returned
   *
   *                      @resolve {JobExecution} - The deserialized result object.
   *
   *                      @reject {Error} - The error object.
   *
   * {function} optionalCallback(err, result, request, response)
   *
   *                      {Error}  err        - The Error object if an error occurred, null otherwise.
   *
   *                      {object} [result]   - The deserialized result object if an error did not occur.
   *                      See {@link JobExecution} for more information.
   *
   *                      {object} [request]  - The HTTP Request object if an error did not occur.
   *
   *                      {stream} [response] - The HTTP Response stream if an error did not occur.
   */
  beginCreateOrUpdate(resourceGroupName, serverName, jobAgentName, jobName, jobExecutionId, options, optionalCallback) {
    let client = this.client;
    let self = this;
    if (!optionalCallback && typeof options === 'function') {
      optionalCallback = options;
      options = null;
    }
    if (!optionalCallback) {
      return new Promise((resolve, reject) => {
        self._beginCreateOrUpdate(resourceGroupName, serverName, jobAgentName, jobName, jobExecutionId, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._beginCreateOrUpdate(resourceGroupName, serverName, jobAgentName, jobName, jobExecutionId, options, optionalCallback);
    }
  }

  /**
   * Lists all executions in a job agent.
   *
   * @param {string} nextPageLink The NextLink from the previous successful call
   * to List operation.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<JobExecutionListResult>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  listByAgentNextWithHttpOperationResponse(nextPageLink, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._listByAgentNext(nextPageLink, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Lists all executions in a job agent.
   *
   * @param {string} nextPageLink The NextLink from the previous successful call
   * to List operation.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @param {function} [optionalCallback] - The optional callback.
   *
   * @returns {function|Promise} If a callback was passed as the last parameter
   * then it returns the callback else returns a Promise.
   *
   * {Promise} A promise is returned
   *
   *                      @resolve {JobExecutionListResult} - The deserialized result object.
   *
   *                      @reject {Error} - The error object.
   *
   * {function} optionalCallback(err, result, request, response)
   *
   *                      {Error}  err        - The Error object if an error occurred, null otherwise.
   *
   *                      {object} [result]   - The deserialized result object if an error did not occur.
   *                      See {@link JobExecutionListResult} for more
   *                      information.
   *
   *                      {object} [request]  - The HTTP Request object if an error did not occur.
   *
   *                      {stream} [response] - The HTTP Response stream if an error did not occur.
   */
  listByAgentNext(nextPageLink, options, optionalCallback) {
    let client = this.client;
    let self = this;
    if (!optionalCallback && typeof options === 'function') {
      optionalCallback = options;
      options = null;
    }
    if (!optionalCallback) {
      return new Promise((resolve, reject) => {
        self._listByAgentNext(nextPageLink, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._listByAgentNext(nextPageLink, options, optionalCallback);
    }
  }

  /**
   * Lists a job's executions.
   *
   * @param {string} nextPageLink The NextLink from the previous successful call
   * to List operation.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @returns {Promise} A promise is returned
   *
   * @resolve {HttpOperationResponse<JobExecutionListResult>} - The deserialized result object.
   *
   * @reject {Error} - The error object.
   */
  listByJobNextWithHttpOperationResponse(nextPageLink, options) {
    let client = this.client;
    let self = this;
    return new Promise((resolve, reject) => {
      self._listByJobNext(nextPageLink, options, (err, result, request, response) => {
        let httpOperationResponse = new msRest.HttpOperationResponse(request, response);
        httpOperationResponse.body = result;
        if (err) { reject(err); }
        else { resolve(httpOperationResponse); }
        return;
      });
    });
  }

  /**
   * Lists a job's executions.
   *
   * @param {string} nextPageLink The NextLink from the previous successful call
   * to List operation.
   *
   * @param {object} [options] Optional Parameters.
   *
   * @param {object} [options.customHeaders] Headers that will be added to the
   * request
   *
   * @param {function} [optionalCallback] - The optional callback.
   *
   * @returns {function|Promise} If a callback was passed as the last parameter
   * then it returns the callback else returns a Promise.
   *
   * {Promise} A promise is returned
   *
   *                      @resolve {JobExecutionListResult} - The deserialized result object.
   *
   *                      @reject {Error} - The error object.
   *
   * {function} optionalCallback(err, result, request, response)
   *
   *                      {Error}  err        - The Error object if an error occurred, null otherwise.
   *
   *                      {object} [result]   - The deserialized result object if an error did not occur.
   *                      See {@link JobExecutionListResult} for more
   *                      information.
   *
   *                      {object} [request]  - The HTTP Request object if an error did not occur.
   *
   *                      {stream} [response] - The HTTP Response stream if an error did not occur.
   */
  listByJobNext(nextPageLink, options, optionalCallback) {
    let client = this.client;
    let self = this;
    if (!optionalCallback && typeof options === 'function') {
      optionalCallback = options;
      options = null;
    }
    if (!optionalCallback) {
      return new Promise((resolve, reject) => {
        self._listByJobNext(nextPageLink, options, (err, result, request, response) => {
          if (err) { reject(err); }
          else { resolve(result); }
          return;
        });
      });
    } else {
      return self._listByJobNext(nextPageLink, options, optionalCallback);
    }
  }

}

module.exports = JobExecutions;
