/// <summary> /// Get the URI of an attachment view /// </summary> /// <param name="attachmentId"></param> /// <param name="viewId">default is "original"</param> /// <returns>uri</returns> public string GetAttachmentUri(string attachmentId, string viewId = "original") { if (attachmentId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "attachmentId"); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "v3/attachments/{attachmentId}/views/{viewId}").ToString(); url = url.Replace("{attachmentId}", Uri.EscapeDataString(attachmentId)); url = url.Replace("{vieWId}", Uri.EscapeDataString(viewId)); return url; }
public async Task <bool> SignOutUserAsync(string userId, string connectionName, CancellationToken cancellationToken = default(CancellationToken)) { if (connectionName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "connectionName"); } if (userId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "userId"); } // Construct URL var _baseUrl = BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/usertoken/SignOut?&userId={userId}&connectionName={connectionName}").ToString(); _url = _url.Replace("{connectionName}", System.Uri.EscapeDataString(connectionName)); _url = _url.Replace("{userId}", System.Uri.EscapeDataString(userId)); MicrosoftAppCredentials.TrustServiceUrl(_url); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Credentials if (Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (_statusCode == HttpStatusCode.OK) { return(true); } else { // TODO: some error situation should be logged return(false); } }
private IList<string> ResolveAssemblyDirectory(Assembly assembly) { var fullUriPath = new Uri(assembly.GetName().CodeBase).LocalPath.ToUpper(); var pathWithoutUnityFolder = fullUriPath.Replace(assembly.ManifestModule.Name.ToUpper(), ""); var path = pathWithoutUnityFolder + @"Unity"; if (!Directory.Exists(path)) return null; var files = Directory.GetFiles(path); return files; }
private static async Task <Tuple <HttpRequestMessage, HttpResponseMessage> > SetupAndSendHttpRequestGetConversationMember(ConnectorClient Client, string conversationId, string userId, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "v3/conversations/{conversationId}/members/{userId}").ToString(); _url = _url.Replace("{conversationId}", System.Uri.EscapeDataString(conversationId)); _url = _url.Replace("{userId}", System.Uri.EscapeDataString(userId)); // 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 (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); return(new Tuple <HttpRequestMessage, HttpResponseMessage>(_httpRequest, _httpResponse)); }
public void AutoConf() { PayloadDescription desc = new PayloadDescription(); string assembly=Assembly.GetExecutingAssembly().CodeBase; if (Uri.IsWellFormedUriString(assembly,UriKind.Absolute)) { assembly = new Uri(assembly).AbsolutePath; assembly = assembly.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar); } desc.AssemblyFullName = Path.GetFileName(assembly); desc.Class = typeof(HostTest).FullName; Assert.AreEqual(assembly+".config", desc.ConfigurationFile, "Config file should match default name"); Assert.AreEqual(Path.GetDirectoryName(assembly), desc.BinaryFolder, "binary folder should be assembly folder"); }
private string ConstructUrl(Guid subscriptionId) { var baseUrl = this.BaseUri.AbsoluteUri; var url = new System.Uri(new System.Uri(baseUrl + (baseUrl.EndsWith("/", StringComparison.OrdinalIgnoreCase) ? string.Empty : "/")), "subscriptions/{subscriptionId}/gateway/products").ToString(); url = url.Replace("{subscriptionId}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(subscriptionId, this.SerializationSettings).Trim('"'))); List <string> queryParameters = new List <string>(); if (queryParameters.Count > 0) { url += "?" + string.Join("&", queryParameters); } return(url); }
/// <summary> /// Our site wide search action method /// </summary> public JsonResult GetVimeoData(string vimeoUrl) { if (!vimeoUrl.StartsWith("http://www.vimeo.com/") && !vimeoUrl.StartsWith("http://vimeo.com/")) { throw new Exception("Not a valid vimeo url"); } //http://www.vimeo.com/20278551?ab = /20278551 var videoUriWithoutQuery = new Uri(vimeoUrl).AbsolutePath; var videoID = videoUriWithoutQuery.Replace("/",""); var vimeoData = new MediaService().GetVimeoVideoData(videoID); return Json(vimeoData); }
public async Task SendEmulateOAuthCardsAsync(bool emulateOAuthCards) { bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("emulateOAuthCards", emulateOAuthCards); ServiceClientTracing.Enter(_invocationId, this, "SendEmulateOAuthCards", tracingParameters); } var cancellationToken = default(CancellationToken); // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/usertoken/emulateOAuthCards?emulate={emulate}").ToString(); _url = _url.Replace("{emulate}", emulateOAuthCards.ToString()); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); MicrosoftAppCredentials.TrustServiceUrl(_url); // Set Credentials if (Client.Credentials != null) { await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } }
internal static void ExecuteCommand (IProgressStatus monitor, string registryPath, string startupDir, string name, params string[] args) { string asm = new Uri (typeof(SetupProcess).Assembly.CodeBase).LocalPath; string verboseParam = monitor.LogLevel.ToString (); // Arguments string StringBuilder sb = new StringBuilder (); sb.Append (verboseParam).Append (' ').Append (name); foreach (string arg in args) sb.Append (" \"").Append (arg).Append ("\""); Process process = new Process (); if (Util.IsWindows) process.StartInfo = new ProcessStartInfo (asm, sb.ToString ()); else { asm = asm.Replace(" ", @"\ "); process.StartInfo = new ProcessStartInfo ("mono", "--debug " + asm + " " + sb.ToString ()); } process.StartInfo.WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardInput = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.EnableRaisingEvents = true; try { process.Start (); } catch (Exception ex) { Console.WriteLine (ex); throw; } process.StandardInput.WriteLine (registryPath); process.StandardInput.WriteLine (startupDir); process.StandardInput.Flush (); // string rr = process.StandardOutput.ReadToEnd (); // Console.WriteLine (rr); StringCollection progessLog = new StringCollection (); ProcessProgressStatus.MonitorProcessStatus (monitor, process.StandardOutput, progessLog); process.WaitForExit (); if (process.ExitCode != 0) throw new ProcessFailedException (progessLog); }
// Add value to list private static bool AppendValue(string value, List <string> domains) { string domain = value .Replace("www.", "").ToLower(); // Remove search results if ( domain.Contains("google") || domain.Contains("bing") || domain.Contains("yandex") || domain.Contains("duckduckgo")) { return(false); } // If cookie value if (domain .StartsWith(".")) { domain = domain.Substring(1); } // Get hostname from url try { domain = new System.Uri(domain).Host; } catch (System.UriFormatException) { } // Remove .com, .org domain = System.IO.Path.GetFileNameWithoutExtension(domain); domain = domain.Replace(".com", "").Replace(".org", ""); // Check if domain already exists in list foreach (string domainValue in domains) { if (domain.ToLower().Replace(" ", "").Contains(domainValue.ToLower().Replace(" ", ""))) { return(false); } } // Convert first char to upper-case domain = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(domain); domains.Add(domain); return(true); }
/// <summary> /// Get a Url's parameters leaving them url encoded /// </summary> /// <param name="urlString">The query string</param> /// <returns></returns> public static Dictionary<string, string> ParseQueryString(string urlString) { string queryString = new Uri(urlString).Query; Dictionary<string, string> kVParms = new Dictionary<string, string>(); queryString.Replace("?", ""); string[] keyValPairing = queryString.Split('&', '='); if ((keyValPairing.Length == 0) || (keyValPairing.Length % 2 != 0)) { throw new Exception("Invalid input Url"); } keyValPairing[0] = keyValPairing[0].TrimStart('?'); for (int i = 0; i < keyValPairing.Length - 1; i++) { kVParms.Add(keyValPairing[i], keyValPairing[i + 1]); } return kVParms; }
public async Task <HttpOperationResponse <object> > CustomUpdateProductWithHttpMessagesAsync(System.Guid subscriptionId, System.Guid productId, string name = default(string), string key = default(string), string description = default(string), string providerId = default(string), bool?apiKeyRequired = default(bool?), bool?clientCredentialRequired = default(bool?), string openidConfigIssuer = default(string), string openidConfigCustomUrl = default(string), bool?providerApprovalRequired = default(bool?), string applicationId = default(string), string productTerms = default(string), string visibility = default(string), IList <System.Guid?> apiIds = default(IList <System.Guid?>), Stream logo = default(Stream), Stream documentation = default(Stream), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(CultureInfo.InvariantCulture); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("subscriptionId", subscriptionId); tracingParameters.Add("key", key); tracingParameters.Add("name", name); tracingParameters.Add("description", description); tracingParameters.Add("providerId", providerId); tracingParameters.Add("apiKeyRequired", apiKeyRequired); tracingParameters.Add("providerApprovalRequired", providerApprovalRequired); tracingParameters.Add("productTerms", productTerms); tracingParameters.Add("visibility", visibility); tracingParameters.Add("apiIds", apiIds); tracingParameters.Add("logo", logo); tracingParameters.Add("documentation", documentation); tracingParameters.Add("clientCredentialRequired", clientCredentialRequired); tracingParameters.Add("openidConfigIssuer", openidConfigIssuer); tracingParameters.Add("openidConfigCustomUrl", openidConfigCustomUrl); tracingParameters.Add("applicationId", applicationId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "UpdateProduct", tracingParameters); } // Construct URL var baseUrl = this.BaseUri.AbsoluteUri; var url = new System.Uri(new System.Uri(baseUrl + (baseUrl.EndsWith("/") ? string.Empty : "/")), "subscriptions/{subscriptionId}/gateway/products/{productId}").ToString(); url = url.Replace("{subscriptionId}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(subscriptionId, this.SerializationSettings).Trim('"'))); url = url.Replace("{productId}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(productId, this.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; MultipartFormDataContent multiPartContent = new MultipartFormDataContent(); if (name != null) { StringContent nameContent = new StringContent(name, System.Text.Encoding.UTF8); multiPartContent.Add(nameContent, "name"); } if (key != null) { StringContent keyContent = new StringContent(key, System.Text.Encoding.UTF8); multiPartContent.Add(keyContent, "key"); } if (description != null) { StringContent descriptionContent = new StringContent(description, System.Text.Encoding.UTF8); multiPartContent.Add(descriptionContent, "description"); } if (providerId != null) { StringContent providerIdContent = new StringContent(providerId, System.Text.Encoding.UTF8); multiPartContent.Add(providerIdContent, "providerId"); } if (apiKeyRequired != null) { StringContent isApiKeyRequired = new StringContent(SafeJsonConvert.SerializeObject(apiKeyRequired, this.SerializationSettings).Trim('"'), System.Text.Encoding.UTF8); multiPartContent.Add(isApiKeyRequired, "apiKeyRequired"); } if (clientCredentialRequired != null) { StringContent clientCredentialRequiredContent = new StringContent(SafeJsonConvert.SerializeObject(clientCredentialRequired, this.SerializationSettings).Trim('"'), System.Text.Encoding.UTF8); multiPartContent.Add(clientCredentialRequiredContent, "clientCredentialRequired"); } if (openidConfigIssuer != null) { StringContent productTermsContent = new StringContent(productTerms, System.Text.Encoding.UTF8); multiPartContent.Add(productTermsContent, "productTerms"); } if (openidConfigCustomUrl != null) { StringContent openidConfigCustomUrlContent = new StringContent(openidConfigCustomUrl, System.Text.Encoding.UTF8); multiPartContent.Add(openidConfigCustomUrlContent, "openidConfigCustomUrl"); } if (providerApprovalRequired != null) { StringContent isProviderApprovalRequired = new StringContent(SafeJsonConvert.SerializeObject(providerApprovalRequired, this.SerializationSettings).Trim('"'), System.Text.Encoding.UTF8); multiPartContent.Add(isProviderApprovalRequired, "providerApprovalRequired"); } if (applicationId != null) { StringContent applicationIdContent = new StringContent(applicationId, System.Text.Encoding.UTF8); multiPartContent.Add(applicationIdContent, "applicationId"); } if (productTerms != null) { StringContent productTermsContent = new StringContent(productTerms, System.Text.Encoding.UTF8); multiPartContent.Add(productTermsContent, "productTerms"); } if (visibility != null) { StringContent visibilityContent = new StringContent(SafeJsonConvert.SerializeObject(visibility, this.SerializationSettings).Trim('"'), System.Text.Encoding.UTF8); multiPartContent.Add(visibilityContent, "visibility"); } if (apiIds != null) { int i = 0; foreach (var apiId in apiIds) { var productIdContent = new StringContent(apiId.ToString()); multiPartContent.Add(productIdContent, $"apiIds[{i}]"); i++; } } if (logo != null) { StreamContent logoContent = new StreamContent(logo); logoContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); ContentDispositionHeaderValue logoContentDispositionHeaderValue = new ContentDispositionHeaderValue("form-data"); logoContentDispositionHeaderValue.Name = "logo"; // get filename from stream if it's a file otherwise, just use 'unknown' var logoFileStream = logo as FileStream; var logoFileName = (logoFileStream != null ? logoFileStream.Name : null) ?? "unknown"; if (System.Linq.Enumerable.Any(logoFileName, c => c > 127)) { // non ASCII chars detected, need UTF encoding: logoContentDispositionHeaderValue.FileNameStar = logoFileName; } else { // ASCII only logoContentDispositionHeaderValue.FileName = logoFileName; } logoContent.Headers.ContentDisposition = logoContentDispositionHeaderValue; multiPartContent.Add(logoContent, "logo"); } if (documentation != null) { StreamContent documentationContent = new StreamContent(documentation); documentationContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); ContentDispositionHeaderValue documentationContentDispositionHeaderValue = new ContentDispositionHeaderValue("form-data"); documentationContentDispositionHeaderValue.Name = "documentation"; // get filename from stream if it's a file otherwise, just use 'unknown' var documentationfileStream = documentation as FileStream; var documentationfileName = (documentationfileStream != null ? documentationfileStream.Name : null) ?? "unknown"; if (System.Linq.Enumerable.Any(documentationfileName, c => c > 127)) { // non ASCII chars detected, need UTF encoding: documentationContentDispositionHeaderValue.FileNameStar = documentationfileName; } else { // ASCII only documentationContentDispositionHeaderValue.FileName = documentationfileName; } documentationContent.Headers.ContentDisposition = documentationContentDispositionHeaderValue; multiPartContent.Add(documentationContent, "documentation"); } httpRequest.Content = multiPartContent; // Set Credentials if (this.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string responseContent = null; if ((int)statusCode != 200 && (int)statusCode != 400 && (int)statusCode != 404 && (int)statusCode != 409 && (int)statusCode != 422) { 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 <object>(); result.Request = httpRequest; result.Response = httpResponse; // Deserialize Response if ((int)statusCode == 200) { responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { result.Body = SafeJsonConvert.DeserializeObject <ProductListModel>(responseContent, this.DeserializationSettings); } catch (JsonException ex) { httpRequest.Dispose(); if (httpResponse != null) { httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", responseContent, ex); } } // Deserialize Response if ((int)statusCode == 400) { responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { result.Body = SafeJsonConvert.DeserializeObject <string>(responseContent, this.DeserializationSettings); } catch (JsonException ex) { httpRequest.Dispose(); if (httpResponse != null) { httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", responseContent, ex); } } // Deserialize Response if ((int)statusCode == 409) { responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { result.Body = SafeJsonConvert.DeserializeObject <IDictionary <string, IList <string> > >(responseContent, this.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); }
private static string GetUncFileName(string song) { string uncFilePath = new Uri(song).LocalPath; uncFilePath = uncFilePath.Replace("\\\\localhost\\", " ").Trim(); return uncFilePath; }
private static string RemoveDuplicateSlashes(string url) { var path = new Uri(url).AbsolutePath; return path.Contains("//") ? url.Replace(path, path.Replace("//", "/")) : url; }
/// <summary> /// Gets the dataset metadata for the specifeid dataset id /// </summary> /// <param name='dataSetId'> /// The dataset id /// </param> /// <param name='token'> /// The dataset id /// </param> /// <param name='query'> /// The dataset id /// </param> /// <param name='offset'> /// The dataset id /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <HttpOperationResponse <Models.Search> > ExecuteSearchWithHttpMessagesAsync(int?searchId, string query, int?offset, int?limit, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (searchId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "searchId"); } if (offset == null) { offset = 0; } if (limit == null) { offset = 10; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object> { { "searchId", searchId }, { "query", query }, { "cancellationToken", cancellationToken } }; ServiceClientTracing.Enter(_invocationId, this, "ExecuteSearch", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/v1/dealers/search/{searchId}?query={query}&offset={offset}&limit={limit}").ToString(); _url = _url.Replace("{searchId}", System.Uri.EscapeDataString(searchId.ToString())); _url = _url.Replace("{query}", query == null ? "" : System.Uri.EscapeDataString(query)); _url = _url.Replace("{offset}", System.Uri.EscapeDataString(offset.ToString())); _url = _url.Replace("{limit}", System.Uri.EscapeDataString(limit.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 (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { 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 <Models.Search> { Request = _httpRequest, Response = _httpResponse }; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <Models.Search>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
/// <summary> /// GetAttachmentInfo. /// </summary> /// <remarks> /// Get AttachmentInfo structure describing the attachment views. /// </remarks> /// <param name='attachmentId'> /// attachment id. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code. /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response. /// </exception> /// <exception cref="ValidationException"> /// Thrown when an input value does not match the expected data type, range or pattern. /// </exception> /// <exception cref="System.ArgumentNullException"> Thrown when a required parameter is null. </exception> /// <returns> /// A response object containing the response body and response headers. /// </returns> public async Task <HttpOperationResponse <AttachmentInfo> > GetAttachmentInfoWithHttpMessagesAsync(string attachmentId, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (attachmentId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "attachmentId"); } // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(CultureInfo.InvariantCulture); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("attachmentId", attachmentId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, this, "GetAttachmentInfo", tracingParameters); } // Construct URL var baseUrl = Client.BaseUri.AbsoluteUri; var url = new System.Uri(new System.Uri(baseUrl + (baseUrl.EndsWith("/", System.StringComparison.InvariantCulture) ? string.Empty : "/")), "v3/attachments/{attachmentId}").ToString(); url = url.Replace("{attachmentId}", System.Uri.EscapeDataString(attachmentId)); // 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 (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string responseContent = null; if ((int)statusCode != 200) { var ex = new ErrorResponseException($"Operation returned an invalid status code '{statusCode}'"); try { responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <ErrorResponse>(responseContent, Client.DeserializationSettings); if (errorBody != null) { ex.Body = errorBody; } } catch (JsonException) { // Ignore the exception } 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 <AttachmentInfo>(); result.Request = httpRequest; result.Response = httpResponse; // Deserialize Response if ((int)statusCode == 200) { responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <AttachmentInfo>(responseContent, Client.DeserializationSettings); } catch (JsonException ex) { httpRequest.Dispose(); if (httpResponse != null) { httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", responseContent, ex); } } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return(result); }
public async Task <string> GetSignInLinkAsync(IActivity activity, string connectionName, CancellationToken cancellationToken = default(CancellationToken)) { if (connectionName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "connectionName"); } if (activity == null) { throw new ValidationException(ValidationRules.CannotBeNull, "activity"); } bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("activity", activity); tracingParameters.Add("connectionName", connectionName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetSignInLinkAsync", tracingParameters); } var tokenExchangeState = new TokenExchangeState() { ConnectionName = connectionName, Conversation = new ConversationReference() { ActivityId = activity.Id, Bot = activity.Recipient, // Activity is from the user to the bot ChannelId = activity.ChannelId, Conversation = activity.Conversation, ServiceUrl = activity.ServiceUrl, User = activity.From }, MsAppId = (Client.Credentials as MicrosoftAppCredentials)?.MicrosoftAppId }; var serializedState = JsonConvert.SerializeObject(tokenExchangeState); var encodedState = Encoding.UTF8.GetBytes(serializedState); var finalState = Convert.ToBase64String(encodedState); // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/botsignin/getsigninurl?&state={state}").ToString(); _url = _url.Replace("{state}", finalState); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } cancellationToken.ThrowIfCancellationRequested(); if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (_statusCode == HttpStatusCode.OK) { var link = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); return(link); } return(String.Empty); }
/// <summary> /// Change reference to adoxio_applications /// </summary> /// <param name='adoxioApplicationid'> /// key: adoxio_applicationid /// </param> /// <param name='fieldname'> /// key: fieldname /// </param> /// <param name='odataid'> /// reference value /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="OdataerrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <HttpOperationResponse> ChangeReferenceWithHttpMessagesAsync(string adoxioApplicationid, string fieldname, Odataid odataid = default(Odataid), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (adoxioApplicationid == null) { throw new ValidationException(ValidationRules.CannotBeNull, "adoxioApplicationid"); } if (fieldname == null) { throw new ValidationException(ValidationRules.CannotBeNull, "fieldname"); } if (odataid != null) { odataid.Validate(); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("adoxioApplicationid", adoxioApplicationid); tracingParameters.Add("fieldname", fieldname); tracingParameters.Add("odataid", odataid); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ChangeReference", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "adoxio_applications({adoxio_applicationid})/{fieldname}/$ref").ToString(); _url = _url.Replace("{adoxio_applicationid}", System.Uri.EscapeDataString(adoxioApplicationid)); _url = _url.Replace("{fieldname}", System.Uri.EscapeDataString(fieldname)); // 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 (odataid != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(odataid, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204) { var ex = new OdataerrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Odataerror _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <Odataerror>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } 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); }
public async Task <AzureOperationResponse <string> > GetContentWithHttpMessagesAsync(string resourceGroupName, string automationAccountName, string runbookName, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$"); } } if (automationAccountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "automationAccountName"); } if (runbookName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "runbookName"); } //string apiVersion = "2015-10-31"; string apiVersion = "2017-05-15-preview"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccountName", automationAccountName); tracingParameters.Add("runbookName", runbookName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetContent", tracingParameters); } // Construct URL string _baseUrl = Client.BaseUri.AbsoluteUri; string _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/runbooks/{runbookName}/content").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{automationAccountName}", System.Uri.EscapeDataString(automationAccountName)); _url = _url.Replace("{runbookName}", System.Uri.EscapeDataString(runbookName)); List <string> _queryParameters = new List <string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach (KeyValuePair <string, List <string> > _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 (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { CloudException ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result AzureOperationResponse <string> _result = new AzureOperationResponse <string>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { //Custom: No deserialize, just return string _result.Body = _responseContent; //Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<string>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
public static string CalculateRelativePathToSlimjimPackages(string packagesPath, string csProjPath) { var relativeUri = new Uri(csProjPath).MakeRelativeUri(new Uri(packagesPath)).OriginalString; return relativeUri.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar); }
private bool IsExternalLink(string url) { try { var link = new Uri(url).Host; link = link.Replace("www.", string.Empty); return !link.StartsWith(_hostOfOriginalUrl); } catch (FormatException) { return false; } }
public async Task <HttpOperationResponse <Stream> > DeleteTournamentWithHttpMessagesAsync(string id, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("id", id); tracingParameters.Add("api_key", Client.ApiKey); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "DeleteCountry", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/Countries/{id}").ToString(); _url = _url.Replace("{id}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(id, Client.SerializationSettings).Trim('"'))); List <string> _queryParameters = new List <string>(); if (Client.ApiKey != null) { _queryParameters.Add(string.Format("api_key={0}", System.Uri.EscapeDataString(Client.ApiKey))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // 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; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, 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 <Stream>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _result.Body = await _httpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
public async Task <HttpOperationResponse <object> > GetCandlesHistoryFromDbWithHttpMessagesAsync(string assetPairId, CandlePriceType priceType, CandleTimeInterval timeInterval, DateTime fromMoment, DateTime toMoment, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (assetPairId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "assetPairId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("assetPairId", assetPairId); tracingParameters.Add("priceType", priceType); tracingParameters.Add("timeInterval", timeInterval); tracingParameters.Add("fromMoment", fromMoment); tracingParameters.Add("toMoment", toMoment); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetCandlesHistoryFromDb", tracingParameters); } // Construct URL var _baseUrl = BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/CandlesHistory/db/{assetPairId}/{priceType}/{timeInterval}/{fromMoment}/{toMoment}").ToString(); _url = _url.Replace("{assetPairId}", System.Uri.EscapeDataString(assetPairId)); _url = _url.Replace("{priceType}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(priceType, SerializationSettings).Trim('"'))); _url = _url.Replace("{timeInterval}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(timeInterval, SerializationSettings).Trim('"'))); _url = _url.Replace("{fromMoment}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(fromMoment, SerializationSettings).Trim('"'))); _url = _url.Replace("{toMoment}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(toMoment, 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; // 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 && (int)_statusCode != 400) { 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 <object>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject <CandlesHistoryResponseModel>(_responseContent, DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 400) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject <ErrorResponse>(_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); }
public static async Task <AzureOperationResponse <Cluster> > BeginUpdateWithHttpMessagesAsync(this ServiceFabricManagementClient sfManagementClient, string resourceGroupName, string clusterName, dynamic parameters, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (clusterName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "clusterName"); } if (sfManagementClient.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "sfManagementClient.SubscriptionId"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } string apiVersion = "2020-03-01"; // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("clusterName", clusterName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(invocationId, sfManagementClient, "BeginUpdate", tracingParameters); } // Construct URL var baseUrl = sfManagementClient.BaseUri.AbsoluteUri; var url = new System.Uri(new System.Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabric/clusters/{clusterName}").ToString(); url = url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); url = url.Replace("{clusterName}", System.Uri.EscapeDataString(clusterName)); url = url.Replace("{subscriptionId}", System.Uri.EscapeDataString(sfManagementClient.SubscriptionId)); List <string> _queryParameters = new List <string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { url += (url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var httpRequest = new HttpRequestMessage(); HttpResponseMessage httpResponse = null; httpRequest.Method = new HttpMethod("PATCH"); httpRequest.RequestUri = new System.Uri(url); // Set Headers if (sfManagementClient.GenerateClientRequestId != null && sfManagementClient.GenerateClientRequestId.Value) { httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (sfManagementClient.AcceptLanguage != null) { if (httpRequest.Headers.Contains("accept-language")) { httpRequest.Headers.Remove("accept-language"); } httpRequest.Headers.TryAddWithoutValidation("accept-language", sfManagementClient.AcceptLanguage); } if (customHeaders != null) { foreach (var _header in customHeaders) { if (httpRequest.Headers.Contains(_header.Key)) { httpRequest.Headers.Remove(_header.Key); } httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string requestContent = null; if (parameters != null) { var dynamicSerializationSettings = sfManagementClient.SerializationSettings.DeepCopy(); dynamicSerializationSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver(); requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, dynamicSerializationSettings); httpRequest.Content = new StringContent(requestContent, System.Text.Encoding.UTF8); httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (sfManagementClient.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await sfManagementClient.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await sfManagementClient.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string responseContent = null; if ((int)statusCode != 200 && (int)statusCode != 202) { var ex = new ErrorModelException(string.Format("Operation returned an invalid status code '{0}'", statusCode)); try { responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorModel _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <ErrorModel>(responseContent, sfManagementClient.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } 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 AzureOperationResponse <Cluster>(); result.Request = httpRequest; result.Response = httpResponse; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)statusCode == 200) { responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <Cluster>(responseContent, sfManagementClient.DeserializationSettings); } catch (JsonException ex) { httpRequest.Dispose(); if (httpResponse != null) { httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", responseContent, ex); } } // Deserialize Response if ((int)statusCode == 202) { responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <Cluster>(responseContent, sfManagementClient.DeserializationSettings); } catch (JsonException ex) { httpRequest.Dispose(); if (httpResponse != null) { httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", responseContent, ex); } } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return(result); }
/// <summary> /// Stops the specified connection monitor. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group containing Network Watcher. /// </param> /// <param name='networkWatcherName'> /// The name of the Network Watcher resource. /// </param> /// <param name='connectionMonitorName'> /// The name of the connection monitor. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <AzureOperationResponse> BeginStopWithHttpMessagesV1Async(string resourceGroupName, string networkWatcherName, string connectionMonitorName, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (networkWatcherName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "networkWatcherName"); } if (connectionMonitorName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "connectionMonitorName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2019-06-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("networkWatcherName", networkWatcherName); tracingParameters.Add("connectionMonitorName", connectionMonitorName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginStop", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/connectionMonitors/{connectionMonitorName}/stop").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{networkWatcherName}", System.Uri.EscapeDataString(networkWatcherName)); _url = _url.Replace("{connectionMonitorName}", System.Uri.EscapeDataString(connectionMonitorName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List <string> _queryParameters = new List <string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } 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 AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
/// <summary> /// Create a system topic. /// </summary> /// <remarks> /// Asynchronously creates a new topic with the specified parameters. /// </remarks> /// <param name='_ResourceGroupName'> /// The name of the resource group within the user's subscription. /// </param> /// <param name='_SystemTopicName'> /// Name of the topic. /// </param> /// <param name='_SystemTopicInfo'> /// System Topic information. /// </param> /// <param name='_FinalTopicInfo'> /// The resulting System topic if successfully created. /// </param> /// <param name='_ErrorMessageAction'> /// Method to write exceptions to. /// </param> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public bool CreateOrUpdate(string _ResourceGroupName, string _SystemTopicName, SystemTopic _SystemTopicInfo, out SystemTopic _FinalTopicInfo, Action <string> _ErrorMessageAction = null) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (_ResourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (_SystemTopicName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "topicName"); } if (_SystemTopicInfo == null) { throw new ValidationException(ValidationRules.CannotBeNull, "topicInfo"); } if (_SystemTopicInfo != null) { _SystemTopicInfo.Validate(); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/systemTopics/{systemTopicName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(_ResourceGroupName)); _url = _url.Replace("{systemTopicName}", System.Uri.EscapeDataString(_SystemTopicName)); List <string> _queryParameters = new List <string>(); if (Client.ApiVersion != null) { _queryParameters.Add(API_VERSION); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Serialize Request string _requestContent = null; if (_SystemTopicInfo != null) { _requestContent = JsonConvert.SerializeObject(_SystemTopicInfo, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.Indented }); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials CancellationToken CancellationToken = new CancellationToken(); CancellationToken.ThrowIfCancellationRequested(); Client.Credentials.ProcessHttpRequestAsync(_httpRequest, CancellationToken); Task <HttpResponseMessage> Response = Client.HttpClient.SendAsync(_httpRequest, CancellationToken); Response.Wait(); _httpResponse = Response.Result; Response.Dispose(); string _responseContent; if (_httpResponse.StatusCode == HttpStatusCode.OK || _httpResponse.StatusCode == HttpStatusCode.Created) { Task <string> ContentReadTask = _httpResponse.Content.ReadAsStringAsync(); ContentReadTask.Wait(); _responseContent = ContentReadTask.Result; ContentReadTask.Dispose(); try { _FinalTopicInfo = JsonConvert.DeserializeObject <SystemTopic>(_responseContent); return(true); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } else { Task <string> ContentReadTask = _httpResponse.Content.ReadAsStringAsync(); ContentReadTask.Wait(); _responseContent = ContentReadTask.Result; _ErrorMessageAction?.Invoke(_responseContent); ContentReadTask.Dispose(); } _FinalTopicInfo = null; return(false); }
/// <summary> /// Create a new SourceLineNumberCollection from a URI. /// </summary> /// <param name="uri">The URI.</param> /// <returns>The new SourceLineNumberCollection.</returns> public static SourceLineNumberCollection FromUri(string uri) { if (null == uri || 0 == uri.Length) { return null; } string localPath = new Uri(uri).LocalPath; // make the local path really look like a normal local path if (localPath.StartsWith(Path.AltDirectorySeparatorChar.ToString(), StringComparison.Ordinal)) { localPath = localPath.Substring(1); } localPath = localPath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar); return new SourceLineNumberCollection(localPath); }
public async Task <TokenResponse> GetUserTokenAsync(string userId, string connectionName, string magicCode, CancellationToken cancellationToken = default(CancellationToken)) { if (connectionName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "connectionName"); } if (userId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "userId"); } // Construct URL var _baseUrl = BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/usertoken/GetToken?userId={userId}&connectionName={connectionName}{magicCodeParam}").ToString(); _url = _url.Replace("{connectionName}", System.Uri.EscapeDataString(connectionName)); _url = _url.Replace("{userId}", System.Uri.EscapeDataString(userId)); if (!string.IsNullOrEmpty(magicCode)) { _url = _url.Replace("{magicCodeParam}", $"&code={System.Uri.EscapeDataString(magicCode)}"); } else { _url = _url.Replace("{magicCodeParam}", String.Empty); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); MicrosoftAppCredentials.TrustServiceUrl(_url); // Set Credentials if (Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if (_statusCode == HttpStatusCode.OK) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { var tokenResponse = Rest.Serialization.SafeJsonConvert.DeserializeObject <TokenResponse>(_responseContent); return(tokenResponse); } catch (JsonException) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } return(null); } } else if (_statusCode == HttpStatusCode.NotFound) { return(null); } else { // TODO: some error situation should be logged return(null); } }
/// <summary> /// Check file path availability /// </summary> /// <remarks> /// Check if a file path is available. /// </remarks> /// <param name='location'> /// The location /// </param> /// <param name='name'> /// Resource name to verify. /// </param> /// <param name='type'> /// Resource type used for verification. Possible values include: /// 'Microsoft.NetApp/netAppAccounts', /// 'Microsoft.NetApp/netAppAccounts/capacityPools', /// 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes', /// 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes/snapshots' /// </param> /// <param name='resourceGroup'> /// Resource group name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <AzureOperationResponse <CheckAvailabilityResponse> > CheckFilePathAvailabilityWithHttpMessagesAsync(string location, string name, string type, string resourceGroup, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { string apiVersion = "2021-02-01"; if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (location == null) { throw new ValidationException(ValidationRules.CannotBeNull, "location"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } if (type == null) { throw new ValidationException(ValidationRules.CannotBeNull, "type"); } if (resourceGroup == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroup"); } ResourceNameAvailabilityRequest body = new ResourceNameAvailabilityRequest(); if (name != null || type != null || resourceGroup != null) { body.Name = name; body.Type = type; body.ResourceGroup = resourceGroup; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("location", location); tracingParameters.Add("body", body); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CheckFilePathAvailability", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.NetApp/locations/{location}/checkFilePathAvailability").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{location}", System.Uri.EscapeDataString(location)); List <string> _queryParameters = new List <string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if (body != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(body, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse <CheckAvailabilityResponse>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <CheckAvailabilityResponse>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
/// <summary> /// The Generatevpnclientpackage operation generates Vpn client package for /// P2S client of the virtual network gateway in the specified resource group /// through Network resource provider. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayName'> /// The name of the virtual network gateway. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Generating Virtual Network Gateway Vpn /// client package operation through Network resource provider. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<string>> GeneratevpnclientpackageWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayName, VpnClientParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { #region 1. Send Async request to generate vpn client package // 1. Send Async request to generate vpn client package string baseUrl = NetworkManagementClient.BaseUri.ToString(); string apiVersion = NetworkManagementClient.ApiVersion; if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (virtualNetworkGatewayName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "virtualNetworkGatewayName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } // Construct URL var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/" + "providers/Microsoft.Network/virtualnetworkgateways/{virtualNetworkGatewayName}/generatevpnclientpackage").ToString(); url = url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); url = url.Replace("{virtualNetworkGatewayName}", Uri.EscapeDataString(virtualNetworkGatewayName)); url = url.Replace("{subscriptionId}", Uri.EscapeDataString(NetworkManagementClient.SubscriptionId)); url += "?" + string.Join("&", string.Format("api-version={0}", Uri.EscapeDataString(apiVersion))); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("POST"); httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); // Serialize Request string requestContent = JsonConvert.SerializeObject(parameters, NetworkManagementClient.SerializationSettings); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Set Credentials if (NetworkManagementClient.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await NetworkManagementClient.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request cancellationToken.ThrowIfCancellationRequested(); var client = this.NetworkManagementClient as NetworkManagementClient; HttpClient httpClient = client.HttpClient; HttpResponseMessage httpResponse = await httpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if ((int)statusCode != 202) { string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); throw new Exception(string.Format("Get-AzureRmVpnClientPackage Operation returned an invalid status code '{0}' with Exception:{1}", statusCode, string.IsNullOrEmpty(responseContent) ? "NotAvailable" : responseContent)); } // Create Result var result = new AzureOperationResponse<string>(); result.Request = httpRequest; result.Response = httpResponse; string locationResultsUrl = string.Empty; // Retrieve the location from LocationUri if (httpResponse.Headers.Contains("Location")) { locationResultsUrl = httpResponse.Headers.GetValues("Location").FirstOrDefault(); } else { throw new Exception(string.Format("Get-AzureRmVpnClientPackage Operation Failed as no valid Location header received in response!")); } if (string.IsNullOrEmpty(locationResultsUrl)) { throw new Exception(string.Format("Get-AzureRmVpnClientPackage Operation Failed as no valid Location header value received in response!")); } #endregion #region 2. Wait for Async operation to succeed and then Get the content i.e. VPN Client package Url from locationResults //Microsoft.WindowsAzure.Commands.Utilities.Common.TestMockSupport.Delay(60000); // 2. Wait for Async operation to succeed DateTime startTime = DateTime.UtcNow; DateTime giveUpAt = DateTime.UtcNow.AddMinutes(3); // Send the Get locationResults request for operaitonId till either we get StatusCode 200 or it time outs (3 minutes in this case) while (true) { HttpRequestMessage newHttpRequest = new HttpRequestMessage(); newHttpRequest.Method = new HttpMethod("GET"); newHttpRequest.RequestUri = new Uri(locationResultsUrl); if (NetworkManagementClient.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await NetworkManagementClient.Credentials.ProcessHttpRequestAsync(newHttpRequest, cancellationToken).ConfigureAwait(false); } HttpResponseMessage newHttpResponse = await httpClient.SendAsync(newHttpRequest, cancellationToken).ConfigureAwait(false); if ((int)newHttpResponse.StatusCode != 200) { if (DateTime.UtcNow > giveUpAt) { string newResponseContent = await newHttpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); throw new Exception(string.Format("Get-AzureRmVpnClientPackage Operation returned an invalid status code '{0}' with Exception:{1} while retrieving " + "the Vpnclient PackageUrl!", newHttpResponse.StatusCode, string.IsNullOrEmpty(newResponseContent) ? "NotAvailable" : newResponseContent)); } else { // Wait for 15 seconds before retrying Microsoft.WindowsAzure.Commands.Utilities.Common.TestMockSupport.Delay(15000); } } else { // Get the content i.e.VPN Client package Url from locationResults result.Body = newHttpResponse.Content.ReadAsStringAsync().Result; return result; } } #endregion }
public async Task <bool> SignOutUserAsync(string channelId, string userId, string connectionName, CancellationToken cancellationToken = default(CancellationToken)) { if (connectionName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "connectionName"); } if (userId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "userId"); } bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("userId", userId); tracingParameters.Add("connectionName", connectionName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "SignOutUserAsync", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/usertoken/SignOut?&userId={userId}&connectionName={connectionName}{channelIdParam}").ToString(); _url = _url.Replace("{connectionName}", System.Uri.EscapeDataString(connectionName)); _url = _url.Replace("{userId}", System.Uri.EscapeDataString(userId)); if (!string.IsNullOrEmpty(channelId)) { _url = _url.Replace("{channelIdParam}", $"&channelId={System.Uri.EscapeDataString(channelId)}"); } else { _url = _url.Replace("{channelIdParam}", String.Empty); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } cancellationToken.ThrowIfCancellationRequested(); if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); if (_statusCode == HttpStatusCode.OK) { return(true); } else { return(false); } }
/// <summary> /// fully resolves any relative pathing inside the URL, and other URL oddities /// </summary> string ResolveUrl(string url) { // resolve any relative pathing try { url = new Uri(url).AbsoluteUri; } catch (UriFormatException ex) { throw new ArgumentException("'" + url + "' does not appear to be a valid URL.", ex); } // remove any anchor tags from the end of URLs if (url.IndexOf("#") > -1) { string jump = Regex.Match(url, "/[^/]*?(?<jump>#[^/?.]+$)").Groups["jump"].Value; if (jump != "") url = url.Replace(jump, ""); } return url; }
public async Task <TokenResponse> GetUserTokenAsync(string channelId, string userId, string connectionName, string magicCode = null, CancellationToken cancellationToken = default(CancellationToken)) { if (connectionName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "connectionName"); } if (userId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "userId"); } bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("channelId", channelId); tracingParameters.Add("userId", userId); tracingParameters.Add("connectionName", connectionName); tracingParameters.Add("magicCode", magicCode); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetUserTokenAsync", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/usertoken/GetToken?userId={userId}&connectionName={connectionName}{magicCodeParam}{channelIdParam}").ToString(); _url = _url.Replace("{connectionName}", System.Uri.EscapeDataString(connectionName)); _url = _url.Replace("{userId}", System.Uri.EscapeDataString(userId)); if (!string.IsNullOrEmpty(magicCode)) { _url = _url.Replace("{magicCodeParam}", $"&code={System.Uri.EscapeDataString(magicCode)}"); } else { _url = _url.Replace("{magicCodeParam}", String.Empty); } if (!string.IsNullOrEmpty(channelId)) { _url = _url.Replace("{channelIdParam}", $"&channelId={System.Uri.EscapeDataString(channelId)}"); } else { _url = _url.Replace("{channelIdParam}", String.Empty); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } cancellationToken.ThrowIfCancellationRequested(); if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if (_statusCode == HttpStatusCode.OK) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { var tokenResponse = Rest.Serialization.SafeJsonConvert.DeserializeObject <TokenResponse>(_responseContent); return(tokenResponse); } catch (JsonException) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } return(null); } } else if (_statusCode == HttpStatusCode.NotFound) { return(null); } else { return(null); } }
/// <summary> /// Adds the provided images to the current project iteration /// </summary> /// <param name='projectId'> /// The project id. /// </param> /// <param name='imageData'> /// </param> /// <param name='tagIds'> /// The tags ids to associate with the image batch. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <HttpOperationResponse <CreateImageSummaryModel> > CreateImagesFromDataWithHttpMessagesAsync(System.Guid projectId, IEnumerable <Stream> imageData, IList <Guid> tagIds = default(IList <Guid>), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (imageData == null) { throw new ValidationException(ValidationRules.CannotBeNull, "imageData"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("projectId", projectId); tracingParameters.Add("tagIds", tagIds); tracingParameters.Add("imageData", imageData); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PostImages", tracingParameters); } // Construct URL var _baseUrl = BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "projects/{projectId}/images/image").ToString(); _url = _url.Replace("{projectId}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(projectId, SerializationSettings).Trim('"'))); List <string> _queryParameters = new List <string>(); if (tagIds != null) { if (tagIds.Count == 0) { _queryParameters.Add(string.Format("tagIds={0}", System.Uri.EscapeDataString(string.Empty))); } else { foreach (var _item in tagIds) { _queryParameters.Add(string.Format("tagIds={0}", System.Uri.EscapeDataString(_item.ToString() ?? string.Empty))); } } } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.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; System.Net.Http.MultipartFormDataContent _multiPartContent = new System.Net.Http.MultipartFormDataContent(); if (imageData != null) { foreach (var image in imageData) { System.Net.Http.StreamContent _imageData = new System.Net.Http.StreamContent(image); _imageData.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream"); FileStream _imageDataAsFileStream = image as FileStream; if (_imageDataAsFileStream != null) { System.Net.Http.Headers.ContentDispositionHeaderValue _contentDispositionHeaderValue = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data"); _contentDispositionHeaderValue.Name = "imageData"; _contentDispositionHeaderValue.FileName = _imageDataAsFileStream.Name; _imageData.Headers.ContentDisposition = _contentDispositionHeaderValue; } _multiPartContent.Add(_imageData, "imageData"); } } _httpRequest.Content = _multiPartContent; // 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 <CreateImageSummaryModel>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject <CreateImageSummaryModel>(_responseContent, DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
/// <summary> /// This method is used to retrieve the master key for the function app. Once this method is added in the web app OpenAPI /// specs, this method will call that in WebAppsOperations.cs instead. /// </summary> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>the master key of the function app.</returns> public async Task <string> GetMasterKeyAsync(CancellationToken cancellationToken = default(CancellationToken)) { string apiVersion = "2016-08-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); var tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("resourceGroupName", ResourceGroupName); tracingParameters.Add("name", Name); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Manager.Inner.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/functions/admin/masterkey").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(ResourceGroupName)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(Name)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Manager.Inner.SubscriptionId)); List <string> _queryParameters = new List <string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Manager.Inner.GenerateClientRequestId != null && Manager.Inner.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Manager.Inner.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Manager.Inner.AcceptLanguage); } // Serialize Request string _requestContent = null; // Set Credentials if (Manager.Inner.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Manager.Inner.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await((WebSiteManagementClient)Manager.Inner).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 CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <CloudError>(_responseContent, Manager.Inner.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { var map = Rest.Serialization.SafeJsonConvert.DeserializeObject <Dictionary <string, string> >(_responseContent, Manager.Inner.DeserializationSettings); return(map["masterKey"]); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } return(null); }
private void ButtonClicked(object sender, EventArgs e) { Project currentProject = GetSelectedProjects().ElementAt(0); var projects = _dte.Solution.GetAllNonWebProjects(); var names = from p in projects where p.UniqueName != currentProject.UniqueName select p.Name; ProjectSelector2 selector = new ProjectSelector2(names); bool? isSelected = selector.ShowDialog(); if (isSelected.HasValue && isSelected.Value) { WebJobCreator creator = new WebJobCreator(); var selectedProject = projects.First(p => p.Name == selector.SelectedProjectName); creator.AddReference(currentProject, selectedProject); var relativePath = new Uri(currentProject.FullName).MakeRelativeUri(new Uri(selectedProject.FullName)).ToString(); relativePath = relativePath.Replace("/", "\\"); creator.CreateFolders(currentProject, selector.Schedule, selector.SelectedProjectName, relativePath); // ensure that the NuGet package is installed in the project as well InstallWebJobsNuGetPackage(currentProject); } }
/// <summary> /// Change reference to adoxio_applications /// </summary> /// <param name='adoxioApplicationid'> /// key: adoxio_applicationid /// </param> /// <param name='fieldname'> /// key: fieldname /// </param> /// <param name='odataid'> /// reference value /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="OdataerrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <HttpOperationResponse <StatsResultResponse> > GetSavedQueryWithHttpMessagesAsync(string savedQueryid, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (savedQueryid == null) { throw new ValidationException(ValidationRules.CannotBeNull, "savedQueryid"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("savedQueryid", savedQueryid); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetSavedQueryWithHttpMessagesAsync", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "adoxio_applications?savedQuery={savedQueryid}").ToString(); _url = _url.Replace("{savedQueryid}", System.Uri.EscapeDataString(savedQueryid)); // 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 (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new OdataerrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Odataerror _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <Odataerror>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } 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 <StatsResultResponse>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <StatsResultResponse>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
public async Task <HttpOperationResponse <KubernetesList <TResource> > > ListClusterAnyResourceKindWithHttpMessagesAsync <TResource>(string group, string version, string plural, string continueParameter = null, string fieldSelector = null, string labelSelector = null, int?limit = null, string resourceVersion = null, int?timeoutSeconds = null, bool?watch = null, string pretty = null, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default) where TResource : IKubernetesObject { if (group == null) { throw new ValidationException(ValidationRules.CannotBeNull, "group"); } if (version == null) { throw new ValidationException(ValidationRules.CannotBeNull, "version"); } if (plural == null) { throw new ValidationException(ValidationRules.CannotBeNull, "plural"); } var namespaces = Client.ListNamespace(); // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("continueParameter", continueParameter); tracingParameters.Add("fieldSelector", fieldSelector); tracingParameters.Add("labelSelector", labelSelector); tracingParameters.Add("limit", limit); tracingParameters.Add("resourceVersion", resourceVersion); tracingParameters.Add("timeoutSeconds", timeoutSeconds); tracingParameters.Add("watch", watch); tracingParameters.Add("pretty", pretty); tracingParameters.Add("group", group); tracingParameters.Add("version", version); tracingParameters.Add("plural", plural); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListClusterAnyResourceKind", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "apis/{group}/{version}/{plural}").ToString(); if (string.IsNullOrEmpty(group)) { _url = _url.Replace("apis/{group}", "api"); } else { _url = _url.Replace("{group}", System.Uri.EscapeDataString(group)); } _url = _url.Replace("{version}", System.Uri.EscapeDataString(version)); _url = _url.Replace("{plural}", System.Uri.EscapeDataString(plural)); List <string> _queryParameters = new List <string>(); if (continueParameter != null) { _queryParameters.Add(string.Format("continue={0}", System.Uri.EscapeDataString(continueParameter))); } if (fieldSelector != null) { _queryParameters.Add(string.Format("fieldSelector={0}", System.Uri.EscapeDataString(fieldSelector))); } if (labelSelector != null) { _queryParameters.Add(string.Format("labelSelector={0}", System.Uri.EscapeDataString(labelSelector))); } if (limit != null) { _queryParameters.Add(string.Format("limit={0}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(limit, Client.SerializationSettings).Trim('"')))); } if (resourceVersion != null) { _queryParameters.Add(string.Format("resourceVersion={0}", System.Uri.EscapeDataString(resourceVersion))); } if (timeoutSeconds != null) { _queryParameters.Add(string.Format("timeoutSeconds={0}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(timeoutSeconds, Client.SerializationSettings).Trim('"')))); } if (watch != null) { _queryParameters.Add(string.Format("watch={0}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(watch, Client.SerializationSettings).Trim('"')))); } if (pretty != null) { _queryParameters.Add(string.Format("pretty={0}", System.Uri.EscapeDataString(pretty))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // 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 (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { 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 <KubernetesList <TResource> >(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject <KubernetesList <TResource> >(_responseContent, Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
/// <summary> /// This method is used to remove a function key from the function. This is part of the KUDU APIs. /// </summary> /// <param name="functionName">the name of the function</param> /// <param name="keyName">the name of the key to remove</param> /// <param name="cancellationToken">The cancellation token</param> public async Task RemoveFunctionKeyAsync(string functionName, string keyName, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); var tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("functionName", functionName); tracingParameters.Add("keyName", keyName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = string.Format("http://{0}", DefaultHostName().Replace("http://", "").Replace("https://", "")); var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "admin/functions/{name}/keys/{keyName}").ToString(); _url = _url.Replace("{name}", System.Uri.EscapeDataString(functionName)); _url = _url.Replace("{keyName}", System.Uri.EscapeDataString(keyName)); // 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 (Manager.Inner.GenerateClientRequestId != null && Manager.Inner.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Manager.Inner.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Manager.Inner.AcceptLanguage); } // Serialize Request string _requestContent = null; _requestContent = null; // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await kuduCredentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await((WebSiteManagementClient)Manager.Inner).HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 204) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <CloudError>(_responseContent, Manager.Inner.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } }
public async Task <HttpOperationResponse <object> > DeleteAnyResourceKindWithHttpMessagesAsync(string group, string version, string namespaceParameter, string plural, string name, V1DeleteOptions body = default(V1DeleteOptions), int?gracePeriodSeconds = default(int?), bool?orphanDependents = default(bool?), string propagationPolicy = default(string), string dryRun = default(string), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (group == null) { throw new ValidationException(ValidationRules.CannotBeNull, "group"); } if (version == null) { throw new ValidationException(ValidationRules.CannotBeNull, "version"); } if (namespaceParameter == null) { throw new ValidationException(ValidationRules.CannotBeNull, "namespaceParameter"); } if (plural == null) { throw new ValidationException(ValidationRules.CannotBeNull, "plural"); } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("body", body); tracingParameters.Add("gracePeriodSeconds", gracePeriodSeconds); tracingParameters.Add("orphanDependents", orphanDependents); tracingParameters.Add("propagationPolicy", propagationPolicy); tracingParameters.Add("dryRun", dryRun); tracingParameters.Add("group", group); tracingParameters.Add("version", version); tracingParameters.Add("namespaceParameter", namespaceParameter); tracingParameters.Add("plural", plural); tracingParameters.Add("name", name); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "DeleteNamespacedCustomObject", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), Pattern(group, namespaceParameter) + "/{name}").ToString(); _url = _url.Replace("{group}", System.Uri.EscapeDataString(group)); _url = _url.Replace("{version}", System.Uri.EscapeDataString(version)); _url = _url.Replace("{namespace}", System.Uri.EscapeDataString(namespaceParameter)); _url = _url.Replace("{plural}", System.Uri.EscapeDataString(plural)); _url = _url.Replace("{name}", System.Uri.EscapeDataString(name)); List <string> _queryParameters = new List <string>(); if (gracePeriodSeconds != null) { _queryParameters.Add(string.Format("gracePeriodSeconds={0}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(gracePeriodSeconds, Client.SerializationSettings).Trim('"')))); } if (orphanDependents != null) { _queryParameters.Add(string.Format("orphanDependents={0}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(orphanDependents, Client.SerializationSettings).Trim('"')))); } if (propagationPolicy != null) { _queryParameters.Add(string.Format("propagationPolicy={0}", System.Uri.EscapeDataString(propagationPolicy))); } if (dryRun != null) { _queryParameters.Add(string.Format("dryRun={0}", System.Uri.EscapeDataString(dryRun))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // 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; if (body != null) { _requestContent = SafeJsonConvert.SerializeObject(body, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = Client.GetHeader(body); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { 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 <object>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject <object>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }