public ApiResponse(IRestResponse response) : this() { StatusCode = response.StatusCode; switch (StatusCode) { case HttpStatusCode.OK: case HttpStatusCode.NoContent: //NOP- Nothing to deserialize break; default: DeserializeErrors(response.Content); break; } }
public override void Get(string identifier, out System.Net.HttpStatusCode code, out string message, object[] messageParameters) { base.Get(identifier, out code, out message, messageParameters); }
/// <summary> /// Restores the specified backed up data. This is an asynchronous operation. /// To know the status of this API call, use /// GetProtectedItemOperationResult API. /// </summary> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='fabricName'> /// Fabric name associated with the backed up items. /// </param> /// <param name='containerName'> /// Container name associated with the backed up items. /// </param> /// <param name='protectedItemName'> /// Backed up item to be restored. /// </param> /// <param name='recoveryPointId'> /// Recovery point ID which represents the backed up data to be restored. /// </param> /// <param name='parameters'> /// resource restore request /// </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="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> BeginTriggerWithHttpMessagesAsync(string vaultName, string resourceGroupName, string fabricName, string containerName, string protectedItemName, string recoveryPointId, RestoreRequestResource parameters, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (vaultName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "vaultName"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (fabricName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "fabricName"); } if (containerName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "containerName"); } if (protectedItemName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "protectedItemName"); } if (recoveryPointId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "recoveryPointId"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } string apiVersion = "2021-08-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("apiVersion", apiVersion); tracingParameters.Add("vaultName", vaultName); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("fabricName", fabricName); tracingParameters.Add("containerName", containerName); tracingParameters.Add("protectedItemName", protectedItemName); tracingParameters.Add("recoveryPointId", recoveryPointId); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginTrigger", 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.RecoveryServices/vaults/{vaultName}/backupFabrics/{fabricName}/protectionContainers/{containerName}/protectedItems/{protectedItemName}/recoveryPoints/{recoveryPointId}/restore").ToString(); _url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{fabricName}", System.Uri.EscapeDataString(fabricName)); _url = _url.Replace("{containerName}", System.Uri.EscapeDataString(containerName)); _url = _url.Replace("{protectedItemName}", System.Uri.EscapeDataString(protectedItemName)); _url = _url.Replace("{recoveryPointId}", System.Uri.EscapeDataString(recoveryPointId)); 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 (parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 202) { 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(); _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> /// Delete a hybrid runbook worker group. /// <see href="http://aka.ms/azureautomationsdk/hybridrunbookworkergroupoperations" /> /// </summary> /// <param name='resourceGroupName'> /// Name of an Azure Resource group. /// </param> /// <param name='automationAccountName'> /// The name of the automation account. /// </param> /// <param name='hybridRunbookWorkerGroupName'> /// The hybrid runbook worker group name /// </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> DeleteWithHttpMessagesAsync(string resourceGroupName, string automationAccountName, string hybridRunbookWorkerGroupName, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { 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 (hybridRunbookWorkerGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "hybridRunbookWorkerGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2020-01-13-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("hybridRunbookWorkerGroupName", hybridRunbookWorkerGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete", 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.Automation/automationAccounts/{automationAccountName}/hybridRunbookWorkerGroups/{hybridRunbookWorkerGroupName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{automationAccountName}", System.Uri.EscapeDataString(automationAccountName)); _url = _url.Replace("{hybridRunbookWorkerGroupName}", System.Uri.EscapeDataString(hybridRunbookWorkerGroupName)); _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("DELETE"); _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); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { 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); }
public ProfileServiceException(string message, System.Net.HttpStatusCode statusCode) : base(message) { StatusCode = statusCode; }
public TextResult(HttpStatusCode status, HttpRequestMessage request, object message) { _status = status; _message = message; _request = request; }
void client_DownloadCalendarStringCompleted(IAsyncResult r) { try { HttpWebRequest httpRequest = (HttpWebRequest)r.AsyncState; HttpWebResponse httpResoponse = (HttpWebResponse)httpRequest.EndGetResponse(r); System.Net.HttpStatusCode status = httpResoponse.StatusCode; if (status == System.Net.HttpStatusCode.OK) { String jsonString = new StreamReader(httpResoponse.GetResponseStream()).ReadToEnd(); ObservableCollection <CalendarListItemViewModel> tempItems = new ObservableCollection <CalendarListItemViewModel>(); using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString))) { //parse into jsonser var ser = new DataContractJsonSerializer(typeof(TraktCalendar[])); TraktCalendar[] obj = (TraktCalendar[])ser.ReadObject(ms); StorageController.saveObjectInMainFolder(obj, typeof(TraktCalendar[]), "upcomming.json"); foreach (TraktCalendar calendarDate in obj) { if ((DateTime.Parse(calendarDate.Date) - DateTime.Now).Days > 20) { break; } ObservableCollection <ListItemViewModel> tempEpisodes = new ObservableCollection <ListItemViewModel>(); foreach (TraktCalendarEpisode episode in calendarDate.Episodes) { tempEpisodes.Add(new ListItemViewModel() { Name = episode.Show.Title, ImageSource = episode.Episode.Images.Screen, Imdb = episode.Show.imdb_id + episode.Episode.Season + episode.Episode.Number, SubItemText = episode.Episode.Title, TruncateTitle = false, Tvdb = episode.Show.tvdb_id, Episode = episode.Episode.Number, Season = episode.Episode.Season }); } tempItems.Add(new CalendarListItemViewModel() { DateString = calendarDate.Date, Items = tempEpisodes }); } if (obj.Length == 00) { tempItems.Add(new CalendarListItemViewModel() { DateString = "No upcomming episodes", Items = new ObservableCollection <ListItemViewModel>() }); } App.UpcommingViewModel.CalendarItems = tempItems; System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => { this.indicator.IsVisible = false; App.UpcommingViewModel.NotifyPropertyChanged("LoadingStatus"); App.UpcommingViewModel.NotifyPropertyChanged("CalendarItems"); }); } } } catch (WebException) { ErrorManager.ShowConnectionErrorPopup(); } catch (TargetInvocationException) { ErrorManager.ShowConnectionErrorPopup(); } }
public AuthException(System.Net.HttpStatusCode statusCode, string message, Exception inner) : base(message, inner) => this.StatusCode = statusCode;
public static HttpResponseMessage GenerateErrorResponse(this HttpRequestMessage request, System.Net.HttpStatusCode statusCode, object o) { HttpResponseMessage response = null; ResponseConfiguration.MessageProvider.VetStatusCode(statusCode, o); response = request.CreateErrorResponse(statusCode, o.ToString()); return(response); }
private static HttpResponseMessage GenerateResponseInternal(this HttpRequestMessage request, System.Net.HttpStatusCode statusCode, object o) { HttpResponseMessage response = null; ResponseConfiguration.MessageProvider.VetStatusCode(statusCode, o); response = request.GenerateResponse(statusCode, o); return(response); }
public static HttpResponseMessage GenerateResponse(this HttpRequestMessage request, System.Net.HttpStatusCode statusCode, object o) { HttpResponseMessage response = null; if (!IsSuccessful(statusCode)) { response = request.GenerateErrorResponse(statusCode, o); } else { response = request.GenerateResponseInternal(statusCode, o); } return(response); }
public static HttpResponseMessage GenerateErrorResponse <T>(this HttpRequestMessage request, System.Net.HttpStatusCode statusCode, T t) { HttpResponseMessage response = null; ResponseConfiguration.MessageProvider.VetStatusCode(statusCode, t); string message; ResponseConfiguration.MessageProvider.GetError(statusCode, t, out message); response = request.CreateErrorResponse(statusCode, message); return(response); }
private static HttpResponseMessage GenerateResponseInternal <T>(this HttpRequestMessage request, System.Net.HttpStatusCode statusCode, T t) { HttpResponseMessage response = null; ResponseConfiguration.MessageProvider.VetStatusCode(statusCode, t); response = request.CreateResponse <T>(statusCode, t); return(response); }
private static bool IsSuccessful(System.Net.HttpStatusCode statusCode) { return(ResponseConfiguration.MessageProvider.IsSuccessful(statusCode)); }
public static HttpResponseMessage GenerateResponse(this HttpRequestMessage request, System.Net.HttpStatusCode statusCode, string message) { HttpResponseMessage response = null; // tag if statusCode not allowed response = request.CreateResponse(statusCode, message); return(response); }
private string SendRequest(string packet) { string stReturn = ""; //httppost for web objects // create the web request with the url to the web service HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(ucmEndpoint); httpReq.Headers.Add("SOAPAction: \"\""); httpReq.ContentType = "text/xml;charset=UTF-8"; httpReq.Accept = "text/xml"; httpReq.Method = "POST"; // add your credentials to the HttpWebRequest //httpReq.Credentials = new NetworkCredential(stUserID, stPswd); httpReq.Credentials = new NetworkCredential(userName, password); // Build XML request XmlDocument oRequest = new XmlDocument(); oRequest.LoadXml(packet); // Setup the Stream Stream oReqStream = httpReq.GetRequestStream(); oRequest.Save(oReqStream); oReqStream.Close(); // To avoid Cert warnings System.Net.ServicePointManager.ServerCertificateValidationCallback = (senderX, certificate, chain, sslPolicyErrors) => { return(true); }; // Send the request & get response WebResponse response = httpReq.GetResponse(); try { HttpWebResponse oTempResponse = (HttpWebResponse)response; System.Net.HttpStatusCode oStatusCode = oTempResponse.StatusCode; int iLoop = 1; // If we're not OK, try again 3 more times while (oStatusCode != HttpStatusCode.OK && iLoop < 3) { // Delay 2 minutes (120 milliseconds) and try again... System.Threading.Thread.Sleep(120000); // Store new values iLoop++; response = httpReq.GetResponse(); oTempResponse = (HttpWebResponse)response; oStatusCode = oTempResponse.StatusCode; } // If we eventually got something, process it. if (oStatusCode == HttpStatusCode.OK) { using (StreamReader rd = new StreamReader(response.GetResponseStream())) { stReturn = rd.ReadToEnd(); rd.Close(); // If it was mutli-part... if (oTempResponse.ContentType.Contains("multipart")) { // find the xml envelope stReturn = stReturn.Substring(stReturn.IndexOf("<?xml version="), stReturn.IndexOf("</env:Envelope>") + 15 - stReturn.IndexOf("<?xml version=")); } } } else { throw new Exception("Bad response received: '" + oTempResponse.StatusCode.ToString() + "' from request: " + packet); } } finally { if (response != null) { ((IDisposable)response).Dispose(); } } // Return the value return(stReturn); }
public HttpResponseMessage PostEntity([FromBody] LogOnViewModel model) { string fullName = string.Empty; System.Net.HttpStatusCode statusCode = System.Net.HttpStatusCode.OK; var exceptionMsg = string.Empty; var encryptionKey = string.Empty; if (_constantService.TryGetValue <string>("EncryptionKey", out encryptionKey)) { string serverEncryptedKey = model.CaptchaCode + "-" + encryptionKey; serverEncryptedKey = EncryptionUtil.Sha1Util.Sha1HashString(serverEncryptedKey); if (serverEncryptedKey == model.HiddenId) { if (ModelState.IsValid) { //string newUserName; //if (AuthorizeWithDomain(model.UserName, out newUserName)) //if(!string.IsNullOrEmpty( model.Domain)) //{ //string domain = _constantService.All().FirstOrDefault(r => // r.Key == "DomainName")?.Value?.Trim(); //if (String.IsNullOrWhiteSpace(domain)) //{ // statusCode = System.Net.HttpStatusCode.BadRequest; // _constantService.TryGetValue<string>("DomainNotDefined", out exceptionMsg); // ModelState.AddModelError("UserIsNotValid", exceptionMsg); // return Request.CreateErrorResponse(statusCode, ModelState); //} //List<string> allowedRoles = _constantService.All().FirstOrDefault(r => // r.Key == "AllowedRolesForDomainUsers")?.Value?.Split(',').Where(r => !String.IsNullOrWhiteSpace(r.Trim())).ToList(); //if (allowedRoles == null || allowedRoles.Count == 0) //{ // statusCode = System.Net.HttpStatusCode.BadRequest; // _constantService.TryGetValue<string>("NoRoleIsNotAllowed", out exceptionMsg); // ModelState.AddModelError("UserIsNotValid", exceptionMsg); // return Request.CreateErrorResponse(statusCode, ModelState); //} //List<string> userRoles; //if (_domainAuthenticationService.Logon(model.UserName, model.Password, model.Domain, out fullName, out userRoles)) //{ //if (!allowedRoles.Any(r => userRoles.Contains(r.Trim().ToUpper()))) //{ // statusCode = System.Net.HttpStatusCode.BadRequest; // _constantService.TryGetValue<string>("UserIsNotInPermittedRole", out exceptionMsg); // ModelState.AddModelError("UserIsNotValid", exceptionMsg); // return Request.CreateErrorResponse(statusCode, ModelState); //} // } // else // { // statusCode = System.Net.HttpStatusCode.BadRequest; // _constantService.TryGetValue<string>("UserIsNotExistInDomain", out exceptionMsg); // ModelState.AddModelError("UserIsNotValid", exceptionMsg); // return Request.CreateErrorResponse(statusCode, ModelState); // } //} if (_membershipService.ValidateUser(model.UserName, model.Password) && _userService.HasAdminRecord()) { //Check User Is Valid or Not... if (!_userService.IsUserActive(model.UserName)) { statusCode = System.Net.HttpStatusCode.BadRequest; _constantService.TryGetValue <string>("UserIsNotActive", out exceptionMsg); ModelState.AddModelError("UserIsNotValid", exceptionMsg); return(Request.CreateErrorResponse(statusCode, ModelState)); } var modifiedUserName = model.UserName.CorrectPersianChars(); UserProfile userProfile = _userProfileService.Filter(profile => profile.UserName.ToLower().Equals(modifiedUserName.ToLower())).FirstOrDefault(); _formsService.SignIn(userProfile, model.RememberMe, true); if (userProfile != null) { var user = userProfile.User; fullName = string.Format("{0} {1}", user.FName, user.LName); //TODO: please uncomment later // AddRecordToUserLog(user); } } else { statusCode = System.Net.HttpStatusCode.BadRequest; _constantService.TryGetValue <string>("IncorrectUserNameOrPassword", out exceptionMsg); ModelState.AddModelError("wrongPassOrUsr", exceptionMsg); return(Request.CreateErrorResponse(statusCode, ModelState)); } } } else { statusCode = System.Net.HttpStatusCode.BadRequest; _constantService.TryGetValue <string>("IncorrectSecurityCode", out exceptionMsg); ModelState.AddModelError("wrongCaptchaCode", exceptionMsg); return(Request.CreateErrorResponse(statusCode, ModelState)); } } else { statusCode = System.Net.HttpStatusCode.BadRequest; ModelState.AddModelError("encryptionKey", "there is no encryptionKey"); return(Request.CreateErrorResponse(statusCode, ModelState)); } return(Request.CreateResponse(statusCode, new { fullName = fullName, url = ConfigurationManager.AppSettings["RedirectUrlAfterLogin"] })); }
//This method is custom written to save one and only one attachment from a UCM response. It only works for text files. To work with binary files it needs to be enhanced private void SendRequestSaveToFile(string packet, string fileName) { //httppost for web objects // create the web request with the url to the web service HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(ucmEndpoint); httpReq.Headers.Add("SOAPAction: \"\""); httpReq.ContentType = "text/xml;charset=UTF-8"; httpReq.Accept = "text/xml"; httpReq.Method = "POST"; // add your credentials to the HttpWebRequest //httpReq.Credentials = new NetworkCredential(stUserID, stPswd); httpReq.Credentials = new NetworkCredential(userName, password); // Build XML request XmlDocument oRequest = new XmlDocument(); oRequest.LoadXml(packet); // Setup the Stream Stream oReqStream = httpReq.GetRequestStream(); oRequest.Save(oReqStream); oReqStream.Close(); // To avoid Cert warnings System.Net.ServicePointManager.ServerCertificateValidationCallback = (senderX, certificate, chain, sslPolicyErrors) => { return(true); }; // Send the request & get response WebResponse response = httpReq.GetResponse(); try { HttpWebResponse oTempResponse = (HttpWebResponse)response; System.Net.HttpStatusCode oStatusCode = oTempResponse.StatusCode; int iLoop = 1; // If we're not OK, try again 3 more times while (oStatusCode != HttpStatusCode.OK && iLoop < 3) { // Delay 2 minutes (120 milliseconds) and try again... System.Threading.Thread.Sleep(120000); // Store new values iLoop++; response = httpReq.GetResponse(); oTempResponse = (HttpWebResponse)response; oStatusCode = oTempResponse.StatusCode; } // If we eventually got something, process it. if (oStatusCode == HttpStatusCode.OK) { if (oTempResponse.ContentType.Contains("multipart")) { if (File.Exists(fileName)) { File.Delete(fileName); } using (StreamWriter swOut = new StreamWriter(fileName, false)) { using (StreamReader rd = new StreamReader(response.GetResponseStream())) { int messagePart = 0; while (rd.EndOfStream == false) { string line = rd.ReadLine(); if (line.StartsWith("------=")) { messagePart++; } else { if (messagePart == 2) { if (line.StartsWith("Content-ID:")) { line = rd.ReadLine(); //Next line is blank, just move past it string lastLine = null; while (true) { line = rd.ReadLine(); if (line == null || line.StartsWith("------=")) //End of attachment { messagePart++; break; } if (lastLine != null) { swOut.WriteLine(lastLine); } lastLine = line; } } } } } } swOut.Close(); } } else { throw new Exception("Bad response received: Expected multipart ContentType from request: " + packet); } } else { throw new Exception("Bad response received: '" + oTempResponse.StatusCode.ToString() + "' from request: " + packet); } } finally { if (response != null) { ((IDisposable)response).Dispose(); } } }
public Response(System.Net.HttpStatusCode code, string data) { Code = code; Data = data; }
protected Exception CreateException(System.Net.HttpStatusCode statusCode, string responseBody, object errorObject, CallContext context) { if (errorObject is PaymentErrorResponse && ((PaymentErrorResponse)errorObject).PaymentResult != null) { return(new DeclinedPaymentException(statusCode, responseBody, (PaymentErrorResponse)errorObject)); } if (errorObject is PayoutErrorResponse && ((PayoutErrorResponse)errorObject).PayoutResult != null) { return(new DeclinedPayoutException(statusCode, responseBody, (PayoutErrorResponse)errorObject)); } if (errorObject is RefundErrorResponse && ((RefundErrorResponse)errorObject).RefundResult != null) { return(new DeclinedRefundException(statusCode, responseBody, (RefundErrorResponse)errorObject)); } string errorId; IList <APIError> errors; if (errorObject is PaymentErrorResponse) { PaymentErrorResponse paymentErrorResponse = (PaymentErrorResponse)errorObject; errorId = paymentErrorResponse.ErrorId; errors = paymentErrorResponse.Errors; } else if (errorObject is PayoutErrorResponse) { PayoutErrorResponse payoutErrorResponse = (PayoutErrorResponse)errorObject; errorId = payoutErrorResponse.ErrorId; errors = payoutErrorResponse.Errors; } else if (errorObject is RefundErrorResponse) { RefundErrorResponse refundErrorResponse = (RefundErrorResponse)errorObject; errorId = refundErrorResponse.ErrorId; errors = refundErrorResponse.Errors; } else if (errorObject is ErrorResponse) { ErrorResponse errorResponse = (ErrorResponse)errorObject; errorId = errorResponse.ErrorId; errors = errorResponse.Errors; } else { throw new ArgumentException("unsupported error object type: " + errorObject.GetType().ToString()); } switch (statusCode) { case HttpStatusCode.BadRequest: return(new ValidationException(statusCode, responseBody, errorId, errors)); case HttpStatusCode.Forbidden: return(new AuthorizationException(statusCode, responseBody, errorId, errors)); case HttpStatusCode.NotFound: return(new ReferenceException(statusCode, responseBody, errorId, errors)); case HttpStatusCode.Conflict: if (IsIdempotenceError(errors, context)) { string idempotenceKey = context.IdempotenceKey; long? idempotenceRequestTimestamp = context.IdempotenceRequestTimestamp; return(new IdempotenceException(idempotenceKey, idempotenceRequestTimestamp, statusCode, responseBody, errorId, errors)); } return(new ReferenceException(statusCode, responseBody, errorId, errors)); case HttpStatusCode.Gone: return(new ReferenceException(statusCode, responseBody, errorId, errors)); case HttpStatusCode.InternalServerError: return(new GlobalCollectException(statusCode, responseBody, errorId, errors)); case HttpStatusCode.BadGateway: return(new GlobalCollectException(statusCode, responseBody, errorId, errors)); case HttpStatusCode.ServiceUnavailable: return(new GlobalCollectException(statusCode, responseBody, errorId, errors)); default: return(new ApiException(statusCode, responseBody, errorId, errors)); } }
public APIResponse(T data, HttpStatusCode statusCode, string errorData = null) { this.StatusCode = statusCode; this.Data = data; this.ErrorData = errorData; }
/// <summary> /// Initialized a PortalException with a message, exception and a caller specificed Http Status Code /// </summary> /// <param name="message">The message that may be displayed in the UI</param> /// <param name="innerException">The inner exception, useful for logging scenario's</param> /// <param name="httpStatusCode">The HTTP Status code to reutrn to the caller</param> public PortalException(string message, Exception innerException, System.Net.HttpStatusCode httpStatusCode) : base(message, innerException) { this.httpStatusCode = httpStatusCode; }
public void SetStatus(System.Net.HttpStatusCode httpStatusCode) { this.Status = httpStatusCode; }
public static StatusCodeWebServerResponse StatusCode(System.Net.HttpStatusCode code, string text = "") => StatusCodeWebServerResponse.FromStatusCode(code, text);
/// <summary> /// Provides a pageable list of all items that are backed up within a vault. /// </summary> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='skipToken'> /// skipToken Filter. /// </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 <IPage <ProtectedItemResource> > > ListWithHttpMessagesAsync(string vaultName, string resourceGroupName, ODataQuery <ProtectedItemQueryObject> odataQuery = default(ODataQuery <ProtectedItemQueryObject>), string skipToken = default(string), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (vaultName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "vaultName"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2020-10-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("odataQuery", odataQuery); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("vaultName", vaultName); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("skipToken", skipToken); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", 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.RecoveryServices/vaults/{vaultName}/backupProtectedItems").ToString(); _url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List <string> _queryParameters = new List <string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (skipToken != null) { _queryParameters.Add(string.Format("$skipToken={0}", System.Uri.EscapeDataString(skipToken))); } 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 (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); } System.Net.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 <IPage <ProtectedItemResource> >(); _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 <Page <ProtectedItemResource> >(_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 override void GetError(string errorIdentifier, object[] messageParameters, out System.Net.HttpStatusCode errorCode, out string message) { base.GetError(errorIdentifier, messageParameters, out errorCode, out message); }
/// <summary> /// Retrieve a list of hybrid runbook worker groups. /// <see href="http://aka.ms/azureautomationsdk/hybridrunbookworkergroupoperations" /> /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </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 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 <IPage <HybridRunbookWorkerGroup> > > ListByAutomationAccountNextWithHttpMessagesAsync(string nextPageLink, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByAutomationAccountNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List <string> _queryParameters = new List <string>(); 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 (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); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { 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 <IPage <HybridRunbookWorkerGroup> >(); _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 <Page1 <HybridRunbookWorkerGroup> >(_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 override void GetError(string identifier, out System.Net.HttpStatusCode errorCode, out string message) { base.GetError(identifier, out errorCode, out message); }
public override void Get(string identifier, out System.Net.HttpStatusCode code, out string message) { base.Get(identifier, out code, out message); }
public override bool VetStatusCode(System.Net.HttpStatusCode candidateStatusCode) { return(base.VetStatusCode(candidateStatusCode)); }
public override void GetError <T>(System.Net.HttpStatusCode statusCode, T t, out string message) { base.GetError <T>(statusCode, t, out message); }
/// <summary> /// Constructs an instance of the <see cref="UrlCrawlData"/> class and initializes /// it with the default values. /// </summary> public UrlCrawlData() { url=new InternetUrlToCrawl(); updated=false; redirected=false; redirectedFlagRobots = false; redirectedFlagDomain = DomainFlagValue.MustVisit; redirectedPriority = 255; httpStatusCode=HttpStatusCode.OK; data=String.Empty; timeStamp=DateTime.UtcNow; retrievalTime=0; outLinks=null;//new ArrayList(); }