The steps I took to solve the problem

  1.  First I loaded SwaggerHub in Chrome.

If you want to follow along, you will need to create an SwaggerHub account

I then imported the generated Swagger JSON from my API, as shown below:

import

  1.  I pasted in the URL to my Swagger file and gave it a distinct name.

 The Swagger is formatted in YAML.  This makes it easier to edit than JSON.   🙂

  1.  In the Editor, I removed the duplicate Status Codes as seen starting on Line 127 below.

swagger1
swagger2
swagger3
swagger4
swagger5

If you look at Line 100, you will see Definitions.  Definitions are used to generate the Model classes.

  1.  On Line 198, the generated class name would be Microsoft.Azure.Documents.StoredProcedures.  I changed that to StoredProcedures. 

  2.  On Line 113, I changed the name to StoredProcedureResponse as shown above.

  3.  I went even further and added additional description and summary information, since this is used to create comments in the generated code.

  4.  I  downloaded the formatted Swagger JSON from SwaggerHub.  The following is final Swagger JSON file.

{
  "swagger" : "2.0",
  "info" : {
    "description" : "DocumentDB Stored Procedures API ",
    "version" : "1.0.2",
    "title" : "DocDbSpApi",
    "contact" : {
      "name" : "Howard S. Edidin",
      "url" : "http://edidin-group.com",
      "email" : "hedidin@edidingroup.net"
    },
    "license" : {
      "name" : "LICENSE",
      "url" : "https://github.com/HEDIDIN/DocDBApi5/blob/master/LICENSE"
    }
  },
  "host" : "XXXXXXXX.documents.azure.com:443",
  "basePath" : "/dbs",
  "schemes" : [ "https" ],
  "paths" : {
    "/fhir/colls/patient/sprocs" : {
      "get" : {
        "tags" : [ "StoredProcedure" ],
        "summary" : "Get Stored Procedures List",
        "description" : "Get an array of all stored procedures.\n- Read the feed 10 items at a time until there are no more items to read",
        "operationId" : "GetListOfStoredProcedures",
        "consumes" : [ ],
        "produces" : [ "application/json" ],
        "parameters" : [ {
          "name" : "authorization",
          "in" : "header",
          "description" : "The authentication type and signature token. Both master key and resource tokens are allowed for this operation. \n\n - ** <c>type={typeoftoken}%26ver={tokenversion}%26sig={hashsignature}</c>**",
          "required" : true,
          "type" : "string"
        }, {
          "name" : "x-ms-date",
          "in" : "header",
          "description" : "The date of the request The date is expressed in **Coordinated Universal Time format**.\n  - <sample> Fri, 08 Apr 2015 03:52:31 GMT</sample>",
          "required" : true,
          "type" : "string"
        }, {
          "name" : "x-ms-version",
          "in" : "header",
          "description" : "The version of DocumentDB REST service. The latest version is used when the header is not provided use\n - <c>2015-08-06</c>",
          "required" : true,
          "type" : "string"
        }, {
          "name" : "User-Agent",
          "in" : "header",
          "description" : "_Optional._ The string of client user agent performing the request. \n\n The recommended format is \n  \n  **<c>{user agent name}/{version}</c>**",
          "required" : false,
          "type" : "string"
        } ],
        "responses" : {
          "200" : {
            "description" : "OK",
            "schema" : {
              "type" : "array",
              "items" : {
                "$ref" : "#/definitions/StoredProcedure"
              }
            }
          },
          "404" : {
            "description" : "Not Found - This means the resource feed you tried to read did not exist."
          },
          "429" : {
            "description" : "TooManyRequests - This means you have exceeded the number of request units per second."
          },
          "500" : {
            "description" : "Internal Server Error"
          }
        }
      }
    },
    "/fhir/colls/patient/sprocs/{rid-proc}" : {
      "post" : {
        "tags" : [ "StoredProcedure" ],
        "summary" : "Execute a Stored Procedure",
        "description" : "**Execute a Stored Procedure**\n-  For information on how stored procedures work, including execution of a stored procedure, see [DocumentDB programming Stored procedures](http://azure.microsoft.com/en-us/documentation/articles/documentdb-programming/)",
        "operationId" : "ExecuteAStoredProcedure",
        "consumes" : [ "application/json" ],
        "produces" : [ "application/json" ],
        "parameters" : [ {
          "name" : "authorization",
          "in" : "header",
          "description" : "The authentication type and signature token. Both master key and resource tokens are allowed for this operation. \n\n - ** <c>type={typeoftoken}%26ver={tokenversion}%26sig={hashsignature}</c>**",
          "required" : true,
          "type" : "string"
        }, {
          "name" : "x-ms-date",
          "in" : "header",
          "description" : "The date of the request The date is expressed in **Coordinated Universal Time format**.\n  - <sample> **Fri, 08 Apr 2015 03:52:31 GMT**</sample>",
          "required" : true,
          "type" : "string"
        }, {
          "name" : "x-ms-version",
          "in" : "header",
          "description" : "The version of DocumentDB REST service. The latest version is used when the header is not provided use\n - **<c>2015-08-06</c>**",
          "required" : true,
          "type" : "string"
        }, {
          "name" : "Content-Type",
          "in" : "header",
          "description" : "Required. The Content-Type header must be **application/json.**",
          "required" : true,
          "type" : "string",
          "default" : "application/query+json"
        }, {
          "name" : "x-ms-documentdb-query-enable-scan",
          "in" : "header",
          "required" : true,
          "type" : "boolean",
          "default" : true
        }, {
          "name" : "x-ms-documentdb-isquery",
          "in" : "header",
          "required" : true,
          "type" : "boolean",
          "default" : true
        }, {
          "in" : "body",
          "name" : "queryRequest",
          "description" : "The Query body",
          "required" : true,
          "schema" : {
            "$ref" : "#/definitions/QueryRequest"
          },
          "x-ms-summary" : "Query Request body"
        }, {
          "name" : "rid-proc",
          "in" : "path",
          "description" : "The Proc Id",
          "required" : true,
          "type" : "string"
        }, {
          "name" : "User-Agent",
          "in" : "header",
          "description" : "_Optional_. The string of client user agent performing the request. \n\n  The recommended format is\n    \n  **<c>{user agent name}/{version}</c>**",
          "required" : false,
          "type" : "string"
        } ],
        "responses" : {
          "200" : {
            "description" : "Success",
            "schema" : {
              "$ref" : "#/definitions/StoredProcedureResponse"
            }
          },
          "400" : {
            "description" : "BadRequest -The syntax of the SQL statement is incorrect"
          },
          "500" : {
            "description" : "Internal Server Error"
          }
        }
      }
    }
  },
  "definitions" : {
    "QueryRequest" : {
      "type" : "object",
      "properties" : {
        "querystring" : {
          "type" : "string",
          "description" : "The SQL query string for the query"
        },
        "parameters" : {
          "type" : "array",
          "description" : "A JSON array of parameters specified as name value pairs. The parameter array can contain from zero to many parameters.Each parameter must have the following values:name: the name of the parameter. Parameter names must be valid string literals and begin with ‘@’.value: the value of the parameter. Can be any valid JSON value (string, number, object, array, Boolean or null).",
          "items" : {
            "type" : "string"
          }
        }
      },
      "description" : "Perform a SQL query Request on a resource"
    },
    "StoredProcedureResponse" : {
      "type" : "object",
      "properties" : {
        "ActivityId" : {
          "type" : "string",
          "readOnly" : true
        },
        "SessionToken" : {
          "type" : "string",
          "readOnly" : true
        },
        "StatusCode" : {
          "type" : "integer",
          "format" : "int32",
          "readOnly" : true,
          "enum" : [ 200, 201, 204, 400, 401, 403, 404, 408, 409, 410, 412, 413, 429 ]
        },
        "MaxResourceQuota" : {
          "type" : "string",
          "readOnly" : true
        },
        "CurrentResourceQuotaUsage" : {
          "type" : "string",
          "readOnly" : true
        },
        "RequestCharge" : {
          "type" : "number",
          "format" : "double",
          "readOnly" : true
        },
        "ResponseHeaders" : {
          "type" : "array",
          "items" : {
            "$ref" : "#/definitions/System.Object"
          }
        },
        "Response" : {
          "type" : "string",
          "readOnly" : true
        }
      }
    },
    "System.Object" : {
      "type" : "object"
    },
    "StoredProcedure" : {
      "type" : "object",
      "properties" : {
        "body" : {
          "type" : "string"
        },
        "id" : {
          "type" : "string"
        },
        "_rid" : {
          "type" : "string"
        },
        "_self" : {
          "type" : "string"
        },
        "_ts" : {
          "type" : "string",
          "format" : "date-time"
        },
        "_etag" : {
          "type" : "string"
        }
      }
    }
  }
}

Next Steps

I created a new API project in Visual Studio 2015.

  1.  I selected my modified  Swagger Metadata file and clicked “OK”.

AddRestApi

This time there were no errors

RestSharp had generated all the classes I needed as shown below.

vs project

The following are classes that were generated.

// Code generated by Microsoft (R) AutoRest Code Generator 0.9.7.0
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using DocDbStoredProcApi.Models;
using Microsoft.Rest;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace DocDbStoredProcApi
{
    /// <summary>
    /// 
    /// </summary>
    public class DocDbSpApi : ServiceClient<DocDbSpApi>, IDocDbSpApi
    {
        /// <summary>
        ///     Initializes a new instance of the DocDbSpApi class.
        /// </summary>
        public DocDbSpApi()
        {
            BaseUri = new Uri("https://docdbspapi.azurewebsites.net");
        }

        /// <summary>
        ///     Initializes a new instance of the DocDbSpApi class.
        /// </summary>
        /// <param name='handlers'>
        ///     Optional. The set of delegating handlers to insert in the http
        ///     client pipeline.
        /// </param>
        public DocDbSpApi(params DelegatingHandler[] handlers)
            : base(handlers)
        {
            BaseUri = new Uri("https://docdbspapi.azurewebsites.net");
        }

        /// <summary>
        ///     Initializes a new instance of the DocDbSpApi class.
        /// </summary>
        /// <param name='rootHandler'>
        ///     Optional. The http client handler used to handle http transport.
        /// </param>
        /// <param name='handlers'>
        ///     Optional. The set of delegating handlers to insert in the http
        ///     client pipeline.
        /// </param>
        public DocDbSpApi(HttpClientHandler rootHandler, params DelegatingHandler[] handlers)
            : base(rootHandler, handlers)
        {
            BaseUri = new Uri("https://docdbspapi.azurewebsites.net");
        }

        /// <summary>
        ///     Initializes a new instance of the DocDbSpApi class.
        /// </summary>
        /// <param name='baseUri'>
        ///     Optional. The base URI of the service.
        /// </param>
        /// <param name='handlers'>
        ///     Optional. The set of delegating handlers to insert in the http
        ///     client pipeline.
        /// </param>
        public DocDbSpApi(Uri baseUri, params DelegatingHandler[] handlers)
            : this(handlers)
        {
            if (baseUri == null)
            {
                throw new ArgumentNullException(nameof(baseUri));
            }
            BaseUri = baseUri;
        }

        /// <summary>
        ///     Initializes a new instance of the DocDbSpApi class.
        /// </summary>
        /// <param name='credentials'>
        ///     Required. Credentials for authenticating with the service.
        /// </param>
        /// <param name='handlers'>
        ///     Optional. The set of delegating handlers to insert in the http
        ///     client pipeline.
        /// </param>
        public DocDbSpApi(ServiceClientCredentials credentials, params DelegatingHandler[] handlers)
            : this(handlers)
        {
            if (credentials == null)
            {
                throw new ArgumentNullException(nameof(credentials));
            }
            Credentials = credentials;

            Credentials?.InitializeServiceClient(this);
        }

        /// <summary>
        ///     Initializes a new instance of the DocDbSpApi class.
        /// </summary>
        /// <param name='baseUri'>
        ///     Optional. The base URI of the service.
        /// </param>
        /// <param name='credentials'>
        ///     Required. Credentials for authenticating with the service.
        /// </param>
        /// <param name='handlers'>
        ///     Optional. The set of delegating handlers to insert in the http
        ///     client pipeline.
        /// </param>
        public DocDbSpApi(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers)
            : this(handlers)
        {
            if (baseUri == null)
            {
                throw new ArgumentNullException(nameof(baseUri));
            }
            if (credentials == null)
            {
                throw new ArgumentNullException(nameof(credentials));
            }
            BaseUri = baseUri;
            Credentials = credentials;

            Credentials?.InitializeServiceClient(this);
        }

        /// <summary>
        ///     The base URI of the service.
        /// </summary>
        public Uri BaseUri { get; set; }

        /// <summary>
        ///     Credentials for authenticating with the service.
        /// </summary>
        public ServiceClientCredentials Credentials { get; set; }

        /// <summary>
        ///     Returns the Response as a string
        /// </summary>
        /// <param name='storedProcedureId'>
        ///     Required. Stored Procedure Id
        /// </param>
        /// <param name='queryRequest'>
        ///     Required. The Query body
        /// </param>
        /// <param name='ridDB'>
        ///     Required. The Database Id
        /// </param>
        /// <param name='ridColl'>
        ///     Required. The Collection Id
        /// </param>
        /// <param name='ridProc'>
        ///     Required. The Proc Id
        /// </param>
        /// <param name='cancellationToken'>
        ///     Cancellation token.
        /// </param>
        public async Task<HttpOperationResponse<StoredProcedureResponse>>
            ExecuteAStoredProcedureWithOperationResponseAsync(string storedProcedureId, QueryRequest queryRequest,
                string ridDB, string ridColl, string ridProc,
                CancellationToken cancellationToken = default(CancellationToken))
        {
            // Validate
            if (storedProcedureId == null)
            {
                throw new ArgumentNullException(nameof(storedProcedureId));
            }
            if (queryRequest == null)
            {
                throw new ArgumentNullException(nameof(queryRequest));
            }
            if (ridDB == null)
            {
                throw new ArgumentNullException(nameof(ridDB));
            }
            if (ridColl == null)
            {
                throw new ArgumentNullException(nameof(ridColl));
            }
            if (ridProc == null)
            {
                throw new ArgumentNullException(nameof(ridProc));
            }

            // Tracing
            var shouldTrace = ServiceClientTracing.IsEnabled;
            string invocationId = null;
            if (shouldTrace)
            {
                invocationId = ServiceClientTracing.NextInvocationId.ToString();
                var tracingParameters = new Dictionary<string, object>
                {
                    {nameof(storedProcedureId), storedProcedureId},
                    {"queryRequest", queryRequest},
                    {"ridDB", ridDB},
                    {"ridColl", ridColl},
                    {"ridProc", ridProc}
                };
                ServiceClientTracing.Enter(invocationId, this, "ExecuteAStoredProcedureAsync", tracingParameters);
            }

            // Construct URL
            var url = "";
            url = url + "/";
            url = url + Uri.EscapeDataString(ridDB);
            url = url + "/colls/";
            url = url + Uri.EscapeDataString(ridColl);
            url = url + "/sprocs/";
            url = url + Uri.EscapeDataString(ridProc);
            var queryParameters = new List<string> {"StoredProcedureId=" + Uri.EscapeDataString(storedProcedureId)};
            if (queryParameters.Count > 0)
            {
                url = url + "?" + string.Join("&", queryParameters);
            }
            var baseUrl = BaseUri.AbsoluteUri;
            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            using (var httpRequest = new HttpRequestMessage
            {
                Method = HttpMethod.Post,
                RequestUri = new Uri(url)
            })
            {

                // Set Headers

                // Set Credentials
                if (Credentials != null)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    await Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
                }

                // Serialize Request

                var requestDoc = queryRequest.SerializeJson(null);
                var requestContent = requestDoc.ToString(Formatting.Indented);
                httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
                httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

                // Send Request
                if (shouldTrace)
                {
                    ServiceClientTracing.SendRequest(invocationId, httpRequest);
                }
                cancellationToken.ThrowIfCancellationRequested();
                var httpResponse = await HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
                if (shouldTrace)
                {
                    ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
                }
                var statusCode = httpResponse.StatusCode;
                cancellationToken.ThrowIfCancellationRequested();
                var responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.BadRequest &&
                    statusCode != HttpStatusCode.InternalServerError)
                {
                    var ex = new HttpOperationException
                    {
                        Request = httpRequest,
                        Response = httpResponse,
                        Body = null
                    };
                    if (shouldTrace)
                    {
                        ServiceClientTracing.Error(invocationId, ex);
                    }
                    throw ex;
                }

                // Create Result
                var result = new HttpOperationResponse<StoredProcedureResponse>
                {
                    Request = httpRequest,
                    Response = httpResponse
                };

                // Deserialize Response
                if (statusCode == HttpStatusCode.OK)
                {
                    var resultModel = new StoredProcedureResponse();
                    JToken responseDoc = null;
                    if (string.IsNullOrEmpty(responseContent) == false)
                    {
                        responseDoc = JToken.Parse(responseContent);
                    }
                    if (responseDoc != null)
                    {
                        resultModel.DeserializeJson(responseDoc);
                    }
                    result.Body = resultModel;
                }

                if (shouldTrace)
                {
                    ServiceClientTracing.Exit(invocationId, result);
                }
                return result;
            }
        }

        /// <summary>
        ///     Get an array of all stored procedures.
        ///     - Read the feed 10 items at a time until there are no more items to
        ///     read
        /// </summary>
        /// <param name='ridDB'>
        ///     Required. The Database Id
        /// </param>
        /// <param name='ridColl'>
        ///     Required. The Collection Id
        /// </param>
        /// <param name='cancellationToken'>
        ///     Cancellation token.
        /// </param>
        public async Task<HttpOperationResponse<IList<StoredProcedure>>>
            GetListOfStoredProceduresWithOperationResponseAsync(string ridDB, string ridColl,
                CancellationToken cancellationToken = default(CancellationToken))
        {
            // Validate
            if (ridDB == null)
            {
                throw new ArgumentNullException(nameof(ridDB));
            }
            if (ridColl == null)
            {
                throw new ArgumentNullException(nameof(ridColl));
            }

            // Tracing
            var shouldTrace = ServiceClientTracing.IsEnabled;
            string invocationId = null;
            if (shouldTrace)
            {
                invocationId = ServiceClientTracing.NextInvocationId.ToString();
                var tracingParameters = new Dictionary<string, object> {{"ridDB", ridDB}, {"ridColl", ridColl}};
                ServiceClientTracing.Enter(invocationId, this, "GetListOfStoredProceduresAsync", tracingParameters);
            }

            // Construct URL
            var url = "";
            url = url + "/";
            url = url + Uri.EscapeDataString(ridDB);
            url = url + "/colls/";
            url = url + Uri.EscapeDataString(ridColl);
            url = url + "/sprocs";
            var baseUrl = BaseUri.AbsoluteUri;
            // Trim '/' character from the end of baseUrl and beginning of url.
            if (baseUrl[baseUrl.Length - 1] == '/')
            {
                baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
            }
            if (url[0] == '/')
            {
                url = url.Substring(1);
            }
            url = baseUrl + "/" + url;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            var httpRequest = new HttpRequestMessage
            {
                Method = HttpMethod.Get,
                RequestUri = new Uri(url)
            };

            // Set Credentials
            if (Credentials != null)
            {
                cancellationToken.ThrowIfCancellationRequested();
                await Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
            }

            // Send Request
            if (shouldTrace)
            {
                ServiceClientTracing.SendRequest(invocationId, httpRequest);
            }
            cancellationToken.ThrowIfCancellationRequested();
            var httpResponse = await HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
            if (shouldTrace)
            {
                ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
            }
            var statusCode = httpResponse.StatusCode;
            cancellationToken.ThrowIfCancellationRequested();
            var responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
            if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NotFound && (int) statusCode != 429 &&
                statusCode != HttpStatusCode.InternalServerError)
            {
                var ex = new HttpOperationException
                {
                    Request = httpRequest,
                    Response = httpResponse,
                    Body = null
                };
                if (shouldTrace)
                {
                    ServiceClientTracing.Error(invocationId, ex);
                }
                throw ex;
            }

            // Create Result
            var result = new HttpOperationResponse<IList<StoredProcedure>>
            {
                Request = httpRequest,
                Response = httpResponse
            };

            // Deserialize Response
            if (statusCode == HttpStatusCode.OK)
            {
                IList<StoredProcedure> resultModel = new List<StoredProcedure>();
                JToken responseDoc = null;
                if (string.IsNullOrEmpty(responseContent) == false)
                {
                    responseDoc = JToken.Parse(responseContent);
                }
                if (responseDoc != null)
                {
                    resultModel = StoredProcedureCollection.DeserializeJson(responseDoc);
                }
                result.Body = resultModel;
            }

            if (shouldTrace)
            {
                ServiceClientTracing.Exit(invocationId, result);
            }
            return result;
        }
    }
}

// Code generated by Microsoft (R) AutoRest Code Generator 0.9.7.0
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

using System.Collections.Generic;
using Hyak.Common;
using Newtonsoft.Json.Linq;

namespace DocDbStoredProcApi.Models
{
    /// <summary>
    /// 
    /// </summary>
    public class QueryRequest
    {
        /// <summary>
        ///     Initializes a new instance of the QueryRequest class.
        /// </summary>
        public QueryRequest()
        {
            Parameters = new LazyList<string>();
        }

        /// <summary>
        ///     Optional. A JSON array of parameters specified as name value pairs.
        ///     The parameter array can contain from zero to many parameters.Each
        ///     parameter must have the following values:name: the name of the
        ///     parameter. Parameter names must be valid string literals and begin
        ///     with ‘@’.value: the value of the parameter. Can be any valid JSON
        ///     value (string, number, object, array, Boolean or null).
        /// </summary>
        public IList<string> Parameters { get; set; }

        /// <summary>
        ///     Optional. The SQL query string for the query
        /// </summary>
        public string Querystring { get; set; }

        /// <summary>
        ///     Serialize the object
        /// </summary>
        /// <param name="outputObject">JToken</param>
        /// <returns>
        ///     Returns the json model for the type QueryRequest
        /// </returns>
        public virtual JToken SerializeJson(JToken outputObject)
        {
            if (outputObject == null)
            {
                outputObject = new JObject();
            }
            if (Parameters != null)
            {
                var collection = Parameters as ILazyCollection;
                if (collection == null ||
                    ((ILazyCollection) Parameters).IsInitialized)
                {
                    var parametersSequence = new JArray();
                    outputObject["parameters"] = parametersSequence;
                    foreach (var parametersItem in Parameters)
                    {
                        if (parametersItem != null)
                            parametersSequence.Add(parametersItem);
                    }
                }
            }
            if (Querystring != null)
                outputObject["querystring"] = Querystring;
            return outputObject;
        }
    }
}

 

// Code generated by Microsoft (R) AutoRest Code Generator 0.9.7.0
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using DocDbStoredProcApi.Models;

namespace DocDbStoredProcApi
{
    /// <summary>
    /// 
    /// </summary>
    public static class DocDbSpApiExtensions
    {
        /// <summary>
        ///     Returns the Response as a string
        /// </summary>
        /// <param name='operations'>
        ///     Reference to the DocDbStoredProcApi.IDocDbSpApi.
        /// </param>
        /// <param name='storedProcedureId'>
        ///     Required. Stored Procedure Id
        /// </param>
        /// <param name='queryRequest'>
        ///     Required. The Query body
        /// </param>
        /// <param name='ridDB'>
        ///     Required. The Database Id
        /// </param>
        /// <param name='ridColl'>
        ///     Required. The Collection Id
        /// </param>
        /// <param name='ridProc'>
        ///     Required. The Proc Id
        /// </param>
        public static StoredProcedureResponse ExecuteAStoredProcedure(this IDocDbSpApi operations,
            string storedProcedureId, QueryRequest queryRequest, string ridDB, string ridColl, string ridProc)
        {
            return
                Task.Factory.StartNew(
                    s => ((IDocDbSpApi) s).ExecuteAStoredProcedureAsync(storedProcedureId, queryRequest, ridDB,
                        ridColl, ridProc), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default)
                    .Unwrap()
                    .GetAwaiter()
                    .GetResult();
        }

        /// <summary>
        ///     Returns the Response as a string
        /// </summary>
        /// <param name='operations'>
        ///     Reference to the DocDbStoredProcApi.IDocDbSpApi.
        /// </param>
        /// <param name='storedProcedureId'>
        ///     Required. Stored Procedure Id
        /// </param>
        /// <param name='queryRequest'>
        ///     Required. The Query body
        /// </param>
        /// <param name='ridDB'>
        ///     Required. The Database Id
        /// </param>
        /// <param name='ridColl'>
        ///     Required. The Collection Id
        /// </param>
        /// <param name='ridProc'>
        ///     Required. The Proc Id
        /// </param>
        /// <param name='cancellationToken'>
        ///     Cancellation token.
        /// </param>
        public static async Task<StoredProcedureResponse> ExecuteAStoredProcedureAsync(this IDocDbSpApi operations,
            string storedProcedureId, QueryRequest queryRequest, string ridDB, string ridColl, string ridProc,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            var result =
                await
                    operations.ExecuteAStoredProcedureWithOperationResponseAsync(storedProcedureId, queryRequest, ridDB,
                        ridColl, ridProc, cancellationToken).ConfigureAwait(false);
            return result.Body;
        }

        /// <summary>
        ///     Get an array of all stored procedures.
        ///     - Read the feed 10 items at a time until there are no more items to
        ///     read
        /// </summary>
        /// <param name='operations'>
        ///     Reference to the DocDbStoredProcApi.IDocDbSpApi.
        /// </param>
        /// <param name='ridDB'>
        ///     Required. The Database Id
        /// </param>
        /// <param name='ridColl'>
        ///     Required. The Collection Id
        /// </param>
        public static IList<StoredProcedure> GetListOfStoredProcedures(this IDocDbSpApi operations, string ridDB,
            string ridColl)
        {
            return
                Task.Factory.StartNew(
                    s => ((IDocDbSpApi) s).GetListOfStoredProceduresAsync(ridDB, ridColl), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default)
                    .Unwrap()
                    .GetAwaiter()
                    .GetResult();
        }

        /// <summary>
        ///     Get an array of all stored procedures.
        ///     - Read the feed 10 items at a time until there are no more items to
        ///     read
        /// </summary>
        /// <param name='operations'>
        ///     Reference to the DocDbStoredProcApi.IDocDbSpApi.
        /// </param>
        /// <param name='ridDB'>
        ///     Required. The Database Id
        /// </param>
        /// <param name='ridColl'>
        ///     Required. The Collection Id
        /// </param>
        /// <param name='cancellationToken'>
        ///     Cancellation token.
        /// </param>
        public static async Task<IList<StoredProcedure>> GetListOfStoredProceduresAsync(this IDocDbSpApi operations,
            string ridDB, string ridColl, CancellationToken cancellationToken = default(CancellationToken))
        {
            var result =
                await
                    operations.GetListOfStoredProceduresWithOperationResponseAsync(ridDB, ridColl, cancellationToken)
                        .ConfigureAwait(false);
            return result.Body;
        }
    }
}

 Creating the Controller class was easy.

using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using DocDbStoredProcApi.Models;
using Swashbuckle.Swagger.Annotations;
using TRex.Metadata;

namespace DocDbStoredProcApi.Controllers
{
    /// <summary>
    ///     DocumentDB Stored Procedure Controller
    /// </summary>
    public class StoredProcedureController : ApiController
    {
       

        /// <summary>
        ///     Execute a Stored Procedure
        /// </summary>
        /// <remarks>Returns the Response as a string</remarks>
        /// <param name="StoredProcedureId">Stored Procedure Id</param>
        /// <param name="queryRequest">SQL Query</param>
        /// <param name="RidDb">Database Id</param>
        /// <param name="RidColl">Collection Id</param>
        /// <param name="operations">IDocDbSpApi</param>
        /// <response code="200">OK</response>
        /// <response code="400">BadRequest -The syntax of the SQL statement is incorrect</response>
        /// <response code="500">Internal Server Error</response>
        /// <returns>Result of Stored Procedure Execution</returns>
        [Metadata("Execute a Stored Procedure")]
        [Route("{DatabaseId}/colls/{CollectioId}/sprocs/{SprocId}")]
        [SwaggerOperation("ExecuteStoredProcedure")]
        public async Task<StoredProcedureResponse> ExecuteStoredProcedureAsync(
            [Metadata("Stored Procedure Id")] string StoredProcedureId,
            [Metadata("Query Request body")] [FromBody] QueryRequest queryRequest,
            [Metadata("Database ID")] string RidDb,
            [Metadata("CollectionId ")] string RidColl,
            [Metadata(nameof(IDocDbSpApi))] IDocDbSpApi operations)
        {
            var sprcResponse =
                await
                    operations.ExecuteAStoredProcedureAsync(StoredProcedureId, queryRequest, RidDb,
                       RidColl, StoredProcedureId);


            return sprcResponse;
        }




        /// <summary>
        /// Get Stored Procedures List
        /// </summary>
        /// <remarks>Get an array of all stored procedures</remarks>
        /// <param name="operations"></param>
        /// <param name="ridDB"></param>
        /// <param name="ridColl"></param>
        /// <response code="200">OK</response>
        /// <response code="404">Not Found - This means the resource feed you tried to read did not exist.</response>
        /// <response code="429">TooManyRequests - This means you have exceeded the number of request units per second. </response>
        /// <response code="500">Internal Server Error</response>
        /// <returns>StoredProcedures</returns>
        [Metadata("Get Stored Procedures List")]
        [Route("{DatabaseId}/colls/{CollectioId}/sprocs")]
        [SwaggerOperation("GetListOfStoredProcedures")]
        public IList<StoredProcedure> GetListOfStoredProcedures(
           [Metadata(nameof(IDocDbSpApi))] IDocDbSpApi operations,
           [Metadata("Database ID")] string ridDB,
           [Metadata("CollectionId ")] string ridColl)
        {
            return
                Task.Factory.StartNew(
                    s => ((IDocDbSpApi)s).GetListOfStoredProceduresAsync(ridDB, ridColl), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default)
                    .Unwrap()
                    .GetAwaiter()
                    .GetResult();
        }
    }
}

 

If you would like access to the complete source code, please fill in the form below.  😎